From 75dd710c11752b2126ca7797a5d89329c951cb45 Mon Sep 17 00:00:00 2001 From: Danish Arora Date: Tue, 9 Sep 2025 17:41:33 +0530 Subject: [PATCH] chore: setup workspace --- .gitignore | 1 + dist/assets/add-B1b4Ty-5.js | 15 + dist/assets/all-wallets-DKy0zRrU.js | 6 + dist/assets/app-store-qA41k1iG.js | 17 + dist/assets/apple-B3teXytZ.js | 18 + dist/assets/arrow-bottom-C7NMSF0g.js | 8 + dist/assets/arrow-bottom-circle-Bo8O7JgA.js | 11 + dist/assets/arrow-left-DFwUccrs.js | 8 + dist/assets/arrow-right-2iACcb0n.js | 8 + dist/assets/arrow-top-BtzNMuue.js | 8 + dist/assets/bank-DPwf5DsI.js | 14 + dist/assets/bin-BshwV3dZ.js | 4 + dist/assets/bitcoin-M-S4Gfjc.js | 13 + dist/assets/browser-CC3et0uk.js | 14 + dist/assets/card-9KwzYBwi.js | 14 + dist/assets/ccip-CSxoh1Sw.js | 1 + dist/assets/checkmark-CDGh-jbz.js | 11 + dist/assets/checkmark-bold-DBpjkRrv.js | 8 + dist/assets/chevron-bottom-B9wx_mOd.js | 8 + dist/assets/chevron-left-nYdEcmRU.js | 8 + dist/assets/chevron-right-BIvCTfn4.js | 8 + dist/assets/chevron-top-D_T8NmSU.js | 8 + dist/assets/chrome-store-DjKACh-G.js | 61 + dist/assets/circle-CMRf11j6.js | 4 + dist/assets/clock-Bu8fqLqw.js | 8 + dist/assets/close-DkOqA3XA.js | 8 + dist/assets/coinPlaceholder-Bog9viJQ.js | 8 + dist/assets/compass-k9qpYhtB.js | 8 + dist/assets/copy-CrR_vPRD.js | 15 + dist/assets/cursor-B5zA10jJ.js | 3 + dist/assets/cursor-transparent-8xgUPsqN.js | 12 + dist/assets/desktop-CW7qCBPc.js | 9 + dist/assets/disconnect-DzbPXgkg.js | 8 + dist/assets/discord-CPs1H_Zj.js | 17 + dist/assets/email-OHUMhOV6.js | 237 + dist/assets/embedded-wallet-Axuw_fFm.js | 194 + dist/assets/ethereum-pDlrEry5.js | 10 + dist/assets/etherscan-yowPVDyy.js | 6 + dist/assets/exclamation-triangle-ByL4C-X2.js | 4 + dist/assets/extension-V_MQztIO.js | 8 + dist/assets/external-link-D5nUBuK8.js | 8 + dist/assets/facebook-IzGdkHXn.js | 26 + dist/assets/farcaster-CQ1ZnK9M.js | 12 + dist/assets/filters-CENUgXu3.js | 8 + dist/assets/github-DB7o3FYw.js | 18 + dist/assets/google-BQasw2Dk.js | 18 + dist/assets/hashTypedData-D0Cx__mD.js | 1 + dist/assets/help-circle-VyIXOAlM.js | 12 + dist/assets/hooks.module-Dz_XB4AG.js | 1 + dist/assets/id-Dqw-Wgu3.js | 12 + dist/assets/image-Dd9GhBqt.js | 4 + dist/assets/index-4N_q9Ijm.js | 2 + dist/assets/index-BGGOaaWA.js | 143 + dist/assets/index-BXHa4upX.css | 1 + dist/assets/index-COonna6N.js | 1 + dist/assets/index-Cl4M8jG7.js | 1 + dist/assets/index-CqL7mnh0.js | 2 + dist/assets/index-Cr5N_0pd.js | 8205 +++++++++++++++++ dist/assets/index-DCwOSe4Q.js | 8 + dist/assets/index-DUeQylCA.js | 35 + dist/assets/index-Dl0F4g05.js | 7 + dist/assets/index-sYri9oP4.js | 1 + dist/assets/info-BzF0mPAp.js | 3 + dist/assets/info-circle-CXT71X33.js | 12 + dist/assets/lightbulb-DXUATdFd.js | 3 + dist/assets/mail-D5Kz7lp0.js | 8 + dist/assets/mobile-iSKvjbUf.js | 9 + dist/assets/more-C8OTKC0g.js | 11 + dist/assets/network-placeholder-C3ZqCyor.js | 14 + dist/assets/nftPlaceholder-1Liwzove.js | 8 + dist/assets/off-DkfF0_gL.js | 4 + dist/assets/onramp-BiRdNRiA.js | 468 + dist/assets/play-store-D-_ekw15.js | 32 + dist/assets/plus-DaZ9pOJ-.js | 13 + dist/assets/qr-code-zSuzYj6q.js | 6 + dist/assets/receive-dL28-83Q.js | 83 + dist/assets/recycle-horizontal-B85mmaoN.js | 9 + dist/assets/refresh-CsELgs90.js | 8 + dist/assets/reown-logo-CHoXyyWe.js | 12 + dist/assets/search-DCC0JOe_.js | 8 + dist/assets/secp256k1-BjJYwyg8.js | 1 + dist/assets/send-DbOL9rGQ.js | 15 + dist/assets/send-Ncb2jADE.js | 535 ++ dist/assets/socials-DtOZCIFp.js | 262 + dist/assets/solana-wnPogKuz.js | 13 + dist/assets/swapHorizontal-iQa05UE_.js | 8 + dist/assets/swapHorizontalBold-CxDNxTSc.js | 8 + dist/assets/swapHorizontalMedium-KeWOduSV.js | 16 + .../swapHorizontalRoundedBold-BKa1b4V9.js | 8 + dist/assets/swapVertical-BkcJfrl6.js | 8 + dist/assets/swaps-2zeCrlxq.js | 976 ++ dist/assets/telegram-APKTNwpu.js | 16 + dist/assets/three-dots-8jGyRbgm.js | 5 + dist/assets/transactions-QUhMMh8E.js | 16 + dist/assets/twitch-BUKiRB8R.js | 18 + dist/assets/twitterIcon-CzR_RgAK.js | 6 + dist/assets/ui-CTdGiFlJ.js | 246 + dist/assets/user-BSr3AuAa.js | 3 + dist/assets/verify-BjYfOgD5.js | 8 + dist/assets/verify-filled-C34Ypr-X.js | 8 + dist/assets/w3m-modal-BNMiKa3F.js | 467 + dist/assets/wallet-B7rYWpGd.js | 8 + dist/assets/wallet-placeholder-BUQhm8ne.js | 14 + dist/assets/walletconnect-DhIwJMgu.js | 30 + dist/assets/warning-circle-Dwz2WWdH.js | 12 + dist/assets/x-C3LRqiud.js | 12 + dist/assets/x-mark-DqeqBMH2.js | 3 + dist/favicon.ico | Bin 0 -> 1150 bytes dist/index.html | 28 + dist/placeholder.svg | 1 + dist/robots.txt | 14 + .../core/dist/database/LocalDatabase.d.ts | 128 + .../core/dist/database/LocalDatabase.d.ts.map | 1 + packages/core/dist/database/LocalDatabase.js | 453 + .../core/dist/database/LocalDatabase.js.map | 1 + packages/core/dist/database/schema.d.ts | 22 + packages/core/dist/database/schema.d.ts.map | 1 + packages/core/dist/database/schema.js | 81 + packages/core/dist/database/schema.js.map | 1 + packages/core/dist/delegation/crypto.d.ts | 48 + packages/core/dist/delegation/crypto.d.ts.map | 1 + packages/core/dist/delegation/crypto.js | 89 + packages/core/dist/delegation/crypto.js.map | 1 + packages/core/dist/delegation/index.d.ts | 48 + packages/core/dist/delegation/index.d.ts.map | 1 + packages/core/dist/delegation/index.js | 184 + packages/core/dist/delegation/index.js.map | 1 + packages/core/dist/delegation/storage.d.ts | 16 + .../core/dist/delegation/storage.d.ts.map | 1 + packages/core/dist/delegation/storage.js | 46 + packages/core/dist/delegation/storage.js.map | 1 + packages/core/dist/delegation/types.d.ts | 29 + packages/core/dist/delegation/types.d.ts.map | 1 + packages/core/dist/delegation/types.js | 2 + packages/core/dist/delegation/types.js.map | 1 + packages/core/dist/forum/ForumActions.d.ts | 65 + .../core/dist/forum/ForumActions.d.ts.map | 1 + packages/core/dist/forum/ForumActions.js | 416 + packages/core/dist/forum/ForumActions.js.map | 1 + .../core/dist/forum/RelevanceCalculator.d.ts | 71 + .../dist/forum/RelevanceCalculator.d.ts.map | 1 + .../core/dist/forum/RelevanceCalculator.js | 250 + .../dist/forum/RelevanceCalculator.js.map | 1 + packages/core/dist/forum/transformers.d.ts | 14 + .../core/dist/forum/transformers.d.ts.map | 1 + packages/core/dist/forum/transformers.js | 186 + packages/core/dist/forum/transformers.js.map | 1 + packages/core/dist/index.d.ts | 15 + packages/core/dist/index.d.ts.map | 1 + packages/core/dist/index.js | 23 + packages/core/dist/index.js.map | 1 + .../core/dist/services/BookmarkService.d.ts | 57 + .../dist/services/BookmarkService.d.ts.map | 1 + .../core/dist/services/BookmarkService.js | 127 + .../core/dist/services/BookmarkService.js.map | 1 + .../core/dist/services/MessageService.d.ts | 30 + .../dist/services/MessageService.d.ts.map | 1 + packages/core/dist/services/MessageService.js | 78 + .../core/dist/services/MessageService.js.map | 1 + .../core/dist/services/Ordinal/index.d.ts | 10 + .../core/dist/services/Ordinal/index.d.ts.map | 1 + packages/core/dist/services/Ordinal/index.js | 39 + .../core/dist/services/Ordinal/index.js.map | 1 + .../core/dist/services/Ordinal/types.d.ts | 25 + .../core/dist/services/Ordinal/types.d.ts.map | 1 + packages/core/dist/services/Ordinal/types.js | 2 + .../core/dist/services/Ordinal/types.js.map | 1 + .../dist/services/UserIdentityService.d.ts | 74 + .../services/UserIdentityService.d.ts.map | 1 + .../core/dist/services/UserIdentityService.js | 354 + .../dist/services/UserIdentityService.js.map | 1 + packages/core/dist/services/index.d.ts | 2 + packages/core/dist/services/index.d.ts.map | 1 + packages/core/dist/services/index.js | 2 + packages/core/dist/services/index.js.map | 1 + packages/core/dist/types/browser.d.ts | 53 + packages/core/dist/types/browser.d.ts.map | 1 + packages/core/dist/types/browser.js | 16 + packages/core/dist/types/browser.js.map | 1 + packages/core/dist/types/forum.d.ts | 133 + packages/core/dist/types/forum.d.ts.map | 1 + packages/core/dist/types/forum.js | 9 + packages/core/dist/types/forum.js.map | 1 + packages/core/dist/types/identity.d.ts | 31 + packages/core/dist/types/identity.d.ts.map | 1 + packages/core/dist/types/identity.js | 12 + packages/core/dist/types/identity.js.map | 1 + packages/core/dist/types/index.d.ts | 2 + packages/core/dist/types/index.d.ts.map | 1 + packages/core/dist/types/index.js | 2 + packages/core/dist/types/index.js.map | 1 + packages/core/dist/types/waku.d.ts | 138 + packages/core/dist/types/waku.d.ts.map | 1 + packages/core/dist/types/waku.js | 13 + packages/core/dist/types/waku.js.map | 1 + packages/core/dist/utils.d.ts | 4 + packages/core/dist/utils.d.ts.map | 1 + packages/core/dist/utils.js | 16 + packages/core/dist/utils.js.map | 1 + .../core/dist/utils/MessageValidator.d.ts | 85 + .../core/dist/utils/MessageValidator.d.ts.map | 1 + packages/core/dist/utils/MessageValidator.js | 279 + .../core/dist/utils/MessageValidator.js.map | 1 + packages/core/dist/utils/sorting.d.ts | 23 + packages/core/dist/utils/sorting.d.ts.map | 1 + packages/core/dist/utils/sorting.js | 52 + packages/core/dist/utils/sorting.js.map | 1 + packages/core/dist/utils/urlLoads.d.ts | 5 + packages/core/dist/utils/urlLoads.d.ts.map | 1 + packages/core/dist/utils/urlLoads.js | 20 + packages/core/dist/utils/urlLoads.js.map | 1 + packages/core/dist/waku/CodecManager.d.ts | 34 + packages/core/dist/waku/CodecManager.d.ts.map | 1 + packages/core/dist/waku/CodecManager.js | 64 + packages/core/dist/waku/CodecManager.js.map | 1 + packages/core/dist/waku/constants.d.ts | 13 + packages/core/dist/waku/constants.d.ts.map | 1 + packages/core/dist/waku/constants.js | 17 + packages/core/dist/waku/constants.js.map | 1 + .../dist/waku/core/ReliableMessaging.d.ts | 21 + .../dist/waku/core/ReliableMessaging.d.ts.map | 1 + .../core/dist/waku/core/ReliableMessaging.js | 83 + .../dist/waku/core/ReliableMessaging.js.map | 1 + .../core/dist/waku/core/WakuNodeManager.d.ts | 19 + .../dist/waku/core/WakuNodeManager.d.ts.map | 1 + .../core/dist/waku/core/WakuNodeManager.js | 74 + .../dist/waku/core/WakuNodeManager.js.map | 1 + packages/core/dist/waku/index.d.ts | 25 + packages/core/dist/waku/index.d.ts.map | 1 + packages/core/dist/waku/index.js | 98 + packages/core/dist/waku/index.js.map | 1 + packages/core/dist/waku/network.d.ts | 11 + packages/core/dist/waku/network.d.ts.map | 1 + packages/core/dist/waku/network.js | 91 + packages/core/dist/waku/network.js.map | 1 + .../dist/waku/services/MessageService.d.ts | 22 + .../waku/services/MessageService.d.ts.map | 1 + .../core/dist/waku/services/MessageService.js | 80 + .../dist/waku/services/MessageService.js.map | 1 + packages/core/dist/wallet/config.d.ts | 6 + packages/core/dist/wallet/config.d.ts.map | 1 + packages/core/dist/wallet/config.js | 41 + packages/core/dist/wallet/config.js.map | 1 + packages/core/dist/wallet/index.d.ts | 75 + packages/core/dist/wallet/index.d.ts.map | 1 + packages/core/dist/wallet/index.js | 209 + packages/core/dist/wallet/index.js.map | 1 + packages/core/dist/wallet/types.d.ts | 12 + packages/core/dist/wallet/types.d.ts.map | 1 + packages/core/dist/wallet/types.js | 2 + packages/core/dist/wallet/types.js.map | 1 + packages/react/dist/index.d.ts | 2 + packages/react/dist/index.d.ts.map | 1 + packages/react/dist/index.js | 3 + packages/react/dist/index.js.map | 1 + 255 files changed, 17786 insertions(+) create mode 100644 .gitignore create mode 100644 dist/assets/add-B1b4Ty-5.js create mode 100644 dist/assets/all-wallets-DKy0zRrU.js create mode 100644 dist/assets/app-store-qA41k1iG.js create mode 100644 dist/assets/apple-B3teXytZ.js create mode 100644 dist/assets/arrow-bottom-C7NMSF0g.js create mode 100644 dist/assets/arrow-bottom-circle-Bo8O7JgA.js create mode 100644 dist/assets/arrow-left-DFwUccrs.js create mode 100644 dist/assets/arrow-right-2iACcb0n.js create mode 100644 dist/assets/arrow-top-BtzNMuue.js create mode 100644 dist/assets/bank-DPwf5DsI.js create mode 100644 dist/assets/bin-BshwV3dZ.js create mode 100644 dist/assets/bitcoin-M-S4Gfjc.js create mode 100644 dist/assets/browser-CC3et0uk.js create mode 100644 dist/assets/card-9KwzYBwi.js create mode 100644 dist/assets/ccip-CSxoh1Sw.js create mode 100644 dist/assets/checkmark-CDGh-jbz.js create mode 100644 dist/assets/checkmark-bold-DBpjkRrv.js create mode 100644 dist/assets/chevron-bottom-B9wx_mOd.js create mode 100644 dist/assets/chevron-left-nYdEcmRU.js create mode 100644 dist/assets/chevron-right-BIvCTfn4.js create mode 100644 dist/assets/chevron-top-D_T8NmSU.js create mode 100644 dist/assets/chrome-store-DjKACh-G.js create mode 100644 dist/assets/circle-CMRf11j6.js create mode 100644 dist/assets/clock-Bu8fqLqw.js create mode 100644 dist/assets/close-DkOqA3XA.js create mode 100644 dist/assets/coinPlaceholder-Bog9viJQ.js create mode 100644 dist/assets/compass-k9qpYhtB.js create mode 100644 dist/assets/copy-CrR_vPRD.js create mode 100644 dist/assets/cursor-B5zA10jJ.js create mode 100644 dist/assets/cursor-transparent-8xgUPsqN.js create mode 100644 dist/assets/desktop-CW7qCBPc.js create mode 100644 dist/assets/disconnect-DzbPXgkg.js create mode 100644 dist/assets/discord-CPs1H_Zj.js create mode 100644 dist/assets/email-OHUMhOV6.js create mode 100644 dist/assets/embedded-wallet-Axuw_fFm.js create mode 100644 dist/assets/ethereum-pDlrEry5.js create mode 100644 dist/assets/etherscan-yowPVDyy.js create mode 100644 dist/assets/exclamation-triangle-ByL4C-X2.js create mode 100644 dist/assets/extension-V_MQztIO.js create mode 100644 dist/assets/external-link-D5nUBuK8.js create mode 100644 dist/assets/facebook-IzGdkHXn.js create mode 100644 dist/assets/farcaster-CQ1ZnK9M.js create mode 100644 dist/assets/filters-CENUgXu3.js create mode 100644 dist/assets/github-DB7o3FYw.js create mode 100644 dist/assets/google-BQasw2Dk.js create mode 100644 dist/assets/hashTypedData-D0Cx__mD.js create mode 100644 dist/assets/help-circle-VyIXOAlM.js create mode 100644 dist/assets/hooks.module-Dz_XB4AG.js create mode 100644 dist/assets/id-Dqw-Wgu3.js create mode 100644 dist/assets/image-Dd9GhBqt.js create mode 100644 dist/assets/index-4N_q9Ijm.js create mode 100644 dist/assets/index-BGGOaaWA.js create mode 100644 dist/assets/index-BXHa4upX.css create mode 100644 dist/assets/index-COonna6N.js create mode 100644 dist/assets/index-Cl4M8jG7.js create mode 100644 dist/assets/index-CqL7mnh0.js create mode 100644 dist/assets/index-Cr5N_0pd.js create mode 100644 dist/assets/index-DCwOSe4Q.js create mode 100644 dist/assets/index-DUeQylCA.js create mode 100644 dist/assets/index-Dl0F4g05.js create mode 100644 dist/assets/index-sYri9oP4.js create mode 100644 dist/assets/info-BzF0mPAp.js create mode 100644 dist/assets/info-circle-CXT71X33.js create mode 100644 dist/assets/lightbulb-DXUATdFd.js create mode 100644 dist/assets/mail-D5Kz7lp0.js create mode 100644 dist/assets/mobile-iSKvjbUf.js create mode 100644 dist/assets/more-C8OTKC0g.js create mode 100644 dist/assets/network-placeholder-C3ZqCyor.js create mode 100644 dist/assets/nftPlaceholder-1Liwzove.js create mode 100644 dist/assets/off-DkfF0_gL.js create mode 100644 dist/assets/onramp-BiRdNRiA.js create mode 100644 dist/assets/play-store-D-_ekw15.js create mode 100644 dist/assets/plus-DaZ9pOJ-.js create mode 100644 dist/assets/qr-code-zSuzYj6q.js create mode 100644 dist/assets/receive-dL28-83Q.js create mode 100644 dist/assets/recycle-horizontal-B85mmaoN.js create mode 100644 dist/assets/refresh-CsELgs90.js create mode 100644 dist/assets/reown-logo-CHoXyyWe.js create mode 100644 dist/assets/search-DCC0JOe_.js create mode 100644 dist/assets/secp256k1-BjJYwyg8.js create mode 100644 dist/assets/send-DbOL9rGQ.js create mode 100644 dist/assets/send-Ncb2jADE.js create mode 100644 dist/assets/socials-DtOZCIFp.js create mode 100644 dist/assets/solana-wnPogKuz.js create mode 100644 dist/assets/swapHorizontal-iQa05UE_.js create mode 100644 dist/assets/swapHorizontalBold-CxDNxTSc.js create mode 100644 dist/assets/swapHorizontalMedium-KeWOduSV.js create mode 100644 dist/assets/swapHorizontalRoundedBold-BKa1b4V9.js create mode 100644 dist/assets/swapVertical-BkcJfrl6.js create mode 100644 dist/assets/swaps-2zeCrlxq.js create mode 100644 dist/assets/telegram-APKTNwpu.js create mode 100644 dist/assets/three-dots-8jGyRbgm.js create mode 100644 dist/assets/transactions-QUhMMh8E.js create mode 100644 dist/assets/twitch-BUKiRB8R.js create mode 100644 dist/assets/twitterIcon-CzR_RgAK.js create mode 100644 dist/assets/ui-CTdGiFlJ.js create mode 100644 dist/assets/user-BSr3AuAa.js create mode 100644 dist/assets/verify-BjYfOgD5.js create mode 100644 dist/assets/verify-filled-C34Ypr-X.js create mode 100644 dist/assets/w3m-modal-BNMiKa3F.js create mode 100644 dist/assets/wallet-B7rYWpGd.js create mode 100644 dist/assets/wallet-placeholder-BUQhm8ne.js create mode 100644 dist/assets/walletconnect-DhIwJMgu.js create mode 100644 dist/assets/warning-circle-Dwz2WWdH.js create mode 100644 dist/assets/x-C3LRqiud.js create mode 100644 dist/assets/x-mark-DqeqBMH2.js create mode 100644 dist/favicon.ico create mode 100644 dist/index.html create mode 100644 dist/placeholder.svg create mode 100644 dist/robots.txt create mode 100644 packages/core/dist/database/LocalDatabase.d.ts create mode 100644 packages/core/dist/database/LocalDatabase.d.ts.map create mode 100644 packages/core/dist/database/LocalDatabase.js create mode 100644 packages/core/dist/database/LocalDatabase.js.map create mode 100644 packages/core/dist/database/schema.d.ts create mode 100644 packages/core/dist/database/schema.d.ts.map create mode 100644 packages/core/dist/database/schema.js create mode 100644 packages/core/dist/database/schema.js.map create mode 100644 packages/core/dist/delegation/crypto.d.ts create mode 100644 packages/core/dist/delegation/crypto.d.ts.map create mode 100644 packages/core/dist/delegation/crypto.js create mode 100644 packages/core/dist/delegation/crypto.js.map create mode 100644 packages/core/dist/delegation/index.d.ts create mode 100644 packages/core/dist/delegation/index.d.ts.map create mode 100644 packages/core/dist/delegation/index.js create mode 100644 packages/core/dist/delegation/index.js.map create mode 100644 packages/core/dist/delegation/storage.d.ts create mode 100644 packages/core/dist/delegation/storage.d.ts.map create mode 100644 packages/core/dist/delegation/storage.js create mode 100644 packages/core/dist/delegation/storage.js.map create mode 100644 packages/core/dist/delegation/types.d.ts create mode 100644 packages/core/dist/delegation/types.d.ts.map create mode 100644 packages/core/dist/delegation/types.js create mode 100644 packages/core/dist/delegation/types.js.map create mode 100644 packages/core/dist/forum/ForumActions.d.ts create mode 100644 packages/core/dist/forum/ForumActions.d.ts.map create mode 100644 packages/core/dist/forum/ForumActions.js create mode 100644 packages/core/dist/forum/ForumActions.js.map create mode 100644 packages/core/dist/forum/RelevanceCalculator.d.ts create mode 100644 packages/core/dist/forum/RelevanceCalculator.d.ts.map create mode 100644 packages/core/dist/forum/RelevanceCalculator.js create mode 100644 packages/core/dist/forum/RelevanceCalculator.js.map create mode 100644 packages/core/dist/forum/transformers.d.ts create mode 100644 packages/core/dist/forum/transformers.d.ts.map create mode 100644 packages/core/dist/forum/transformers.js create mode 100644 packages/core/dist/forum/transformers.js.map create mode 100644 packages/core/dist/index.d.ts create mode 100644 packages/core/dist/index.d.ts.map create mode 100644 packages/core/dist/index.js create mode 100644 packages/core/dist/index.js.map create mode 100644 packages/core/dist/services/BookmarkService.d.ts create mode 100644 packages/core/dist/services/BookmarkService.d.ts.map create mode 100644 packages/core/dist/services/BookmarkService.js create mode 100644 packages/core/dist/services/BookmarkService.js.map create mode 100644 packages/core/dist/services/MessageService.d.ts create mode 100644 packages/core/dist/services/MessageService.d.ts.map create mode 100644 packages/core/dist/services/MessageService.js create mode 100644 packages/core/dist/services/MessageService.js.map create mode 100644 packages/core/dist/services/Ordinal/index.d.ts create mode 100644 packages/core/dist/services/Ordinal/index.d.ts.map create mode 100644 packages/core/dist/services/Ordinal/index.js create mode 100644 packages/core/dist/services/Ordinal/index.js.map create mode 100644 packages/core/dist/services/Ordinal/types.d.ts create mode 100644 packages/core/dist/services/Ordinal/types.d.ts.map create mode 100644 packages/core/dist/services/Ordinal/types.js create mode 100644 packages/core/dist/services/Ordinal/types.js.map create mode 100644 packages/core/dist/services/UserIdentityService.d.ts create mode 100644 packages/core/dist/services/UserIdentityService.d.ts.map create mode 100644 packages/core/dist/services/UserIdentityService.js create mode 100644 packages/core/dist/services/UserIdentityService.js.map create mode 100644 packages/core/dist/services/index.d.ts create mode 100644 packages/core/dist/services/index.d.ts.map create mode 100644 packages/core/dist/services/index.js create mode 100644 packages/core/dist/services/index.js.map create mode 100644 packages/core/dist/types/browser.d.ts create mode 100644 packages/core/dist/types/browser.d.ts.map create mode 100644 packages/core/dist/types/browser.js create mode 100644 packages/core/dist/types/browser.js.map create mode 100644 packages/core/dist/types/forum.d.ts create mode 100644 packages/core/dist/types/forum.d.ts.map create mode 100644 packages/core/dist/types/forum.js create mode 100644 packages/core/dist/types/forum.js.map create mode 100644 packages/core/dist/types/identity.d.ts create mode 100644 packages/core/dist/types/identity.d.ts.map create mode 100644 packages/core/dist/types/identity.js create mode 100644 packages/core/dist/types/identity.js.map create mode 100644 packages/core/dist/types/index.d.ts create mode 100644 packages/core/dist/types/index.d.ts.map create mode 100644 packages/core/dist/types/index.js create mode 100644 packages/core/dist/types/index.js.map create mode 100644 packages/core/dist/types/waku.d.ts create mode 100644 packages/core/dist/types/waku.d.ts.map create mode 100644 packages/core/dist/types/waku.js create mode 100644 packages/core/dist/types/waku.js.map create mode 100644 packages/core/dist/utils.d.ts create mode 100644 packages/core/dist/utils.d.ts.map create mode 100644 packages/core/dist/utils.js create mode 100644 packages/core/dist/utils.js.map create mode 100644 packages/core/dist/utils/MessageValidator.d.ts create mode 100644 packages/core/dist/utils/MessageValidator.d.ts.map create mode 100644 packages/core/dist/utils/MessageValidator.js create mode 100644 packages/core/dist/utils/MessageValidator.js.map create mode 100644 packages/core/dist/utils/sorting.d.ts create mode 100644 packages/core/dist/utils/sorting.d.ts.map create mode 100644 packages/core/dist/utils/sorting.js create mode 100644 packages/core/dist/utils/sorting.js.map create mode 100644 packages/core/dist/utils/urlLoads.d.ts create mode 100644 packages/core/dist/utils/urlLoads.d.ts.map create mode 100644 packages/core/dist/utils/urlLoads.js create mode 100644 packages/core/dist/utils/urlLoads.js.map create mode 100644 packages/core/dist/waku/CodecManager.d.ts create mode 100644 packages/core/dist/waku/CodecManager.d.ts.map create mode 100644 packages/core/dist/waku/CodecManager.js create mode 100644 packages/core/dist/waku/CodecManager.js.map create mode 100644 packages/core/dist/waku/constants.d.ts create mode 100644 packages/core/dist/waku/constants.d.ts.map create mode 100644 packages/core/dist/waku/constants.js create mode 100644 packages/core/dist/waku/constants.js.map create mode 100644 packages/core/dist/waku/core/ReliableMessaging.d.ts create mode 100644 packages/core/dist/waku/core/ReliableMessaging.d.ts.map create mode 100644 packages/core/dist/waku/core/ReliableMessaging.js create mode 100644 packages/core/dist/waku/core/ReliableMessaging.js.map create mode 100644 packages/core/dist/waku/core/WakuNodeManager.d.ts create mode 100644 packages/core/dist/waku/core/WakuNodeManager.d.ts.map create mode 100644 packages/core/dist/waku/core/WakuNodeManager.js create mode 100644 packages/core/dist/waku/core/WakuNodeManager.js.map create mode 100644 packages/core/dist/waku/index.d.ts create mode 100644 packages/core/dist/waku/index.d.ts.map create mode 100644 packages/core/dist/waku/index.js create mode 100644 packages/core/dist/waku/index.js.map create mode 100644 packages/core/dist/waku/network.d.ts create mode 100644 packages/core/dist/waku/network.d.ts.map create mode 100644 packages/core/dist/waku/network.js create mode 100644 packages/core/dist/waku/network.js.map create mode 100644 packages/core/dist/waku/services/MessageService.d.ts create mode 100644 packages/core/dist/waku/services/MessageService.d.ts.map create mode 100644 packages/core/dist/waku/services/MessageService.js create mode 100644 packages/core/dist/waku/services/MessageService.js.map create mode 100644 packages/core/dist/wallet/config.d.ts create mode 100644 packages/core/dist/wallet/config.d.ts.map create mode 100644 packages/core/dist/wallet/config.js create mode 100644 packages/core/dist/wallet/config.js.map create mode 100644 packages/core/dist/wallet/index.d.ts create mode 100644 packages/core/dist/wallet/index.d.ts.map create mode 100644 packages/core/dist/wallet/index.js create mode 100644 packages/core/dist/wallet/index.js.map create mode 100644 packages/core/dist/wallet/types.d.ts create mode 100644 packages/core/dist/wallet/types.d.ts.map create mode 100644 packages/core/dist/wallet/types.js create mode 100644 packages/core/dist/wallet/types.js.map create mode 100644 packages/react/dist/index.d.ts create mode 100644 packages/react/dist/index.d.ts.map create mode 100644 packages/react/dist/index.js create mode 100644 packages/react/dist/index.js.map diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/dist/assets/add-B1b4Ty-5.js b/dist/assets/add-B1b4Ty-5.js new file mode 100644 index 0000000..f924f01 --- /dev/null +++ b/dist/assets/add-B1b4Ty-5.js @@ -0,0 +1,15 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + `;export{o as addSvg}; diff --git a/dist/assets/all-wallets-DKy0zRrU.js b/dist/assets/all-wallets-DKy0zRrU.js new file mode 100644 index 0000000..58a17e4 --- /dev/null +++ b/dist/assets/all-wallets-DKy0zRrU.js @@ -0,0 +1,6 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + +`;export{o as allWalletsSvg}; diff --git a/dist/assets/app-store-qA41k1iG.js b/dist/assets/app-store-qA41k1iG.js new file mode 100644 index 0000000..d993001 --- /dev/null +++ b/dist/assets/app-store-qA41k1iG.js @@ -0,0 +1,17 @@ +import{b as t}from"./index-Cr5N_0pd.js";const e=t` + + + + + + + + + +`;export{e as appStoreSvg}; diff --git a/dist/assets/apple-B3teXytZ.js b/dist/assets/apple-B3teXytZ.js new file mode 100644 index 0000000..de26ff8 --- /dev/null +++ b/dist/assets/apple-B3teXytZ.js @@ -0,0 +1,18 @@ +import{b as l}from"./index-Cr5N_0pd.js";const f=l` + + + + + + + + + + + + + +`;export{f as appleSvg}; diff --git a/dist/assets/arrow-bottom-C7NMSF0g.js b/dist/assets/arrow-bottom-C7NMSF0g.js new file mode 100644 index 0000000..75909a6 --- /dev/null +++ b/dist/assets/arrow-bottom-C7NMSF0g.js @@ -0,0 +1,8 @@ +import{b as o}from"./index-Cr5N_0pd.js";const e=o` + +`;export{e as arrowBottomSvg}; diff --git a/dist/assets/arrow-bottom-circle-Bo8O7JgA.js b/dist/assets/arrow-bottom-circle-Bo8O7JgA.js new file mode 100644 index 0000000..6441e3d --- /dev/null +++ b/dist/assets/arrow-bottom-circle-Bo8O7JgA.js @@ -0,0 +1,11 @@ +import{b as C}from"./index-Cr5N_0pd.js";const e=C` + `;export{e as arrowBottomCircleSvg}; diff --git a/dist/assets/arrow-left-DFwUccrs.js b/dist/assets/arrow-left-DFwUccrs.js new file mode 100644 index 0000000..e573614 --- /dev/null +++ b/dist/assets/arrow-left-DFwUccrs.js @@ -0,0 +1,8 @@ +import{b as e}from"./index-Cr5N_0pd.js";const o=e` + +`;export{o as arrowLeftSvg}; diff --git a/dist/assets/arrow-right-2iACcb0n.js b/dist/assets/arrow-right-2iACcb0n.js new file mode 100644 index 0000000..6361cd1 --- /dev/null +++ b/dist/assets/arrow-right-2iACcb0n.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const e=l` + +`;export{e as arrowRightSvg}; diff --git a/dist/assets/arrow-top-BtzNMuue.js b/dist/assets/arrow-top-BtzNMuue.js new file mode 100644 index 0000000..54fbe97 --- /dev/null +++ b/dist/assets/arrow-top-BtzNMuue.js @@ -0,0 +1,8 @@ +import{b as o}from"./index-Cr5N_0pd.js";const e=o` + +`;export{e as arrowTopSvg}; diff --git a/dist/assets/bank-DPwf5DsI.js b/dist/assets/bank-DPwf5DsI.js new file mode 100644 index 0000000..10bba91 --- /dev/null +++ b/dist/assets/bank-DPwf5DsI.js @@ -0,0 +1,14 @@ +import{b as e}from"./index-Cr5N_0pd.js";const o=e` + `;export{o as bankSvg}; diff --git a/dist/assets/bin-BshwV3dZ.js b/dist/assets/bin-BshwV3dZ.js new file mode 100644 index 0000000..be2bd73 --- /dev/null +++ b/dist/assets/bin-BshwV3dZ.js @@ -0,0 +1,4 @@ +import{b as C}from"./index-Cr5N_0pd.js";const o=C` + + +`;export{o as binSvg}; diff --git a/dist/assets/bitcoin-M-S4Gfjc.js b/dist/assets/bitcoin-M-S4Gfjc.js new file mode 100644 index 0000000..8d1c46d --- /dev/null +++ b/dist/assets/bitcoin-M-S4Gfjc.js @@ -0,0 +1,13 @@ +import{b as L}from"./index-Cr5N_0pd.js";const i=L` + + + + + + + + + + + +`;export{i as bitcoinSvg}; diff --git a/dist/assets/browser-CC3et0uk.js b/dist/assets/browser-CC3et0uk.js new file mode 100644 index 0000000..e19c933 --- /dev/null +++ b/dist/assets/browser-CC3et0uk.js @@ -0,0 +1,14 @@ +import{b as l}from"./index-Cr5N_0pd.js";const a=l` + + +`;export{a as browserSvg}; diff --git a/dist/assets/card-9KwzYBwi.js b/dist/assets/card-9KwzYBwi.js new file mode 100644 index 0000000..15df809 --- /dev/null +++ b/dist/assets/card-9KwzYBwi.js @@ -0,0 +1,14 @@ +import{b as C}from"./index-Cr5N_0pd.js";const l=C` + `;export{l as cardSvg}; diff --git a/dist/assets/ccip-CSxoh1Sw.js b/dist/assets/ccip-CSxoh1Sw.js new file mode 100644 index 0000000..0584a95 --- /dev/null +++ b/dist/assets/ccip-CSxoh1Sw.js @@ -0,0 +1 @@ +import{B as p,f as y,s as w,h as k,j as b,l as L,k as O,m as R,o as E,p as x,H as m,q as M}from"./index-Cr5N_0pd.js";class q extends p{constructor({callbackSelector:s,cause:e,data:o,extraData:n,sender:c,urls:t}){super(e.shortMessage||"An error occurred while fetching for an offchain result.",{cause:e,metaMessages:[...e.metaMessages||[],e.metaMessages?.length?"":[],"Offchain Gateway Call:",t&&[" Gateway URL(s):",...t.map(i=>` ${y(i)}`)],` Sender: ${c}`,` Data: ${o}`,` Callback selector: ${s}`,` Extra data: ${n}`].flat(),name:"OffchainLookupError"})}}class S extends p{constructor({result:s,url:e}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${y(e)}`,`Response: ${w(s)}`],name:"OffchainLookupResponseMalformedError"})}}class $ extends p{constructor({sender:s,to:e}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${e}`,`OffchainLookup sender address: ${s}`],name:"OffchainLookupSenderMismatchError"})}}const A="0x556f1830",T={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function D(d,{blockNumber:s,blockTag:e,data:o,to:n}){const{args:c}=k({data:o,abi:[T]}),[t,i,l,a,r]=c,{ccipRead:f}=d,h=f&&typeof f?.request=="function"?f.request:C;try{if(!b(n,t))throw new $({sender:t,to:n});const u=i.includes(L)?await O({data:l,ccipRequest:h}):await h({data:l,sender:t,urls:i}),{data:g}=await R(d,{blockNumber:s,blockTag:e,data:E([a,x([{type:"bytes"},{type:"bytes"}],[u,r])]),to:n});return g}catch(u){throw new q({callbackSelector:a,cause:u,data:o,extraData:r,sender:t,urls:i})}}async function C({data:d,sender:s,urls:e}){let o=new Error("An unknown error occurred.");for(let n=0;n + + +`;export{o as checkmarkSvg}; diff --git a/dist/assets/checkmark-bold-DBpjkRrv.js b/dist/assets/checkmark-bold-DBpjkRrv.js new file mode 100644 index 0000000..6c60021 --- /dev/null +++ b/dist/assets/checkmark-bold-DBpjkRrv.js @@ -0,0 +1,8 @@ +import{b as e}from"./index-Cr5N_0pd.js";const o=e` + +`;export{o as checkmarkBoldSvg}; diff --git a/dist/assets/chevron-bottom-B9wx_mOd.js b/dist/assets/chevron-bottom-B9wx_mOd.js new file mode 100644 index 0000000..9ef8252 --- /dev/null +++ b/dist/assets/chevron-bottom-B9wx_mOd.js @@ -0,0 +1,8 @@ +import{b as o}from"./index-Cr5N_0pd.js";const e=o` + +`;export{e as chevronBottomSvg}; diff --git a/dist/assets/chevron-left-nYdEcmRU.js b/dist/assets/chevron-left-nYdEcmRU.js new file mode 100644 index 0000000..9445369 --- /dev/null +++ b/dist/assets/chevron-left-nYdEcmRU.js @@ -0,0 +1,8 @@ +import{b as e}from"./index-Cr5N_0pd.js";const o=e` + +`;export{o as chevronLeftSvg}; diff --git a/dist/assets/chevron-right-BIvCTfn4.js b/dist/assets/chevron-right-BIvCTfn4.js new file mode 100644 index 0000000..2edb354 --- /dev/null +++ b/dist/assets/chevron-right-BIvCTfn4.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + +`;export{o as chevronRightSvg}; diff --git a/dist/assets/chevron-top-D_T8NmSU.js b/dist/assets/chevron-top-D_T8NmSU.js new file mode 100644 index 0000000..ed06716 --- /dev/null +++ b/dist/assets/chevron-top-D_T8NmSU.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const e=l` + +`;export{e as chevronTopSvg}; diff --git a/dist/assets/chrome-store-DjKACh-G.js b/dist/assets/chrome-store-DjKACh-G.js new file mode 100644 index 0000000..6500d6d --- /dev/null +++ b/dist/assets/chrome-store-DjKACh-G.js @@ -0,0 +1,61 @@ +import{b as t}from"./index-Cr5N_0pd.js";const o=t` + + + + + + + + + + + + + + + + + + + + + +`;export{o as chromeStoreSvg}; diff --git a/dist/assets/circle-CMRf11j6.js b/dist/assets/circle-CMRf11j6.js new file mode 100644 index 0000000..b8803a1 --- /dev/null +++ b/dist/assets/circle-CMRf11j6.js @@ -0,0 +1,4 @@ +import{b as i}from"./index-Cr5N_0pd.js";const t=i` + + +`;export{t as circleSvg}; diff --git a/dist/assets/clock-Bu8fqLqw.js b/dist/assets/clock-Bu8fqLqw.js new file mode 100644 index 0000000..53a6689 --- /dev/null +++ b/dist/assets/clock-Bu8fqLqw.js @@ -0,0 +1,8 @@ +import{b as C}from"./index-Cr5N_0pd.js";const l=C` + +`;export{l as clockSvg}; diff --git a/dist/assets/close-DkOqA3XA.js b/dist/assets/close-DkOqA3XA.js new file mode 100644 index 0000000..0816250 --- /dev/null +++ b/dist/assets/close-DkOqA3XA.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + +`;export{o as closeSvg}; diff --git a/dist/assets/coinPlaceholder-Bog9viJQ.js b/dist/assets/coinPlaceholder-Bog9viJQ.js new file mode 100644 index 0000000..2e7af18 --- /dev/null +++ b/dist/assets/coinPlaceholder-Bog9viJQ.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + +`;export{o as coinPlaceholderSvg}; diff --git a/dist/assets/compass-k9qpYhtB.js b/dist/assets/compass-k9qpYhtB.js new file mode 100644 index 0000000..2a1c67a --- /dev/null +++ b/dist/assets/compass-k9qpYhtB.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const e=l` + +`;export{e as compassSvg}; diff --git a/dist/assets/copy-CrR_vPRD.js b/dist/assets/copy-CrR_vPRD.js new file mode 100644 index 0000000..41cdda5 --- /dev/null +++ b/dist/assets/copy-CrR_vPRD.js @@ -0,0 +1,15 @@ +import{b as C}from"./index-Cr5N_0pd.js";const o=C` + `;export{o as copySvg}; diff --git a/dist/assets/cursor-B5zA10jJ.js b/dist/assets/cursor-B5zA10jJ.js new file mode 100644 index 0000000..123db61 --- /dev/null +++ b/dist/assets/cursor-B5zA10jJ.js @@ -0,0 +1,3 @@ +import{b as o}from"./index-Cr5N_0pd.js";const l=o` + +`;export{l as cursorSvg}; diff --git a/dist/assets/cursor-transparent-8xgUPsqN.js b/dist/assets/cursor-transparent-8xgUPsqN.js new file mode 100644 index 0000000..0bdabc5 --- /dev/null +++ b/dist/assets/cursor-transparent-8xgUPsqN.js @@ -0,0 +1,12 @@ +import{b as o}from"./index-Cr5N_0pd.js";const l=o` + + + + `;export{l as cursorTransparentSvg}; diff --git a/dist/assets/desktop-CW7qCBPc.js b/dist/assets/desktop-CW7qCBPc.js new file mode 100644 index 0000000..c2363c1 --- /dev/null +++ b/dist/assets/desktop-CW7qCBPc.js @@ -0,0 +1,9 @@ +import{b as c}from"./index-Cr5N_0pd.js";const l=c` + + +`;export{l as desktopSvg}; diff --git a/dist/assets/disconnect-DzbPXgkg.js b/dist/assets/disconnect-DzbPXgkg.js new file mode 100644 index 0000000..8b47b8c --- /dev/null +++ b/dist/assets/disconnect-DzbPXgkg.js @@ -0,0 +1,8 @@ +import{b as a}from"./index-Cr5N_0pd.js";const e=a` + +`;export{e as disconnectSvg}; diff --git a/dist/assets/discord-CPs1H_Zj.js b/dist/assets/discord-CPs1H_Zj.js new file mode 100644 index 0000000..fe361b5 --- /dev/null +++ b/dist/assets/discord-CPs1H_Zj.js @@ -0,0 +1,17 @@ +import{b as l}from"./index-Cr5N_0pd.js";const i=l` + + + + + + + + + + +`;export{i as discordSvg}; diff --git a/dist/assets/email-OHUMhOV6.js b/dist/assets/email-OHUMhOV6.js new file mode 100644 index 0000000..65b6083 --- /dev/null +++ b/dist/assets/email-OHUMhOV6.js @@ -0,0 +1,237 @@ +import{i as b,a3 as U,a4 as M,a5 as I,c as d,a as v,x as u,aa as m,a7 as P,d3 as R,T as l,O as h,L as C,R as f,K as V,$ as N,aj as y,a0 as c,ap as L,ay as B,aA as H,aw as q,Q as K}from"./index-Cr5N_0pd.js";const G=b` + :host { + position: relative; + display: inline-block; + } + + input { + width: 50px; + height: 50px; + background: var(--wui-color-gray-glass-010); + border-radius: var(--wui-border-radius-xs); + border: 1px solid var(--wui-color-gray-glass-005); + font-family: var(--wui-font-family); + font-size: var(--wui-font-size-large); + font-weight: var(--wui-font-weight-regular); + letter-spacing: var(--wui-letter-spacing-large); + text-align: center; + color: var(--wui-color-fg-100); + caret-color: var(--wui-color-accent-100); + transition: + background-color var(--wui-ease-inout-power-1) var(--wui-duration-md), + border-color var(--wui-ease-inout-power-1) var(--wui-duration-md), + box-shadow var(--wui-ease-inout-power-1) var(--wui-duration-md); + will-change: background-color, border-color, box-shadow; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: textfield; + padding: 0px; + } + + input::-webkit-outer-spin-button, + input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; + } + + input[type='number'] { + -moz-appearance: textfield; + } + + input:disabled { + cursor: not-allowed; + border: 1px solid var(--wui-color-gray-glass-010); + background: var(--wui-color-gray-glass-005); + } + + input:focus:enabled { + background-color: var(--wui-color-gray-glass-015); + border: 1px solid var(--wui-color-accent-100); + -webkit-box-shadow: 0px 0px 0px 4px var(--wui-box-shadow-blue); + -moz-box-shadow: 0px 0px 0px 4px var(--wui-box-shadow-blue); + box-shadow: 0px 0px 0px 4px var(--wui-box-shadow-blue); + } + + @media (hover: hover) and (pointer: fine) { + input:hover:enabled { + background-color: var(--wui-color-gray-glass-015); + } + } +`;var S=function(a,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,n);else for(var s=a.length-1;s>=0;s--)(r=a[s])&&(i=(o<3?r(i):o>3?r(e,t,i):r(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i};let g=class extends v{constructor(){super(...arguments),this.disabled=!1,this.value=""}render(){return u` `}};g.styles=[U,M,G];S([I({type:Boolean})],g.prototype,"disabled",void 0);S([I({type:String})],g.prototype,"value",void 0);g=S([d("wui-input-numeric")],g);const Y=b` + :host { + position: relative; + display: block; + } +`;var O=function(a,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,n);else for(var s=a.length-1;s>=0;s--)(r=a[s])&&(i=(o<3?r(i):o>3?r(e,t,i):r(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i};let w=class extends v{constructor(){super(...arguments),this.length=6,this.otp="",this.values=Array.from({length:this.length}).map(()=>""),this.numerics=[],this.shouldInputBeEnabled=e=>this.values.slice(0,e).every(n=>n!==""),this.handleKeyDown=(e,t)=>{const n=e.target,o=this.getInputElement(n),i=["ArrowLeft","ArrowRight","Shift","Delete"];if(!o)return;i.includes(e.key)&&e.preventDefault();const r=o.selectionStart;switch(e.key){case"ArrowLeft":r&&o.setSelectionRange(r+1,r+1),this.focusInputField("prev",t);break;case"ArrowRight":this.focusInputField("next",t);break;case"Shift":this.focusInputField("next",t);break;case"Delete":o.value===""?this.focusInputField("prev",t):this.updateInput(o,t,"");break;case"Backspace":o.value===""?this.focusInputField("prev",t):this.updateInput(o,t,"");break}},this.focusInputField=(e,t)=>{if(e==="next"){const n=t+1;if(!this.shouldInputBeEnabled(n))return;const o=this.numerics[n-1?n:t],i=o?this.getInputElement(o):void 0;i&&i.focus()}}}firstUpdated(){this.otp&&(this.values=this.otp.split(""));const e=this.shadowRoot?.querySelectorAll("wui-input-numeric");e&&(this.numerics=Array.from(e)),this.numerics[0]?.focus()}render(){return u` + + ${Array.from({length:this.length}).map((e,t)=>u` + this.handleInput(n,t)} + @click=${n=>this.selectInput(n)} + @keydown=${n=>this.handleKeyDown(n,t)} + .disabled=${!this.shouldInputBeEnabled(t)} + .value=${this.values[t]||""} + > + + `)} + + `}updateInput(e,t,n){const o=this.numerics[t],i=e||(o?this.getInputElement(o):void 0);i&&(i.value=n,this.values=this.values.map((r,s)=>s===t?n:r))}selectInput(e){const t=e.target;t&&this.getInputElement(t)?.select()}handleInput(e,t){const n=e.target,o=this.getInputElement(n);if(o){const i=o.value;e.inputType==="insertFromPaste"?this.handlePaste(o,i,t):P.isNumber(i)&&e.data?(this.updateInput(o,t,e.data),this.focusInputField("next",t)):this.updateInput(o,t,"")}this.dispatchInputChangeEvent()}handlePaste(e,t,n){const o=t[0];if(o&&P.isNumber(o)){this.updateInput(e,n,o);const r=t.substring(1);if(n+1=0;s--)(r=a[s])&&(i=(o<3?r(i):o>3?r(e,t,i):r(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},T;let p=T=class extends v{firstUpdated(){this.startOTPTimeout()}disconnectedCallback(){clearTimeout(this.OTPTimeout)}constructor(){super(),this.loading=!1,this.timeoutTimeLeft=R.getTimeToNextEmailLogin(),this.error="",this.otp="",this.email=l.state.data?.email,this.authConnector=h.getAuthConnector()}render(){if(!this.email)throw new Error("w3m-email-otp-widget: No email provided");const e=!!this.timeoutTimeLeft,t=this.getFooterLabels(e);return u` + + + + The code expires in 20 minutes + + ${this.loading?u``:u` + + ${this.error?u` + + ${this.error}. Try Again + + `:null} + `} + + + ${t.title} + + ${t.action} + + + + `}startOTPTimeout(){this.timeoutTimeLeft=R.getTimeToNextEmailLogin(),this.OTPTimeout=setInterval(()=>{this.timeoutTimeLeft>0?this.timeoutTimeLeft=R.getTimeToNextEmailLogin():clearInterval(this.OTPTimeout)},1e3)}async onOtpInputChange(e){try{this.loading||(this.otp=e.detail,this.shouldSubmitOnOtpChange()&&(this.loading=!0,await this.onOtpSubmit?.(this.otp)))}catch(t){this.error=C.parseError(t),this.loading=!1}}async onResendCode(){try{if(this.onOtpResend){if(!this.loading&&!this.timeoutTimeLeft){if(this.error="",this.otp="",!h.getAuthConnector()||!this.email)throw new Error("w3m-email-otp-widget: Unable to resend email");this.loading=!0,await this.onOtpResend(this.email),this.startOTPTimeout(),f.showSuccess("Code email resent")}}else this.onStartOver&&this.onStartOver()}catch(e){f.showError(e)}finally{this.loading=!1}}getFooterLabels(e){return this.onStartOver?{title:"Something wrong?",action:`Try again ${e?`in ${this.timeoutTimeLeft}s`:""}`}:{title:"Didn't receive it?",action:`Resend ${e?`in ${this.timeoutTimeLeft}s`:"Code"}`}}shouldSubmitOnOtpChange(){return this.authConnector&&this.otp.length===T.OTP_LENGTH}};p.OTP_LENGTH=6;p.styles=Q;_([m()],p.prototype,"loading",void 0);_([m()],p.prototype,"timeoutTimeLeft",void 0);_([m()],p.prototype,"error",void 0);p=T=_([d("w3m-email-otp-widget")],p);var J=function(a,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,n);else for(var s=a.length-1;s>=0;s--)(r=a[s])&&(i=(o<3?r(i):o>3?r(e,t,i):r(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i};let W=class extends p{constructor(){super(...arguments),this.onOtpSubmit=async e=>{try{if(this.authConnector){const t=V.state.activeChain,n=N.getConnections(t),o=y.state.remoteFeatures?.multiWallet,i=n.length>0;if(await this.authConnector.provider.connectOtp({otp:e}),c.sendEvent({type:"track",event:"EMAIL_VERIFICATION_CODE_PASS"}),t)await N.connectExternal(this.authConnector,t);else throw new Error("Active chain is not set on ChainControll");if(c.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:"email",name:this.authConnector.name||"Unknown",caipNetworkId:V.getActiveCaipNetwork()?.caipNetworkId}}),y.state.remoteFeatures?.emailCapture)return;if(y.state.siwx){L.close();return}if(i&&o){l.replace("ProfileWallets"),f.showSuccess("New Wallet Added");return}L.close()}}catch(t){throw c.sendEvent({type:"track",event:"EMAIL_VERIFICATION_CODE_FAIL",properties:{message:C.parseError(t)}}),t}},this.onOtpResend=async e=>{this.authConnector&&(await this.authConnector.provider.connectEmail({email:e}),c.sendEvent({type:"track",event:"EMAIL_VERIFICATION_CODE_SENT"}))}}};W=J([d("w3m-email-verify-otp-view")],W);const X=b` + wui-icon-box { + height: var(--wui-icon-box-size-xl); + width: var(--wui-icon-box-size-xl); + } +`;var k=function(a,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,n);else for(var s=a.length-1;s>=0;s--)(r=a[s])&&(i=(o<3?r(i):o>3?r(e,t,i):r(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i};let x=class extends v{constructor(){super(),this.email=l.state.data?.email,this.authConnector=h.getAuthConnector(),this.loading=!1,this.listenForDeviceApproval()}render(){if(!this.email)throw new Error("w3m-email-verify-device-view: No email provided");if(!this.authConnector)throw new Error("w3m-email-verify-device-view: No auth connector provided");return u` + + + + + + + Approve the login link we sent to + + ${this.email} + + + + The code expires in 20 minutes + + + + + Didn't receive it? + + + Resend email + + + + + `}async listenForDeviceApproval(){if(this.authConnector)try{await this.authConnector.provider.connectDevice(),c.sendEvent({type:"track",event:"DEVICE_REGISTERED_FOR_EMAIL"}),c.sendEvent({type:"track",event:"EMAIL_VERIFICATION_CODE_SENT"}),l.replace("EmailVerifyOtp",{email:this.email})}catch{l.goBack()}}async onResendCode(){try{if(!this.loading){if(!this.authConnector||!this.email)throw new Error("w3m-email-login-widget: Unable to resend email");this.loading=!0,await this.authConnector.provider.connectEmail({email:this.email}),this.listenForDeviceApproval(),f.showSuccess("Code email resent")}}catch(e){f.showError(e)}finally{this.loading=!1}}};x.styles=X;k([m()],x.prototype,"loading",void 0);x=k([d("w3m-email-verify-device-view")],x);const Z=b` + wui-email-input { + width: 100%; + } + + form { + width: 100%; + display: block; + position: relative; + } +`;var $=function(a,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,n);else for(var s=a.length-1;s>=0;s--)(r=a[s])&&(i=(o<3?r(i):o>3?r(e,t,i):r(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i};let E=class extends v{constructor(){super(...arguments),this.formRef=B(),this.initialEmail=l.state.data?.email??"",this.redirectView=l.state.data?.redirectView,this.email="",this.loading=!1}firstUpdated(){this.formRef.value?.addEventListener("keydown",e=>{e.key==="Enter"&&this.onSubmitEmail(e)})}render(){return u` + +
+ + + +
+ ${this.buttonsTemplate()} +
+ `}onEmailInputChange(e){this.email=e.detail}async onSubmitEmail(e){try{if(this.loading)return;this.loading=!0,e.preventDefault();const t=h.getAuthConnector();if(!t)throw new Error("w3m-update-email-wallet: Auth connector not found");const n=await t.provider.updateEmail({email:this.email});c.sendEvent({type:"track",event:"EMAIL_EDIT"}),n.action==="VERIFY_SECONDARY_OTP"?l.push("UpdateEmailSecondaryOtp",{email:this.initialEmail,newEmail:this.email,redirectView:this.redirectView}):l.push("UpdateEmailPrimaryOtp",{email:this.initialEmail,newEmail:this.email,redirectView:this.redirectView})}catch(t){f.showError(t),this.loading=!1}}buttonsTemplate(){const e=!this.loading&&this.email.length>3&&this.email!==this.initialEmail;return this.redirectView?u` + + + Cancel + + + + Save + + + `:u` + + Save + + `}};E.styles=Z;$([m()],E.prototype,"email",void 0);$([m()],E.prototype,"loading",void 0);E=$([d("w3m-update-email-wallet-view")],E);var ee=function(a,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,n);else for(var s=a.length-1;s>=0;s--)(r=a[s])&&(i=(o<3?r(i):o>3?r(e,t,i):r(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i};let F=class extends p{constructor(){super(),this.email=l.state.data?.email,this.onOtpSubmit=async e=>{try{this.authConnector&&(await this.authConnector.provider.updateEmailPrimaryOtp({otp:e}),c.sendEvent({type:"track",event:"EMAIL_VERIFICATION_CODE_PASS"}),l.replace("UpdateEmailSecondaryOtp",l.state.data))}catch(t){throw c.sendEvent({type:"track",event:"EMAIL_VERIFICATION_CODE_FAIL",properties:{message:C.parseError(t)}}),t}},this.onStartOver=()=>{l.replace("UpdateEmailWallet",l.state.data)}}};F=ee([d("w3m-update-email-primary-otp-view")],F);var te=function(a,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,n);else for(var s=a.length-1;s>=0;s--)(r=a[s])&&(i=(o<3?r(i):o>3?r(e,t,i):r(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i};let j=class extends p{constructor(){super(),this.email=l.state.data?.newEmail,this.redirectView=l.state.data?.redirectView,this.onOtpSubmit=async e=>{try{this.authConnector&&(await this.authConnector.provider.updateEmailSecondaryOtp({otp:e}),c.sendEvent({type:"track",event:"EMAIL_VERIFICATION_CODE_PASS"}),this.redirectView&&l.reset(this.redirectView))}catch(t){throw c.sendEvent({type:"track",event:"EMAIL_VERIFICATION_CODE_FAIL",properties:{message:C.parseError(t)}}),t}},this.onStartOver=()=>{l.replace("UpdateEmailWallet",l.state.data)}}};j=te([d("w3m-update-email-secondary-otp-view")],j);var z=function(a,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,n);else for(var s=a.length-1;s>=0;s--)(r=a[s])&&(i=(o<3?r(i):o>3?r(e,t,i):r(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i};let A=class extends v{constructor(){super(),this.authConnector=h.getAuthConnector(),this.isEmailEnabled=y.state.remoteFeatures?.email,this.isAuthEnabled=this.checkIfAuthEnabled(h.state.connectors),this.connectors=h.state.connectors,h.subscribeKey("connectors",e=>{this.connectors=e,this.isAuthEnabled=this.checkIfAuthEnabled(this.connectors)})}render(){if(!this.isEmailEnabled)throw new Error("w3m-email-login-view: Email is not enabled");if(!this.isAuthEnabled)throw new Error("w3m-email-login-view: No auth connector provided");return u` + + `}checkIfAuthEnabled(e){const t=e.filter(o=>o.type===q.CONNECTOR_TYPE_AUTH).map(o=>o.chain);return K.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(o=>t.includes(o))}};z([m()],A.prototype,"connectors",void 0);A=z([d("w3m-email-login-view")],A);export{A as W3mEmailLoginView,p as W3mEmailOtpWidget,x as W3mEmailVerifyDeviceView,W as W3mEmailVerifyOtpView,F as W3mUpdateEmailPrimaryOtpView,j as W3mUpdateEmailSecondaryOtpView,E as W3mUpdateEmailWalletView}; diff --git a/dist/assets/embedded-wallet-Axuw_fFm.js b/dist/assets/embedded-wallet-Axuw_fFm.js new file mode 100644 index 0000000..78d1d3d --- /dev/null +++ b/dist/assets/embedded-wallet-Axuw_fFm.js @@ -0,0 +1,194 @@ +import{i as v,a as p,ap as E,x as l,O as j,a8 as A,ax as D,aa as h,c as f,F as _,a3 as M,a5 as g,a9 as P,Q as C,ay as z,az as c,Y as N,L as U,aA as k,a0 as x,a1 as y,K as S,a2 as T,R as H,aB as F,T as V}from"./index-Cr5N_0pd.js";const B=v` + div { + width: 100%; + } + + [data-ready='false'] { + transform: scale(1.05); + } + + @media (max-width: 430px) { + [data-ready='false'] { + transform: translateY(-50px); + } + } +`;var W=function(r,e,i,n){var s=arguments.length,t=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(r,e,i,n);else for(var o=r.length-1;o>=0;o--)(a=r[o])&&(t=(s<3?a(t):s>3?a(e,i,t):a(e,i))||t);return s>3&&t&&Object.defineProperty(e,i,t),t};const $=600,I=360,Y=64;let b=class extends p{constructor(){super(),this.bodyObserver=void 0,this.unsubscribe=[],this.iframe=document.getElementById("w3m-iframe"),this.ready=!1,this.unsubscribe.push(E.subscribeKey("open",e=>{e||this.onHideIframe()}),E.subscribeKey("shake",e=>{e?this.iframe.style.animation="w3m-shake 500ms var(--wui-ease-out-power-2)":this.iframe.style.animation="none"}))}disconnectedCallback(){this.onHideIframe(),this.unsubscribe.forEach(e=>e()),this.bodyObserver?.unobserve(window.document.body)}async firstUpdated(){await this.syncTheme(),this.iframe.style.display="block";const e=this?.renderRoot?.querySelector("div");this.bodyObserver=new ResizeObserver(i=>{const s=i?.[0]?.contentBoxSize?.[0]?.inlineSize;this.iframe.style.height=`${$}px`,e.style.height=`${$}px`,s&&s<=430?(this.iframe.style.width="100%",this.iframe.style.left="0px",this.iframe.style.bottom="0px",this.iframe.style.top="unset"):(this.iframe.style.width=`${I}px`,this.iframe.style.left=`calc(50% - ${I/2}px)`,this.iframe.style.top=`calc(50% - ${$/2}px + ${Y/2}px)`,this.iframe.style.bottom="unset"),this.ready=!0,this.onShowIframe()}),this.bodyObserver.observe(window.document.body)}render(){return l`
`}onShowIframe(){const e=window.innerWidth<=430;this.iframe.style.animation=e?"w3m-iframe-zoom-in-mobile 200ms var(--wui-ease-out-power-2)":"w3m-iframe-zoom-in 200ms var(--wui-ease-out-power-2)"}onHideIframe(){this.iframe.style.display="none",this.iframe.style.animation="w3m-iframe-fade-out 200ms var(--wui-ease-out-power-2)"}async syncTheme(){const e=j.getAuthConnector();if(e){const i=A.getSnapshot().themeMode,n=A.getSnapshot().themeVariables;await e.provider.syncTheme({themeVariables:n,w3mThemeVariables:D(n,i)})}}};b.styles=B;W([h()],b.prototype,"ready",void 0);b=W([f("w3m-approve-transaction-view")],b);var G=function(r,e,i,n){var s=arguments.length,t=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(r,e,i,n);else for(var o=r.length-1;o>=0;o--)(a=r[o])&&(t=(s<3?a(t):s>3?a(e,i,t):a(e,i))||t);return s>3&&t&&Object.defineProperty(e,i,t),t};let O=class extends p{render(){return l` + + Follow the instructions on + + + + You will have to reconnect for security reasons + + + `}};O=G([f("w3m-upgrade-wallet-view")],O);const L=v` + :host { + position: relative; + width: 100%; + display: inline-block; + color: var(--wui-color-fg-275); + } + + .error { + margin: var(--wui-spacing-xxs) var(--wui-spacing-m) var(--wui-spacing-0) var(--wui-spacing-m); + } + + .base-name { + position: absolute; + right: 45px; + top: 15px; + text-align: right; + } +`;var w=function(r,e,i,n){var s=arguments.length,t=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(r,e,i,n);else for(var o=r.length-1;o>=0;o--)(a=r[o])&&(t=(s<3?a(t):s>3?a(e,i,t):a(e,i))||t);return s>3&&t&&Object.defineProperty(e,i,t),t};let d=class extends p{constructor(){super(...arguments),this.disabled=!1,this.loading=!1}render(){return l` + + ${this.baseNameTemplate()} ${this.errorTemplate()}${this.loadingTemplate()} + + `}baseNameTemplate(){return l` + ${C.WC_NAME_SUFFIX} + `}loadingTemplate(){return this.loading?l``:null}errorTemplate(){return this.errorMessage?l`${this.errorMessage}`:null}};d.styles=[M,L];w([g()],d.prototype,"errorMessage",void 0);w([g({type:Boolean})],d.prototype,"disabled",void 0);w([g()],d.prototype,"value",void 0);w([g({type:Boolean})],d.prototype,"loading",void 0);d=w([f("wui-ens-input")],d);const K=v` + wui-flex { + width: 100%; + } + + .suggestion { + background: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + } + + .suggestion:hover { + background-color: var(--wui-color-gray-glass-005); + cursor: pointer; + } + + .suggested-name { + max-width: 75%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + form { + width: 100%; + } + + wui-icon-link { + position: absolute; + right: 20px; + transform: translateY(11px); + } +`;var m=function(r,e,i,n){var s=arguments.length,t=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(r,e,i,n);else for(var o=r.length-1;o>=0;o--)(a=r[o])&&(t=(s<3?a(t):s>3?a(e,i,t):a(e,i))||t);return s>3&&t&&Object.defineProperty(e,i,t),t};let u=class extends p{constructor(){super(),this.formRef=z(),this.usubscribe=[],this.name="",this.error="",this.loading=c.state.loading,this.suggestions=c.state.suggestions,this.registered=!1,this.profileName=N.state.profileName,this.onDebouncedNameInputChange=U.debounce(e=>{c.validateName(e)?(this.error="",this.name=e,c.getSuggestions(e),c.isNameRegistered(e).then(i=>{this.registered=i})):e.length<4?this.error="Name must be at least 4 characters long":this.error="Can only contain letters, numbers and - characters"}),this.usubscribe.push(c.subscribe(e=>{this.suggestions=e.suggestions,this.loading=e.loading}),N.subscribeKey("profileName",e=>{this.profileName=e,e&&(this.error="You already own a name")}))}firstUpdated(){this.formRef.value?.addEventListener("keydown",this.onEnterKey.bind(this))}disconnectedCallback(){super.disconnectedCallback(),this.usubscribe.forEach(e=>e()),this.formRef.value?.removeEventListener("keydown",this.onEnterKey.bind(this))}render(){return l` + +
+ + + ${this.submitButtonTemplate()} + +
+ ${this.templateSuggestions()} +
+ `}submitButtonTemplate(){return this.isAllowedToSubmit()?l` + + + `:null}onSelectSuggestion(e){return()=>{this.name=e,this.registered=!1,this.requestUpdate()}}onNameInputChange(e){this.onDebouncedNameInputChange(e.detail)}nameSuggestionTagTemplate(){return this.loading?l``:this.registered?l`Registered`:l`Available`}templateSuggestions(){if(!this.name||this.name.length<4||this.error)return null;const e=this.registered?this.suggestions.filter(i=>i.name!==this.name):[];return l` + + + ${this.name}${this.nameSuggestionTagTemplate()} + + ${e.map(i=>this.availableNameTemplate(i.name))} + `}availableNameTemplate(e){return l` + + ${e} + + Available + `}isAllowedToSubmit(){return!this.loading&&!this.registered&&!this.error&&!this.profileName&&c.validateName(this.name)}async onSubmitName(){try{if(!this.isAllowedToSubmit())return;const e=`${this.name}${C.WC_NAME_SUFFIX}`;x.sendEvent({type:"track",event:"REGISTER_NAME_INITIATED",properties:{isSmartAccount:y(S.state.activeChain)===T.ACCOUNT_TYPES.SMART_ACCOUNT,ensName:e}}),await c.registerName(e),x.sendEvent({type:"track",event:"REGISTER_NAME_SUCCESS",properties:{isSmartAccount:y(S.state.activeChain)===T.ACCOUNT_TYPES.SMART_ACCOUNT,ensName:e}})}catch(e){H.showError(e.message),x.sendEvent({type:"track",event:"REGISTER_NAME_ERROR",properties:{isSmartAccount:y(S.state.activeChain)===T.ACCOUNT_TYPES.SMART_ACCOUNT,ensName:`${this.name}${C.WC_NAME_SUFFIX}`,error:e?.message||"Unknown error"}})}}onEnterKey(e){e.key==="Enter"&&this.isAllowedToSubmit()&&this.onSubmitName()}};u.styles=K;m([g()],u.prototype,"errorMessage",void 0);m([h()],u.prototype,"name",void 0);m([h()],u.prototype,"error",void 0);m([h()],u.prototype,"loading",void 0);m([h()],u.prototype,"suggestions",void 0);m([h()],u.prototype,"registered",void 0);m([h()],u.prototype,"profileName",void 0);u=m([f("w3m-register-account-name-view")],u);const q=v` + .continue-button-container { + width: 100%; + } +`;var X=function(r,e,i,n){var s=arguments.length,t=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(r,e,i,n);else for(var o=r.length-1;o>=0;o--)(a=r[o])&&(t=(s<3?a(t):s>3?a(e,i,t):a(e,i))||t);return s>3&&t&&Object.defineProperty(e,i,t),t};let R=class extends p{render(){return l` + + ${this.onboardingTemplate()} ${this.buttonsTemplate()} + {U.openHref(F.URLS.FAQ,"_blank")}} + > + Learn more + + + + `}onboardingTemplate(){return l` + + + + + + Account name chosen successfully + + + You can now fund your account and trade crypto + + + `}buttonsTemplate(){return l` + Let's Go! + + `}redirectToAccount(){V.replace("Account")}};R.styles=q;R=X([f("w3m-register-account-name-success-view")],R);export{b as W3mApproveTransactionView,R as W3mRegisterAccountNameSuccess,u as W3mRegisterAccountNameView,O as W3mUpgradeWalletView}; diff --git a/dist/assets/ethereum-pDlrEry5.js b/dist/assets/ethereum-pDlrEry5.js new file mode 100644 index 0000000..b0578df --- /dev/null +++ b/dist/assets/ethereum-pDlrEry5.js @@ -0,0 +1,10 @@ +import{b as l}from"./index-Cr5N_0pd.js";const r=l` + + + + + + + + +`;export{r as ethereumSvg}; diff --git a/dist/assets/etherscan-yowPVDyy.js b/dist/assets/etherscan-yowPVDyy.js new file mode 100644 index 0000000..8ae8b41 --- /dev/null +++ b/dist/assets/etherscan-yowPVDyy.js @@ -0,0 +1,6 @@ +import{b as c}from"./index-Cr5N_0pd.js";const a=c` + +`;export{a as etherscanSvg}; diff --git a/dist/assets/exclamation-triangle-ByL4C-X2.js b/dist/assets/exclamation-triangle-ByL4C-X2.js new file mode 100644 index 0000000..dc70ec2 --- /dev/null +++ b/dist/assets/exclamation-triangle-ByL4C-X2.js @@ -0,0 +1,4 @@ +import{b as C}from"./index-Cr5N_0pd.js";const t=C` + + +`;export{t as exclamationTriangleSvg}; diff --git a/dist/assets/extension-V_MQztIO.js b/dist/assets/extension-V_MQztIO.js new file mode 100644 index 0000000..ea8341f --- /dev/null +++ b/dist/assets/extension-V_MQztIO.js @@ -0,0 +1,8 @@ +import{b as a}from"./index-Cr5N_0pd.js";const e=a` + +`;export{e as extensionSvg}; diff --git a/dist/assets/external-link-D5nUBuK8.js b/dist/assets/external-link-D5nUBuK8.js new file mode 100644 index 0000000..c4c19cd --- /dev/null +++ b/dist/assets/external-link-D5nUBuK8.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + +`;export{o as externalLinkSvg}; diff --git a/dist/assets/facebook-IzGdkHXn.js b/dist/assets/facebook-IzGdkHXn.js new file mode 100644 index 0000000..93347ac --- /dev/null +++ b/dist/assets/facebook-IzGdkHXn.js @@ -0,0 +1,26 @@ +import{b as l}from"./index-Cr5N_0pd.js";const f=l` + + + + + + + + + + + + + + + +`;export{f as facebookSvg}; diff --git a/dist/assets/farcaster-CQ1ZnK9M.js b/dist/assets/farcaster-CQ1ZnK9M.js new file mode 100644 index 0000000..09a4a69 --- /dev/null +++ b/dist/assets/farcaster-CQ1ZnK9M.js @@ -0,0 +1,12 @@ +import{b as h}from"./index-Cr5N_0pd.js";const a=h` + + + + +`;export{a as farcasterSvg}; diff --git a/dist/assets/filters-CENUgXu3.js b/dist/assets/filters-CENUgXu3.js new file mode 100644 index 0000000..39c8f44 --- /dev/null +++ b/dist/assets/filters-CENUgXu3.js @@ -0,0 +1,8 @@ +import{b as e}from"./index-Cr5N_0pd.js";const a=e` + +`;export{a as filtersSvg}; diff --git a/dist/assets/github-DB7o3FYw.js b/dist/assets/github-DB7o3FYw.js new file mode 100644 index 0000000..e1bb496 --- /dev/null +++ b/dist/assets/github-DB7o3FYw.js @@ -0,0 +1,18 @@ +import{b as l}from"./index-Cr5N_0pd.js";const c=l` + + + + + + + + + + + + + +`;export{c as githubSvg}; diff --git a/dist/assets/google-BQasw2Dk.js b/dist/assets/google-BQasw2Dk.js new file mode 100644 index 0000000..ab05886 --- /dev/null +++ b/dist/assets/google-BQasw2Dk.js @@ -0,0 +1,18 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + + + + +`;export{o as googleSvg}; diff --git a/dist/assets/hashTypedData-D0Cx__mD.js b/dist/assets/hashTypedData-D0Cx__mD.js new file mode 100644 index 0000000..2abd748 --- /dev/null +++ b/dist/assets/hashTypedData-D0Cx__mD.js @@ -0,0 +1 @@ +import{B as f,s as S,r as $,n as z,t as M,I as k,u as A,v as l,y as B,z as c,o as N,p as g,A as b}from"./index-Cr5N_0pd.js";class O extends f{constructor({domain:t}){super(`Invalid domain "${S(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class _ extends f{constructor({primaryType:t,types:n}){super(`Invalid primary type \`${t}\` must be one of \`${JSON.stringify(Object.keys(n))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class j extends f{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function C(e){const{domain:t,message:n,primaryType:s,types:r}=e,a=(i,d)=>{for(const D of i){const{name:x,type:p}=D,o=d[x],m=p.match($);if(m&&(typeof o=="number"||typeof o=="bigint")){const[w,y,P]=m;z(o,{signed:y==="int",size:Number.parseInt(P,10)/8})}if(p==="address"&&typeof o=="string"&&!M(o))throw new k({address:o});const u=p.match(A);if(u){const[w,y]=u;if(y&&l(o)!==Number.parseInt(y,10))throw new B({expectedSize:Number.parseInt(y,10),givenSize:l(o)})}const h=r[p];h&&(R(p),a(h,o))}};if(r.EIP712Domain&&t){if(typeof t!="object")throw new O({domain:t});a(r.EIP712Domain,t)}if(s!=="EIP712Domain")if(r[s])a(r[s],n);else throw new _({primaryType:s,types:r})}function H({domain:e}){return[typeof e?.name=="string"&&{name:"name",type:"string"},e?.version&&{name:"version",type:"string"},(typeof e?.chainId=="number"||typeof e?.chainId=="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function R(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new j({type:e})}function q(e){const{domain:t={},message:n,primaryType:s}=e,r={EIP712Domain:H({domain:t}),...e.types};C({domain:t,message:n,primaryType:s,types:r});const a=["0x1901"];return t&&a.push(W({domain:t,types:r})),s!=="EIP712Domain"&&a.push(I({data:n,primaryType:s,types:r})),c(N(a))}function W({domain:e,types:t}){return I({data:e,primaryType:"EIP712Domain",types:t})}function I({data:e,primaryType:t,types:n}){const s=T({data:e,primaryType:t,types:n});return c(s)}function T({data:e,primaryType:t,types:n}){const s=[{type:"bytes32"}],r=[F({primaryType:t,types:n})];for(const a of n[t]){const[i,d]=E({types:n,name:a.name,type:a.type,value:e[a.name]});s.push(i),r.push(d)}return g(s,r)}function F({primaryType:e,types:t}){const n=b(V({primaryType:e,types:t}));return c(n)}function V({primaryType:e,types:t}){let n="";const s=v({primaryType:e,types:t});s.delete(e);const r=[e,...Array.from(s).sort()];for(const a of r)n+=`${a}(${t[a].map(({name:i,type:d})=>`${d} ${i}`).join(",")})`;return n}function v({primaryType:e,types:t},n=new Set){const r=e.match(/^\w*/u)?.[0];if(n.has(r)||t[r]===void 0)return n;n.add(r);for(const a of t[r])v({primaryType:a.type,types:t},n);return n}function E({types:e,name:t,type:n,value:s}){if(e[n]!==void 0)return[{type:"bytes32"},c(T({data:s,primaryType:n,types:e}))];if(n==="bytes")return s=`0x${(s.length%2?"0":"")+s.slice(2)}`,[{type:"bytes32"},c(s)];if(n==="string")return[{type:"bytes32"},c(b(s))];if(n.lastIndexOf("]")===n.length-1){const r=n.slice(0,n.lastIndexOf("[")),a=s.map(i=>E({name:t,type:r,types:e,value:i}));return[{type:"bytes32"},c(g(a.map(([i])=>i),a.map(([,i])=>i)))]}return[{type:n},s]}export{q as h}; diff --git a/dist/assets/help-circle-VyIXOAlM.js b/dist/assets/help-circle-VyIXOAlM.js new file mode 100644 index 0000000..dbfcfe3 --- /dev/null +++ b/dist/assets/help-circle-VyIXOAlM.js @@ -0,0 +1,12 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + + +`;export{o as helpCircleSvg}; diff --git a/dist/assets/hooks.module-Dz_XB4AG.js b/dist/assets/hooks.module-Dz_XB4AG.js new file mode 100644 index 0000000..a45ce45 --- /dev/null +++ b/dist/assets/hooks.module-Dz_XB4AG.js @@ -0,0 +1 @@ +var F,d,d_,v_,H,o_,m_,z,Y,G,J,y_,M={},g_=[],M_=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,B=Array.isArray;function C(e,_){for(var t in _)e[t]=_[t];return e}function b_(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function K(e,_,t){var n,o,i,l={};for(i in _)i=="key"?n=_[i]:i=="ref"?o=_[i]:l[i]=_[i];if(arguments.length>2&&(l.children=arguments.length>3?F.call(arguments,2):t),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)l[i]===void 0&&(l[i]=e.defaultProps[i]);return N(e,l,n,o,null)}function N(e,_,t,n,o){var i={type:e,props:_,key:t,ref:n,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:o??++d_,__i:-1,__u:0};return o==null&&d.vnode!=null&&d.vnode(i),i}function F_(){return{current:null}}function A(e){return e.children}function D(e,_){this.props=e,this.context=_}function S(e,_){if(_==null)return e.__?S(e.__,e.__i+1):null;for(var t;__&&H.sort(z));j.__r=0}function $_(e,_,t,n,o,i,l,u,s,c,a){var r,h,f,g,k,b=n&&n.__k||g_,v=_.length;for(t.__d=s,A_(t,_,b),s=t.__d,r=0;r0?N(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=e,o.__b=e.__b+1,i=null,(u=o.__i=L_(o,t,l,a))!==-1&&(a--,(i=t[u])&&(i.__u|=131072)),i==null||i.__v===null?(u==-1&&r--,typeof o.type!="function"&&(o.__u|=65536)):u!==l&&(u==l-1?r--:u==l+1?r++:(u>l?r--:r++,o.__u|=65536))):o=e.__k[n]=null;if(a)for(n=0;n(s!=null&&!(131072&s.__u)?1:0))for(;l>=0||u<_.length;){if(l>=0){if((s=_[l])&&!(131072&s.__u)&&o==s.key&&i===s.type)return l;l--}if(u<_.length){if((s=_[u])&&!(131072&s.__u)&&o==s.key&&i===s.type)return u;u++}}return-1}function r_(e,_,t){_[0]==="-"?e.setProperty(_,t??""):e[_]=t==null?"":typeof t!="number"||M_.test(_)?t:t+"px"}function O(e,_,t,n,o){var i;_:if(_==="style")if(typeof t=="string")e.style.cssText=t;else{if(typeof n=="string"&&(e.style.cssText=n=""),n)for(_ in n)t&&_ in t||r_(e.style,_,"");if(t)for(_ in t)n&&t[_]===n[_]||r_(e.style,_,t[_])}else if(_[0]==="o"&&_[1]==="n")i=_!==(_=_.replace(/(PointerCapture)$|Capture$/i,"$1")),_=_.toLowerCase()in e||_==="onFocusOut"||_==="onFocusIn"?_.toLowerCase().slice(2):_.slice(2),e.l||(e.l={}),e.l[_+i]=t,t?n?t.u=n.u:(t.u=Y,e.addEventListener(_,i?J:G,i)):e.removeEventListener(_,i?J:G,i);else{if(o=="http://www.w3.org/2000/svg")_=_.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(_!="width"&&_!="height"&&_!="href"&&_!="list"&&_!="form"&&_!="tabIndex"&&_!="download"&&_!="rowSpan"&&_!="colSpan"&&_!="role"&&_!="popover"&&_ in e)try{e[_]=t??"";break _}catch{}typeof t=="function"||(t==null||t===!1&&_[4]!=="-"?e.removeAttribute(_):e.setAttribute(_,_=="popover"&&t==1?"":t))}}function i_(e){return function(_){if(this.l){var t=this.l[_.type+e];if(_.t==null)_.t=Y++;else if(_.t2&&(u.children=arguments.length>3?F.call(arguments,2):t),N(e.type,u,n||e.key,o||e.ref,null)}function R_(e,_){var t={__c:_="__cC"+y_++,__:e,Consumer:function(n,o){return n.children(o)},Provider:function(n){var o,i;return this.getChildContext||(o=[],(i={})[_]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){o=null},this.shouldComponentUpdate=function(l){this.props.value!==l.value&&o.some(function(u){u.__e=!0,Q(u)})},this.sub=function(l){o.push(l);var u=l.componentWillUnmount;l.componentWillUnmount=function(){o&&o.splice(o.indexOf(l),1),u&&u.call(l)}}),n.children}};return t.Provider.__=t.Consumer.contextType=t}F=g_.slice,d={__e:function(e,_,t,n){for(var o,i,l;_=_.__;)if((o=_.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),l=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,n||{}),l=o.__d),l)return o.__E=o}catch(u){e=u}throw e}},d_=0,v_=function(e){return e!=null&&e.constructor==null},D.prototype.setState=function(e,_){var t;t=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=C({},this.state),typeof e=="function"&&(e=e(C({},t),this.props)),e&&C(t,e),e!=null&&this.__v&&(_&&this._sb.push(_),Q(this))},D.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Q(this))},D.prototype.render=A,H=[],m_=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,z=function(e,_){return e.__v.__b-_.__v.__b},j.__r=0,Y=0,G=i_(!1),J=i_(!0),y_=0;const Y_=Object.freeze(Object.defineProperty({__proto__:null,Component:D,Fragment:A,cloneElement:O_,createContext:R_,createElement:K,createRef:F_,h:K,hydrate:S_,get isValidElement(){return v_},get options(){return d},render:P_,toChildArray:w_},Symbol.toStringTag,{value:"Module"}));var w,p,V,u_,E=0,E_=[],y=d,l_=y.__b,c_=y.__r,f_=y.diffed,s_=y.__c,a_=y.unmount,p_=y.__;function P(e,_){y.__h&&y.__h(p,e,E||_),E=0;var t=p.__H||(p.__H={__:[],__h:[]});return e>=t.__.length&&t.__.push({}),t.__[e]}function T_(e){return E=1,U_(D_,e)}function U_(e,_,t){var n=P(w++,2);if(n.t=e,!n.__c&&(n.__=[t?t(_):D_(void 0,_),function(u){var s=n.__N?n.__N[0]:n.__[0],c=n.t(s,u);s!==c&&(n.__N=[c,n.__[1]],n.__c.setState({}))}],n.__c=p,!p.u)){var o=function(u,s,c){if(!n.__c.__H)return!0;var a=n.__c.__H.__.filter(function(h){return!!h.__c});if(a.every(function(h){return!h.__N}))return!i||i.call(this,u,s,c);var r=!1;return a.forEach(function(h){if(h.__N){var f=h.__[0];h.__=h.__N,h.__N=void 0,f!==h.__[0]&&(r=!0)}}),!(!r&&n.__c.props===u)&&(!i||i.call(this,u,s,c))};p.u=!0;var i=p.shouldComponentUpdate,l=p.componentWillUpdate;p.componentWillUpdate=function(u,s,c){if(this.__e){var a=i;i=void 0,o(u,s,c),i=a}l&&l.call(this,u,s,c)},p.shouldComponentUpdate=o}return n.__N||n.__}function j_(e,_){var t=P(w++,3);!y.__s&&t_(t.__H,_)&&(t.__=e,t.i=_,p.__H.__h.push(t))}function N_(e,_){var t=P(w++,4);!y.__s&&t_(t.__H,_)&&(t.__=e,t.i=_,p.__h.push(t))}function B_(e){return E=5,e_(function(){return{current:e}},[])}function q_(e,_,t){E=6,N_(function(){return typeof e=="function"?(e(_()),function(){return e(null)}):e?(e.current=_(),function(){return e.current=null}):void 0},t==null?t:t.concat(e))}function e_(e,_){var t=P(w++,7);return t_(t.__H,_)&&(t.__=e(),t.__H=_,t.__h=e),t.__}function V_(e,_){return E=8,e_(function(){return e},_)}function z_(e){var _=p.context[e.__c],t=P(w++,9);return t.c=e,_?(t.__==null&&(t.__=!0,_.sub(p)),_.props.value):e.__}function G_(e,_){y.useDebugValue&&y.useDebugValue(_?_(e):e)}function J_(e){var _=P(w++,10),t=T_();return _.__=e,p.componentDidCatch||(p.componentDidCatch=function(n,o){_.__&&_.__(n,o),t[1](n)}),[t[0],function(){t[1](void 0)}]}function K_(){var e=P(w++,11);if(!e.__){for(var _=p.__v;_!==null&&!_.__m&&_.__!==null;)_=_.__;var t=_.__m||(_.__m=[0,0]);e.__="P"+t[0]+"-"+t[1]++}return e.__}function Q_(){for(var e;e=E_.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(R),e.__H.__h.forEach(X),e.__H.__h=[]}catch(_){e.__H.__h=[],y.__e(_,e.__v)}}y.__b=function(e){p=null,l_&&l_(e)},y.__=function(e,_){e&&_.__k&&_.__k.__m&&(e.__m=_.__k.__m),p_&&p_(e,_)},y.__r=function(e){c_&&c_(e),w=0;var _=(p=e.__c).__H;_&&(V===p?(_.__h=[],p.__h=[],_.__.forEach(function(t){t.__N&&(t.__=t.__N),t.i=t.__N=void 0})):(_.__h.forEach(R),_.__h.forEach(X),_.__h=[],w=0)),V=p},y.diffed=function(e){f_&&f_(e);var _=e.__c;_&&_.__H&&(_.__H.__h.length&&(E_.push(_)!==1&&u_===y.requestAnimationFrame||((u_=y.requestAnimationFrame)||X_)(Q_)),_.__H.__.forEach(function(t){t.i&&(t.__H=t.i),t.i=void 0})),V=p=null},y.__c=function(e,_){_.some(function(t){try{t.__h.forEach(R),t.__h=t.__h.filter(function(n){return!n.__||X(n)})}catch(n){_.some(function(o){o.__h&&(o.__h=[])}),_=[],y.__e(n,t.__v)}}),s_&&s_(e,_)},y.unmount=function(e){a_&&a_(e);var _,t=e.__c;t&&t.__H&&(t.__H.__.forEach(function(n){try{R(n)}catch(o){_=o}}),t.__H=void 0,_&&y.__e(_,t.__v))};var h_=typeof requestAnimationFrame=="function";function X_(e){var _,t=function(){clearTimeout(n),h_&&cancelAnimationFrame(_),setTimeout(e)},n=setTimeout(t,100);h_&&(_=requestAnimationFrame(t))}function R(e){var _=p,t=e.__c;typeof t=="function"&&(e.__c=void 0,t()),p=_}function X(e){var _=p;e.__c=e.__(),p=_}function t_(e,_){return!e||e.length!==_.length||_.some(function(t,n){return t!==e[n]})}function D_(e,_){return typeof _=="function"?_(e):_}const Z_=Object.freeze(Object.defineProperty({__proto__:null,useCallback:V_,useContext:z_,useDebugValue:G_,useEffect:j_,useErrorBoundary:J_,useId:K_,useImperativeHandle:q_,useLayoutEffect:N_,useMemo:e_,useReducer:U_,useRef:B_,useState:T_},Symbol.toStringTag,{value:"Module"}));export{P_ as B,K as _,Z_ as a,T_ as h,Y_ as p,j_ as y}; diff --git a/dist/assets/id-Dqw-Wgu3.js b/dist/assets/id-Dqw-Wgu3.js new file mode 100644 index 0000000..b5967c0 --- /dev/null +++ b/dist/assets/id-Dqw-Wgu3.js @@ -0,0 +1,12 @@ +import{b as c}from"./index-Cr5N_0pd.js";const e=c` + +`;export{e as idSvg}; diff --git a/dist/assets/image-Dd9GhBqt.js b/dist/assets/image-Dd9GhBqt.js new file mode 100644 index 0000000..dde7492 --- /dev/null +++ b/dist/assets/image-Dd9GhBqt.js @@ -0,0 +1,4 @@ +import{b as C}from"./index-Cr5N_0pd.js";const l=C` + + +`;export{l as imageSvg}; diff --git a/dist/assets/index-4N_q9Ijm.js b/dist/assets/index-4N_q9Ijm.js new file mode 100644 index 0000000..663c3c2 --- /dev/null +++ b/dist/assets/index-4N_q9Ijm.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DCwOSe4Q.js","assets/hooks.module-Dz_XB4AG.js","assets/index-Cr5N_0pd.js","assets/index-BXHa4upX.css","assets/hashTypedData-D0Cx__mD.js","assets/index-Dl0F4g05.js","assets/index-COonna6N.js","assets/index-Cl4M8jG7.js","assets/index-sYri9oP4.js"])))=>i.map(i=>d[i]); +import{d as _,g as w,U as p,_ as m,S as y,C as A,n as C,P as g,w as P}from"./index-Cr5N_0pd.js";import{e as q}from"./index-Cr5N_0pd.js";I.type="coinbaseWallet";function I(a={}){return a.version==="3"||a.headlessMode?E(a):U(a)}function U(a){let f,u,d,c;return _(o=>({id:"coinbaseWalletSDK",name:"Coinbase Wallet",rdns:"com.coinbase.wallet",type:I.type,async connect({chainId:t,...r}={}){try{const e=await this.getProvider(),n=(await e.request({method:"eth_requestAccounts",params:"instantOnboarding"in r&&r.instantOnboarding?[{onboarding:"instant"}]:[]})).map(s=>w(s));u||(u=this.onAccountsChanged.bind(this),e.on("accountsChanged",u)),d||(d=this.onChainChanged.bind(this),e.on("chainChanged",d)),c||(c=this.onDisconnect.bind(this),e.on("disconnect",c));let i=await this.getChainId();return t&&i!==t&&(i=(await this.switchChain({chainId:t}).catch(l=>{if(l.code===p.code)throw l;return{id:i}}))?.id??i),{accounts:n,chainId:i}}catch(e){throw/(user closed modal|accounts received is empty|user denied account|request rejected)/i.test(e.message)?new p(e):e}},async disconnect(){const t=await this.getProvider();u&&(t.removeListener("accountsChanged",u),u=void 0),d&&(t.removeListener("chainChanged",d),d=void 0),c&&(t.removeListener("disconnect",c),c=void 0),t.disconnect(),t.close?.()},async getAccounts(){return(await(await this.getProvider()).request({method:"eth_accounts"})).map(r=>w(r))},async getChainId(){const r=await(await this.getProvider()).request({method:"eth_chainId"});return Number(r)},async getProvider(){if(!f){const t=typeof a.preference=="string"?{options:a.preference}:{...a.preference,options:a.preference?.options??"all"},{createCoinbaseWalletSDK:r}=await m(async()=>{const{createCoinbaseWalletSDK:n}=await import("./index-DCwOSe4Q.js");return{createCoinbaseWalletSDK:n}},__vite__mapDeps([0,1,2,3,4]));f=r({...a,appChainIds:o.chains.map(n=>n.id),preference:t}).getProvider()}return f},async isAuthorized(){try{return!!(await this.getAccounts()).length}catch{return!1}},async switchChain({addEthereumChainParameter:t,chainId:r}){const e=o.chains.find(i=>i.id===r);if(!e)throw new y(new A);const n=await this.getProvider();try{return await n.request({method:"wallet_switchEthereumChain",params:[{chainId:C(e.id)}]}),e}catch(i){if(i.code===4902)try{let s;t?.blockExplorerUrls?s=t.blockExplorerUrls:s=e.blockExplorers?.default.url?[e.blockExplorers?.default.url]:[];let l;t?.rpcUrls?.length?l=t.rpcUrls:l=[e.rpcUrls.default?.http[0]??""];const h={blockExplorerUrls:s,chainId:C(r),chainName:t?.chainName??e.name,iconUrls:t?.iconUrls,nativeCurrency:t?.nativeCurrency??e.nativeCurrency,rpcUrls:l};return await n.request({method:"wallet_addEthereumChain",params:[h]}),e}catch(s){throw new p(s)}throw new y(i)}},onAccountsChanged(t){t.length===0?this.onDisconnect():o.emitter.emit("change",{accounts:t.map(r=>w(r))})},onChainChanged(t){const r=Number(t);o.emitter.emit("change",{chainId:r})},async onDisconnect(t){o.emitter.emit("disconnect");const r=await this.getProvider();u&&(r.removeListener("accountsChanged",u),u=void 0),d&&(r.removeListener("chainChanged",d),d=void 0),c&&(r.removeListener("disconnect",c),c=void 0)}}))}function E(a){let u,d,c,o,t;return _(r=>({id:"coinbaseWalletSDK",name:"Coinbase Wallet",rdns:"com.coinbase.wallet",type:I.type,async connect({chainId:e}={}){try{const n=await this.getProvider(),i=(await n.request({method:"eth_requestAccounts"})).map(l=>w(l));c||(c=this.onAccountsChanged.bind(this),n.on("accountsChanged",c)),o||(o=this.onChainChanged.bind(this),n.on("chainChanged",o)),t||(t=this.onDisconnect.bind(this),n.on("disconnect",t));let s=await this.getChainId();return e&&s!==e&&(s=(await this.switchChain({chainId:e}).catch(h=>{if(h.code===p.code)throw h;return{id:s}}))?.id??s),{accounts:i,chainId:s}}catch(n){throw/(user closed modal|accounts received is empty|user denied account)/i.test(n.message)?new p(n):n}},async disconnect(){const e=await this.getProvider();c&&(e.removeListener("accountsChanged",c),c=void 0),o&&(e.removeListener("chainChanged",o),o=void 0),t&&(e.removeListener("disconnect",t),t=void 0),e.disconnect(),e.close()},async getAccounts(){return(await(await this.getProvider()).request({method:"eth_accounts"})).map(n=>w(n))},async getChainId(){const n=await(await this.getProvider()).request({method:"eth_chainId"});return Number(n)},async getProvider(){if(!d){const e=await(async()=>{const{default:h}=await m(async()=>{const{default:v}=await import("./index-Dl0F4g05.js").then(b=>b.i);return{default:v}},__vite__mapDeps([5,2,3,6,1]));return typeof h!="function"&&typeof h.default=="function"?h.default:h})();u=new e({...a,reloadOnDisconnect:!1});const n=u.walletExtension?.getChainId(),i=r.chains.find(h=>a.chainId?h.id===a.chainId:h.id===n)||r.chains[0],s=a.chainId||i?.id,l=a.jsonRpcUrl||i?.rpcUrls.default.http[0];d=u.makeWeb3Provider(l,s)}return d},async isAuthorized(){try{return!!(await this.getAccounts()).length}catch{return!1}},async switchChain({addEthereumChainParameter:e,chainId:n}){const i=r.chains.find(l=>l.id===n);if(!i)throw new y(new A);const s=await this.getProvider();try{return await s.request({method:"wallet_switchEthereumChain",params:[{chainId:C(i.id)}]}),i}catch(l){if(l.code===4902)try{let h;e?.blockExplorerUrls?h=e.blockExplorerUrls:h=i.blockExplorers?.default.url?[i.blockExplorers?.default.url]:[];let v;e?.rpcUrls?.length?v=e.rpcUrls:v=[i.rpcUrls.default?.http[0]??""];const b={blockExplorerUrls:h,chainId:C(n),chainName:e?.chainName??i.name,iconUrls:e?.iconUrls,nativeCurrency:e?.nativeCurrency??i.nativeCurrency,rpcUrls:v};return await s.request({method:"wallet_addEthereumChain",params:[b]}),i}catch(h){throw new p(h)}throw new y(l)}},onAccountsChanged(e){e.length===0?this.onDisconnect():r.emitter.emit("change",{accounts:e.map(n=>w(n))})},onChainChanged(e){const n=Number(e);r.emitter.emit("change",{chainId:n})},async onDisconnect(e){r.emitter.emit("disconnect");const n=await this.getProvider();c&&(n.removeListener("accountsChanged",c),c=void 0),o&&(n.removeListener("chainChanged",o),o=void 0),t&&(n.removeListener("disconnect",t),t=void 0)}}))}D.type="safe";function D(a={}){const{shimDisconnect:f=!1}=a;let u,d;return _(c=>({id:"safe",name:"Safe",type:D.type,async connect(){const o=await this.getProvider();if(!o)throw new g;const t=await this.getAccounts(),r=await this.getChainId();return d||(d=this.onDisconnect.bind(this),o.on("disconnect",d)),f&&await c.storage?.removeItem("safe.disconnected"),{accounts:t,chainId:r}},async disconnect(){const o=await this.getProvider();if(!o)throw new g;d&&(o.removeListener("disconnect",d),d=void 0),f&&await c.storage?.setItem("safe.disconnected",!0)},async getAccounts(){const o=await this.getProvider();if(!o)throw new g;return(await o.request({method:"eth_accounts"})).map(w)},async getProvider(){if(typeof window<"u"&&window?.parent!==window){if(!u){const{default:t}=await m(async()=>{const{default:i}=await import("./index-Cl4M8jG7.js").then(s=>s.e);return{default:i}},__vite__mapDeps([7,2,3,4])),r=new t(a),e=await P(()=>r.safe.getInfo(),{timeout:a.unstable_getInfoTimeout??10});if(!e)throw new Error("Could not load Safe information");const n=await(async()=>{const i=await m(()=>import("./index-sYri9oP4.js").then(s=>s.i),__vite__mapDeps([8,2,3,7,4]));return typeof i.SafeAppProvider!="function"&&typeof i.default.SafeAppProvider=="function"?i.default.SafeAppProvider:i.SafeAppProvider})();u=new n(e,r)}return u}},async getChainId(){const o=await this.getProvider();if(!o)throw new g;return Number(o.chainId)},async isAuthorized(){try{return f&&await c.storage?.getItem("safe.disconnected")?!1:!!(await this.getAccounts()).length}catch{return!1}},onAccountsChanged(){},onChainChanged(){},onDisconnect(){c.emitter.emit("disconnect")}}))}export{I as coinbaseWallet,q as injected,D as safe}; diff --git a/dist/assets/index-BGGOaaWA.js b/dist/assets/index-BGGOaaWA.js new file mode 100644 index 0000000..1320173 --- /dev/null +++ b/dist/assets/index-BGGOaaWA.js @@ -0,0 +1,143 @@ +import{aj as j,aC as S,L as O,K as y,Q as g,$ as h,aD as q,aE as B,D as z,G as X,J,a0 as P,ap as x,R as _,Y as E,T as G,i as W,a as F,x as d,a9 as v,aa as w,c as H,a8 as Z,O as Y,a6 as Q}from"./index-Cr5N_0pd.js";const r={INVALID_PAYMENT_CONFIG:"INVALID_PAYMENT_CONFIG",INVALID_RECIPIENT:"INVALID_RECIPIENT",INVALID_ASSET:"INVALID_ASSET",INVALID_AMOUNT:"INVALID_AMOUNT",UNKNOWN_ERROR:"UNKNOWN_ERROR",UNABLE_TO_INITIATE_PAYMENT:"UNABLE_TO_INITIATE_PAYMENT",INVALID_CHAIN_NAMESPACE:"INVALID_CHAIN_NAMESPACE",GENERIC_PAYMENT_ERROR:"GENERIC_PAYMENT_ERROR",UNABLE_TO_GET_EXCHANGES:"UNABLE_TO_GET_EXCHANGES",ASSET_NOT_SUPPORTED:"ASSET_NOT_SUPPORTED",UNABLE_TO_GET_PAY_URL:"UNABLE_TO_GET_PAY_URL",UNABLE_TO_GET_BUY_STATUS:"UNABLE_TO_GET_BUY_STATUS"},N={[r.INVALID_PAYMENT_CONFIG]:"Invalid payment configuration",[r.INVALID_RECIPIENT]:"Invalid recipient address",[r.INVALID_ASSET]:"Invalid asset specified",[r.INVALID_AMOUNT]:"Invalid payment amount",[r.UNKNOWN_ERROR]:"Unknown payment error occurred",[r.UNABLE_TO_INITIATE_PAYMENT]:"Unable to initiate payment",[r.INVALID_CHAIN_NAMESPACE]:"Invalid chain namespace",[r.GENERIC_PAYMENT_ERROR]:"Unable to process payment",[r.UNABLE_TO_GET_EXCHANGES]:"Unable to get exchanges",[r.ASSET_NOT_SUPPORTED]:"Asset not supported by the selected exchange",[r.UNABLE_TO_GET_PAY_URL]:"Unable to get payment URL",[r.UNABLE_TO_GET_BUY_STATUS]:"Unable to get buy status"};class c extends Error{get message(){return N[this.code]}constructor(e,a){super(N[e]),this.name="AppKitPayError",this.code=e,this.details=a,Error.captureStackTrace&&Error.captureStackTrace(this,c)}}const ee="https://rpc.walletconnect.org/v1/json-rpc";class te extends Error{}function ne(){const n=j.getSnapshot().projectId;return`${ee}?projectId=${n}`}async function L(n,e){const a=ne(),o=await(await fetch(a,{method:"POST",body:JSON.stringify({jsonrpc:"2.0",id:1,method:n,params:e}),headers:{"Content-Type":"application/json"}})).json();if(o.error)throw new te(o.error.message);return o}async function V(n){return(await L("reown_getExchanges",n)).result}async function ae(n){return(await L("reown_getExchangePayUrl",n)).result}async function se(n){return(await L("reown_getExchangeBuyStatus",n)).result}const re=["eip155","solana"],ie={eip155:{native:{assetNamespace:"slip44",assetReference:"60"},defaultTokenNamespace:"erc20"},solana:{native:{assetNamespace:"slip44",assetReference:"501"},defaultTokenNamespace:"token"}};function R(n,e){const{chainNamespace:a,chainId:s}=S.parseCaipNetworkId(n),i=ie[a];if(!i)throw new Error(`Unsupported chain namespace for CAIP-19 formatting: ${a}`);let o=i.native.assetNamespace,l=i.native.assetReference;return e!=="native"&&(o=i.defaultTokenNamespace,l=e),`${`${a}:${s}`}/${o}:${l}`}function oe(n){const{chainNamespace:e}=S.parseCaipNetworkId(n);return re.includes(e)}async function ce(n){const{paymentAssetNetwork:e,activeCaipNetwork:a,approvedCaipNetworkIds:s,requestedCaipNetworks:i}=n,l=O.sortRequestedNetworks(s,i).find(I=>I.caipNetworkId===e);if(!l)throw new c(r.INVALID_PAYMENT_CONFIG);if(l.caipNetworkId===a.caipNetworkId)return;const p=y.getNetworkProp("supportsAllNetworks",l.chainNamespace);if(!(s?.includes(l.caipNetworkId)||p))throw new c(r.INVALID_PAYMENT_CONFIG);try{await y.switchActiveNetwork(l)}catch(I){throw new c(r.GENERIC_PAYMENT_ERROR,I)}}async function ue(n,e,a){if(e!==g.CHAIN.EVM)throw new c(r.INVALID_CHAIN_NAMESPACE);if(!a.fromAddress)throw new c(r.INVALID_PAYMENT_CONFIG,"fromAddress is required for native EVM payments.");const s=typeof a.amount=="string"?parseFloat(a.amount):a.amount;if(isNaN(s))throw new c(r.INVALID_PAYMENT_CONFIG);const i=n.metadata?.decimals??18,o=h.parseUnits(s.toString(),i);if(typeof o!="bigint")throw new c(r.GENERIC_PAYMENT_ERROR);return await h.sendTransaction({chainNamespace:e,to:a.recipient,address:a.fromAddress,value:o,data:"0x"})??void 0}async function le(n,e){if(!e.fromAddress)throw new c(r.INVALID_PAYMENT_CONFIG,"fromAddress is required for ERC20 EVM payments.");const a=n.asset,s=e.recipient,i=Number(n.metadata.decimals),o=h.parseUnits(e.amount.toString(),i);if(o===void 0)throw new c(r.GENERIC_PAYMENT_ERROR);return await h.writeContract({fromAddress:e.fromAddress,tokenAddress:a,args:[s,o],method:"transfer",abi:q.getERC20Abi(a),chainNamespace:g.CHAIN.EVM})??void 0}async function de(n,e){if(n!==g.CHAIN.SOLANA)throw new c(r.INVALID_CHAIN_NAMESPACE);if(!e.fromAddress)throw new c(r.INVALID_PAYMENT_CONFIG,"fromAddress is required for Solana payments.");const a=typeof e.amount=="string"?parseFloat(e.amount):e.amount;if(isNaN(a)||a<=0)throw new c(r.INVALID_PAYMENT_CONFIG,"Invalid payment amount.");try{if(!B.getProvider(n))throw new c(r.GENERIC_PAYMENT_ERROR,"No Solana provider available.");const i=await h.sendTransaction({chainNamespace:g.CHAIN.SOLANA,to:e.recipient,value:a,tokenMint:e.tokenMint});if(!i)throw new c(r.GENERIC_PAYMENT_ERROR,"Transaction failed.");return i}catch(s){throw s instanceof c?s:new c(r.GENERIC_PAYMENT_ERROR,`Solana payment failed: ${s}`)}}const $=0,k="unknown",t=z({paymentAsset:{network:"eip155:1",asset:"0x0",metadata:{name:"0x0",symbol:"0x0",decimals:0}},recipient:"0x0",amount:0,isConfigured:!1,error:null,isPaymentInProgress:!1,exchanges:[],isLoading:!1,openInNewTab:!0,redirectUrl:void 0,payWithExchange:void 0,currentPayment:void 0,analyticsSet:!1,paymentId:void 0}),u={state:t,subscribe(n){return X(t,()=>n(t))},subscribeKey(n,e){return J(t,n,e)},async handleOpenPay(n){this.resetState(),this.setPaymentConfig(n),this.subscribeEvents(),this.initializeAnalytics(),t.isConfigured=!0,P.sendEvent({type:"track",event:"PAY_MODAL_OPEN",properties:{exchanges:t.exchanges,configuration:{network:t.paymentAsset.network,asset:t.paymentAsset.asset,recipient:t.recipient,amount:t.amount}}}),await x.open({view:"Pay"})},resetState(){t.paymentAsset={network:"eip155:1",asset:"0x0",metadata:{name:"0x0",symbol:"0x0",decimals:0}},t.recipient="0x0",t.amount=0,t.isConfigured=!1,t.error=null,t.isPaymentInProgress=!1,t.isLoading=!1,t.currentPayment=void 0},setPaymentConfig(n){if(!n.paymentAsset)throw new c(r.INVALID_PAYMENT_CONFIG);try{t.paymentAsset=n.paymentAsset,t.recipient=n.recipient,t.amount=n.amount,t.openInNewTab=n.openInNewTab??!0,t.redirectUrl=n.redirectUrl,t.payWithExchange=n.payWithExchange,t.error=null}catch(e){throw new c(r.INVALID_PAYMENT_CONFIG,e.message)}},getPaymentAsset(){return t.paymentAsset},getExchanges(){return t.exchanges},async fetchExchanges(){try{t.isLoading=!0;const n=await V({page:$,asset:R(t.paymentAsset.network,t.paymentAsset.asset),amount:t.amount.toString()});t.exchanges=n.exchanges.slice(0,2)}catch{throw _.showError(N.UNABLE_TO_GET_EXCHANGES),new c(r.UNABLE_TO_GET_EXCHANGES)}finally{t.isLoading=!1}},async getAvailableExchanges(n){try{const e=n?.asset&&n?.network?R(n.network,n.asset):void 0;return await V({page:n?.page??$,asset:e,amount:n?.amount?.toString()})}catch{throw new c(r.UNABLE_TO_GET_EXCHANGES)}},async getPayUrl(n,e,a=!1){try{const s=Number(e.amount),i=await ae({exchangeId:n,asset:R(e.network,e.asset),amount:s.toString(),recipient:`${e.network}:${e.recipient}`});return P.sendEvent({type:"track",event:"PAY_EXCHANGE_SELECTED",properties:{exchange:{id:n},configuration:{network:e.network,asset:e.asset,recipient:e.recipient,amount:s},currentPayment:{type:"exchange",exchangeId:n},headless:a}}),a&&(this.initiatePayment(),P.sendEvent({type:"track",event:"PAY_INITIATED",properties:{paymentId:t.paymentId||k,configuration:{network:e.network,asset:e.asset,recipient:e.recipient,amount:s},currentPayment:{type:"exchange",exchangeId:n}}})),i}catch(s){throw s instanceof Error&&s.message.includes("is not supported")?new c(r.ASSET_NOT_SUPPORTED):new Error(s.message)}},async openPayUrl(n,e,a=!1){try{const s=await this.getPayUrl(n.exchangeId,e,a);if(!s)throw new c(r.UNABLE_TO_GET_PAY_URL);const o=n.openInNewTab??!0?"_blank":"_self";return O.openHref(s.url,o),s}catch(s){throw s instanceof c?t.error=s.message:t.error=N.GENERIC_PAYMENT_ERROR,new c(r.UNABLE_TO_GET_PAY_URL)}},subscribeEvents(){t.isConfigured||(h.subscribeKey("connections",n=>{n.size>0&&this.handlePayment()}),E.subscribeKey("caipAddress",n=>{const e=h.hasAnyConnection(g.CONNECTOR_ID.WALLET_CONNECT);n&&(e?setTimeout(()=>{this.handlePayment()},100):this.handlePayment())}))},async handlePayment(){t.currentPayment={type:"wallet",status:"IN_PROGRESS"};const n=E.state.caipAddress;if(!n)return;const{chainId:e,address:a}=S.parseCaipAddress(n),s=y.state.activeChain;if(!a||!e||!s||!B.getProvider(s))return;const o=y.state.activeCaipNetwork;if(o&&!t.isPaymentInProgress)try{this.initiatePayment();const l=y.getAllRequestedCaipNetworks(),p=y.getAllApprovedCaipNetworkIds();switch(await ce({paymentAssetNetwork:t.paymentAsset.network,activeCaipNetwork:o,approvedCaipNetworkIds:p,requestedCaipNetworks:l}),await x.open({view:"PayLoading"}),s){case g.CHAIN.EVM:t.paymentAsset.asset==="native"&&(t.currentPayment.result=await ue(t.paymentAsset,s,{recipient:t.recipient,amount:t.amount,fromAddress:a})),t.paymentAsset.asset.startsWith("0x")&&(t.currentPayment.result=await le(t.paymentAsset,{recipient:t.recipient,amount:t.amount,fromAddress:a})),t.currentPayment.status="SUCCESS";break;case g.CHAIN.SOLANA:t.currentPayment.result=await de(s,{recipient:t.recipient,amount:t.amount,fromAddress:a,tokenMint:t.paymentAsset.asset==="native"?void 0:t.paymentAsset.asset}),t.currentPayment.status="SUCCESS";break;default:throw new c(r.INVALID_CHAIN_NAMESPACE)}}catch(l){l instanceof c?t.error=l.message:t.error=N.GENERIC_PAYMENT_ERROR,t.currentPayment.status="FAILED",_.showError(t.error)}finally{t.isPaymentInProgress=!1}},getExchangeById(n){return t.exchanges.find(e=>e.id===n)},validatePayConfig(n){const{paymentAsset:e,recipient:a,amount:s}=n;if(!e)throw new c(r.INVALID_PAYMENT_CONFIG);if(!a)throw new c(r.INVALID_RECIPIENT);if(!e.asset)throw new c(r.INVALID_ASSET);if(s==null||s<=0)throw new c(r.INVALID_AMOUNT)},handlePayWithWallet(){const n=E.state.caipAddress;if(!n){G.push("Connect");return}const{chainId:e,address:a}=S.parseCaipAddress(n),s=y.state.activeChain;if(!a||!e||!s){G.push("Connect");return}this.handlePayment()},async handlePayWithExchange(n){try{t.currentPayment={type:"exchange",exchangeId:n};const{network:e,asset:a}=t.paymentAsset,s={network:e,asset:a,amount:t.amount,recipient:t.recipient},i=await this.getPayUrl(n,s);if(!i)throw new c(r.UNABLE_TO_INITIATE_PAYMENT);return t.currentPayment.sessionId=i.sessionId,t.currentPayment.status="IN_PROGRESS",t.currentPayment.exchangeId=n,this.initiatePayment(),{url:i.url,openInNewTab:t.openInNewTab}}catch(e){return e instanceof c?t.error=e.message:t.error=N.GENERIC_PAYMENT_ERROR,t.isPaymentInProgress=!1,_.showError(t.error),null}},async getBuyStatus(n,e){try{const a=await se({sessionId:e,exchangeId:n});return(a.status==="SUCCESS"||a.status==="FAILED")&&P.sendEvent({type:"track",event:a.status==="SUCCESS"?"PAY_SUCCESS":"PAY_ERROR",properties:{paymentId:t.paymentId||k,configuration:{network:t.paymentAsset.network,asset:t.paymentAsset.asset,recipient:t.recipient,amount:t.amount},currentPayment:{type:"exchange",exchangeId:t.currentPayment?.exchangeId,sessionId:t.currentPayment?.sessionId,result:a.txHash}}}),a}catch{throw new c(r.UNABLE_TO_GET_BUY_STATUS)}},async updateBuyStatus(n,e){try{const a=await this.getBuyStatus(n,e);t.currentPayment&&(t.currentPayment.status=a.status,t.currentPayment.result=a.txHash),(a.status==="SUCCESS"||a.status==="FAILED")&&(t.isPaymentInProgress=!1)}catch{throw new c(r.UNABLE_TO_GET_BUY_STATUS)}},initiatePayment(){t.isPaymentInProgress=!0,t.paymentId=crypto.randomUUID()},initializeAnalytics(){t.analyticsSet||(t.analyticsSet=!0,this.subscribeKey("isPaymentInProgress",n=>{if(t.currentPayment?.status&&t.currentPayment.status!=="UNKNOWN"){const e={IN_PROGRESS:"PAY_INITIATED",SUCCESS:"PAY_SUCCESS",FAILED:"PAY_ERROR"}[t.currentPayment.status];P.sendEvent({type:"track",event:e,properties:{paymentId:t.paymentId||k,configuration:{network:t.paymentAsset.network,asset:t.paymentAsset.asset,recipient:t.recipient,amount:t.amount},currentPayment:{type:t.currentPayment.type,exchangeId:t.currentPayment.exchangeId,sessionId:t.currentPayment.sessionId,result:t.currentPayment.result}}})}}))}},pe=W` + wui-separator { + margin: var(--wui-spacing-m) calc(var(--wui-spacing-m) * -1) var(--wui-spacing-xs) + calc(var(--wui-spacing-m) * -1); + width: calc(100% + var(--wui-spacing-s) * 2); + } + + .token-display { + padding: var(--wui-spacing-s) var(--wui-spacing-m); + border-radius: var(--wui-border-radius-s); + background-color: var(--wui-color-bg-125); + margin-top: var(--wui-spacing-s); + margin-bottom: var(--wui-spacing-s); + } + + .token-display wui-text { + text-transform: none; + } + + wui-loading-spinner { + padding: var(--wui-spacing-xs); + } +`;var f=function(n,e,a,s){var i=arguments.length,o=i<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,a):s,l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,a,s);else for(var p=n.length-1;p>=0;p--)(l=n[p])&&(o=(i<3?l(o):i>3?l(e,a,o):l(e,a))||o);return i>3&&o&&Object.defineProperty(e,a,o),o};let m=class extends F{constructor(){super(),this.unsubscribe=[],this.amount="",this.tokenSymbol="",this.networkName="",this.exchanges=u.state.exchanges,this.isLoading=u.state.isLoading,this.loadingExchangeId=null,this.connectedWalletInfo=E.state.connectedWalletInfo,this.initializePaymentDetails(),this.unsubscribe.push(u.subscribeKey("exchanges",e=>this.exchanges=e)),this.unsubscribe.push(u.subscribeKey("isLoading",e=>this.isLoading=e)),this.unsubscribe.push(E.subscribe(e=>this.connectedWalletInfo=e.connectedWalletInfo)),u.fetchExchanges()}get isWalletConnected(){return E.state.status==="connected"}render(){return d` + + + ${this.renderPaymentHeader()} + + + ${this.renderPayWithWallet()} ${this.renderExchangeOptions()} + + + + `}initializePaymentDetails(){const e=u.getPaymentAsset();this.networkName=e.network,this.tokenSymbol=e.metadata.symbol,this.amount=u.state.amount.toString()}renderPayWithWallet(){return oe(this.networkName)?d` + ${this.isWalletConnected?this.renderConnectedView():this.renderDisconnectedView()} + + `:d``}renderPaymentHeader(){let e=this.networkName;if(this.networkName){const s=y.getAllRequestedCaipNetworks().find(i=>i.caipNetworkId===this.networkName);s&&(e=s.name)}return d` + + + ${this.amount||"0.0000"} + + + ${this.tokenSymbol||"Unknown Asset"} + + ${e?d` + on ${e} + `:""} + + + + `}renderConnectedView(){const e=this.connectedWalletInfo?.name||"connected wallet";return d` + + + + Pay with ${e} + + + + + Disconnect + + `}renderDisconnectedView(){return d` + Pay from wallet + `}renderExchangeOptions(){return this.isLoading?d` + + `:this.exchanges.length===0?d` + No exchanges available + `:this.exchanges.map(e=>d` + this.onExchangePayment(e.id)} + data-testid="exchange-option-${e.id}" + ?chevron=${!0} + ?disabled=${this.loadingExchangeId!==null} + > + + ${this.loadingExchangeId===e.id?d``:d``} + Pay with ${e.name} + + + `)}onWalletPayment(){u.handlePayWithWallet()}async onExchangePayment(e){try{this.loadingExchangeId=e;const a=await u.handlePayWithExchange(e);a&&(await x.open({view:"PayLoading"}),O.openHref(a.url,a.openInNewTab?"_blank":"_self"))}catch(a){console.error("Failed to pay with exchange",a),_.showError("Failed to pay with exchange")}finally{this.loadingExchangeId=null}}async onDisconnect(e){e.stopPropagation();try{await h.disconnect()}catch{console.error("Failed to disconnect"),_.showError("Failed to disconnect")}}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}};m.styles=pe;f([w()],m.prototype,"amount",void 0);f([w()],m.prototype,"tokenSymbol",void 0);f([w()],m.prototype,"networkName",void 0);f([w()],m.prototype,"exchanges",void 0);f([w()],m.prototype,"isLoading",void 0);f([w()],m.prototype,"loadingExchangeId",void 0);f([w()],m.prototype,"connectedWalletInfo",void 0);m=f([H("w3m-pay-view")],m);const me=W` + :host { + display: block; + height: 100%; + width: 100%; + } + + wui-flex:first-child:not(:only-child) { + position: relative; + } + + wui-loading-thumbnail { + position: absolute; + } +`;var b=function(n,e,a,s){var i=arguments.length,o=i<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,a):s,l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,a,s);else for(var p=n.length-1;p>=0;p--)(l=n[p])&&(o=(i<3?l(o):i>3?l(e,a,o):l(e,a))||o);return i>3&&o&&Object.defineProperty(e,a,o),o};const we=4e3;let A=class extends F{constructor(){super(),this.loadingMessage="",this.subMessage="",this.paymentState="in-progress",this.paymentState=u.state.isPaymentInProgress?"in-progress":"completed",this.updateMessages(),this.setupSubscription(),this.setupExchangeSubscription()}disconnectedCallback(){clearInterval(this.exchangeSubscription)}render(){return d` + + ${this.getStateIcon()} + + + ${this.loadingMessage} + + + ${this.subMessage} + + + + `}updateMessages(){switch(this.paymentState){case"completed":this.loadingMessage="Payment completed",this.subMessage="Your transaction has been successfully processed";break;case"error":this.loadingMessage="Payment failed",this.subMessage="There was an error processing your transaction";break;case"in-progress":default:u.state.currentPayment?.type==="exchange"?(this.loadingMessage="Payment initiated",this.subMessage="Please complete the payment on the exchange"):(this.loadingMessage="Awaiting payment confirmation",this.subMessage="Please confirm the payment transaction in your wallet");break}}getStateIcon(){switch(this.paymentState){case"completed":return this.successTemplate();case"error":return this.errorTemplate();case"in-progress":default:return this.loaderTemplate()}}setupExchangeSubscription(){u.state.currentPayment?.type==="exchange"&&(this.exchangeSubscription=setInterval(async()=>{const e=u.state.currentPayment?.exchangeId,a=u.state.currentPayment?.sessionId;e&&a&&(await u.updateBuyStatus(e,a),u.state.currentPayment?.status==="SUCCESS"&&clearInterval(this.exchangeSubscription))},we))}setupSubscription(){u.subscribeKey("isPaymentInProgress",e=>{!e&&this.paymentState==="in-progress"&&(u.state.error||!u.state.currentPayment?.result?this.paymentState="error":this.paymentState="completed",this.updateMessages(),setTimeout(()=>{h.state.status!=="disconnected"&&x.close()},3e3))}),u.subscribeKey("error",e=>{e&&this.paymentState==="in-progress"&&(this.paymentState="error",this.updateMessages())})}loaderTemplate(){const e=Z.state.themeVariables["--w3m-border-radius-master"],a=e?parseInt(e.replace("px",""),10):4,s=this.getPaymentIcon();return d` + + ${s?d``:null} + + + `}getPaymentIcon(){const e=u.state.currentPayment;if(e){if(e.type==="exchange"){const a=e.exchangeId;if(a)return u.getExchangeById(a)?.imageUrl}if(e.type==="wallet"){const a=E.state.connectedWalletInfo?.icon;if(a)return a;const s=y.state.activeChain;if(!s)return;const i=Y.getConnectorId(s);if(!i)return;const o=Y.getConnectorById(i);return o?Q.getConnectorImage(o):void 0}}}successTemplate(){return d``}errorTemplate(){return d``}};A.styles=me;b([w()],A.prototype,"loadingMessage",void 0);b([w()],A.prototype,"subMessage",void 0);b([w()],A.prototype,"paymentState",void 0);A=b([H("w3m-pay-loading-view")],A);const ye=3e5;async function he(n){return u.handleOpenPay(n)}async function Ae(n,e=ye){if(e<=0)throw new c(r.INVALID_PAYMENT_CONFIG,"Timeout must be greater than 0");try{await he(n)}catch(a){throw a instanceof c?a:new c(r.UNABLE_TO_INITIATE_PAYMENT,a.message)}return new Promise((a,s)=>{let i=!1;const o=setTimeout(()=>{i||(i=!0,T(),s(new c(r.GENERIC_PAYMENT_ERROR,"Payment timeout")))},e);function l(){if(i)return;const C=u.state.currentPayment,U=u.state.error,K=u.state.isPaymentInProgress;if(C?.status==="SUCCESS"){i=!0,T(),clearTimeout(o),a({success:!0,result:C.result});return}if(C?.status==="FAILED"){i=!0,T(),clearTimeout(o),a({success:!1,error:U||"Payment failed"});return}U&&!K&&!C&&(i=!0,T(),clearTimeout(o),a({success:!1,error:U}))}const p=D("currentPayment",l),M=D("error",l),I=D("isPaymentInProgress",l),T=fe([p,M,I]);l()})}function Ie(){return u.getExchanges()}function Pe(){return u.state.currentPayment?.result}function _e(){return u.state.error}function Te(){return u.state.isPaymentInProgress}function D(n,e){return u.subscribeKey(n,e)}function fe(n){return()=>{n.forEach(e=>{try{e()}catch{}})}}const Ce={network:"eip155:8453",asset:"native",metadata:{name:"Ethereum",symbol:"ETH",decimals:18}},Se={network:"eip155:8453",asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},xe={network:"eip155:84532",asset:"native",metadata:{name:"Ethereum",symbol:"ETH",decimals:18}},be={network:"eip155:1",asset:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},Ue={network:"eip155:10",asset:"0x0b2c639c533813f4aa9d7837caf62653d097ff85",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},ve={network:"eip155:42161",asset:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},Re={network:"eip155:137",asset:"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},ke={network:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",asset:"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},De={network:"eip155:1",asset:"0xdAC17F958D2ee523a2206206994597C13D831ec7",metadata:{name:"Tether USD",symbol:"USDT",decimals:6}},Oe={network:"eip155:10",asset:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",metadata:{name:"Tether USD",symbol:"USDT",decimals:6}},Le={network:"eip155:42161",asset:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",metadata:{name:"Tether USD",symbol:"USDT",decimals:6}},Me={network:"eip155:137",asset:"0xc2132d05d31c914a87c6611c10748aeb04b58e8f",metadata:{name:"Tether USD",symbol:"USDT",decimals:6}},Ge={network:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",asset:"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB",metadata:{name:"Tether USD",symbol:"USDT",decimals:6}};export{A as W3mPayLoadingView,m as W3mPayView,ve as arbitrumUSDC,Le as arbitrumUSDT,Ce as baseETH,xe as baseSepoliaETH,Se as baseUSDC,be as ethereumUSDC,De as ethereumUSDT,Ie as getExchanges,Te as getIsPaymentInProgress,_e as getPayError,Pe as getPayResult,he as openPay,Ue as optimismUSDC,Oe as optimismUSDT,Ae as pay,Re as polygonUSDC,Me as polygonUSDT,ke as solanaUSDC,Ge as solanaUSDT}; diff --git a/dist/assets/index-BXHa4upX.css b/dist/assets/index-BXHa4upX.css new file mode 100644 index 0000000..eafecdf --- /dev/null +++ b/dist/assets/index-BXHa4upX.css @@ -0,0 +1 @@ +@import"https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600;700&family=Inter:wght@300;400;500;600;700&display=swap";*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Inter,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:JetBrains Mono,Menlo,Monaco,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}:root{--background: 226 20% 12%;--foreground: 0 0% 95%;--card: 226 20% 12%;--card-foreground: 0 0% 94%;--popover: 226 20% 18%;--popover-foreground: 0 0% 94%;--primary: 195 82% 42%;--primary-foreground: 0 0% 98%;--secondary: 226 20% 18%;--secondary-foreground: 0 0% 94%;--muted: 226 13% 27%;--muted-foreground: 225 6% 57%;--accent: 195 82% 42%;--accent-foreground: 0 0% 98%;--destructive: 0 84% 60%;--destructive-foreground: 0 0% 98%;--border: 226 13% 27%;--input: 226 13% 27%;--ring: 195 82% 42%;--radius: .25rem;--sidebar-background: 226 20% 14%;--sidebar-foreground: 0 0% 94%;--sidebar-primary: 195 82% 42%;--sidebar-primary-foreground: 0 0% 98%;--sidebar-accent: 226 20% 18%;--sidebar-accent-foreground: 0 0% 94%;--sidebar-border: 226 13% 27%;--sidebar-ring: 195 82% 42%}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));font-family:JetBrains Mono,Menlo,Monaco,Courier New,monospace;color:hsl(var(--foreground));font-family:IBM Plex Mono,Inter,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Open Sans,Helvetica Neue,sans-serif}::-webkit-scrollbar{width:8px}::-webkit-scrollbar-track{background:hsl(var(--secondary))}::-webkit-scrollbar-thumb{background:hsl(var(--muted));border-radius:3px}::-webkit-scrollbar-thumb:hover{background:hsl(var(--muted-foreground))}*:focus-visible{outline:2px solid transparent;outline-offset:2px;--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000);--tw-ring-color: hsl(var(--primary) / .7);--tw-ring-offset-width: 1px;--tw-ring-offset-color: hsl(var(--background))}h1,h2,h3,h4,h5,h6,button,input,textarea{font-family:JetBrains Mono,Menlo,Monaco,Courier New,monospace}.container{width:100%;margin-right:auto;margin-left:auto;padding-right:2rem;padding-left:2rem}@media (min-width: 1400px){.container{max-width:1400px}}.page-container{display:flex;min-height:100vh;flex-direction:column;--tw-bg-opacity: 1;background-color:rgb(26 31 44 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.page-header{margin-bottom:2rem}.page-title{margin-bottom:.5rem;font-family:JetBrains Mono,Menlo,Monaco,Courier New,monospace;font-size:1.875rem;line-height:2.25rem;font-weight:700;--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.page-subtitle{--tw-text-opacity: 1;color:rgb(142 145 150 / var(--tw-text-opacity, 1))}.page-content{flex:1 1 0%;padding-top:4rem}.page-main{width:100%;margin-right:auto;margin-left:auto;padding-right:2rem;padding-left:2rem}@media (min-width: 1400px){.page-main{max-width:1400px}}.page-main{margin-left:auto;margin-right:auto;max-width:72rem;padding:2rem 1rem}.page-footer{border-top-width:1px;--tw-border-opacity: 1;border-color:rgb(58 63 76 / var(--tw-border-opacity, 1));padding-top:1rem;padding-bottom:1rem;text-align:center;font-size:.75rem;line-height:1rem;--tw-text-opacity: 1;color:rgb(142 145 150 / var(--tw-text-opacity, 1))}.thread-card{border-radius:calc(var(--radius) - 4px);border-width:1px;border-color:#3a3f4c4d;background-color:#3a3f4c33;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.2s;animation-duration:.2s}.thread-card:hover{border-color:#0fa0ce80;background-color:#3a3f4c4d}.thread-card{padding:1rem;margin-bottom:1rem}.board-card{border-radius:calc(var(--radius) - 4px);border-width:1px;border-color:#3a3f4c4d;background-color:#3a3f4c33;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.2s;animation-duration:.2s}.board-card:hover{border-color:#0fa0ce80;background-color:#3a3f4c4d}.board-card{padding:1rem;margin-bottom:.75rem}.content-card{border-radius:calc(var(--radius) - 4px);border-width:1px;border-color:#3a3f4c4d;background-color:#3a3f4c33;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.2s;animation-duration:.2s}.content-card:hover{border-color:#0fa0ce80;background-color:#3a3f4c4d}.content-card{padding:1.5rem}.content-card-sm{border-radius:calc(var(--radius) - 4px);border-width:1px;border-color:#3a3f4c4d;background-color:#3a3f4c33;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.2s;animation-duration:.2s}.content-card-sm:hover{border-color:#0fa0ce80;background-color:#3a3f4c4d}.content-card-sm{padding:1rem}.text-glow{text-shadow:0 0 8px rgba(15,160,206,.5)}.section-spacing{margin-bottom:2rem}.content-spacing{margin-bottom:1.5rem}.grid-main-sidebar{display:grid;grid-template-columns:repeat(1,minmax(0,1fr));gap:1.5rem}@media (min-width: 1024px){.grid-main-sidebar{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-main-content{grid-column:span 2 / span 2}.grid-sidebar{grid-column:span 1 / span 1}}.empty-state{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:4rem 1rem;text-align:center}.empty-state-icon{margin-bottom:1rem;height:4rem;width:4rem;color:#0fa0ce80}.empty-state-title{margin-bottom:.5rem;font-family:JetBrains Mono,Menlo,Monaco,Courier New,monospace;font-size:1.25rem;line-height:1.75rem;font-weight:700;--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.empty-state-description{margin-bottom:1rem;--tw-text-opacity: 1;color:rgb(142 145 150 / var(--tw-text-opacity, 1))}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.invisible{visibility:hidden}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{inset:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.-bottom-12{bottom:-3rem}.-bottom-2{bottom:-.5rem}.-left-12{left:-3rem}.-left-2{left:-.5rem}.-right-12{right:-3rem}.-right-2{right:-.5rem}.-top-12{top:-3rem}.-top-2{top:-.5rem}.bottom-0{bottom:0}.bottom-4{bottom:1rem}.left-0{left:0}.left-1{left:.25rem}.left-1\/2{left:50%}.left-2{left:.5rem}.left-\[50\%\]{left:50%}.right-0{right:0}.right-1{right:.25rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.top-0{top:0}.top-1\.5{top:.375rem}.top-1\/2{top:50%}.top-2{top:.5rem}.top-3\.5{top:.875rem}.top-4{top:1rem}.top-\[1px\]{top:1px}.top-\[50\%\]{top:50%}.top-\[60\%\]{top:60%}.top-full{top:100%}.z-0{z-index:0}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[1\]{z-index:1}.col-span-2{grid-column:span 2 / span 2}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-3\.5{margin-left:.875rem;margin-right:.875rem}.mx-auto{margin-left:auto;margin-right:auto}.my-0\.5{margin-top:.125rem;margin-bottom:.125rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.-ml-4{margin-left:-1rem}.-mt-4{margin-top:-1rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-2{margin-left:.5rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mt-1{margin-top:.25rem}.mt-1\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-24{margin-top:6rem}.mt-4{margin-top:1rem}.mt-auto{margin-top:auto}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.line-clamp-3{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3}.block{display:block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:16 / 9}.size-4{width:1rem;height:1rem}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[1px\]{height:1px}.h-\[400px\]{height:400px}.h-\[var\(--radix-navigation-menu-viewport-height\)\]{height:var(--radix-navigation-menu-viewport-height)}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-auto{height:auto}.h-full{height:100%}.h-px{height:1px}.h-svh{height:100svh}.max-h-96{max-height:24rem}.max-h-\[300px\]{max-height:300px}.max-h-\[80vh\]{max-height:80vh}.max-h-screen{max-height:100vh}.min-h-0{min-height:0px}.min-h-\[80px\]{min-height:80px}.min-h-screen{min-height:100vh}.min-h-svh{min-height:100svh}.w-0{width:0px}.w-1{width:.25rem}.w-1\/2{width:50%}.w-1\/3{width:33.333333%}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-2\/3{width:66.666667%}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-3\/4{width:75%}.w-32{width:8rem}.w-4{width:1rem}.w-40{width:10rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-8{width:2rem}.w-80{width:20rem}.w-9{width:2.25rem}.w-\[--sidebar-width\]{width:var(--sidebar-width)}.w-\[100px\]{width:100px}.w-\[1px\]{width:1px}.w-auto{width:auto}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.w-px{width:1px}.min-w-0{min-width:0px}.min-w-5{min-width:1.25rem}.min-w-\[12rem\]{min-width:12rem}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-6xl{max-width:72rem}.max-w-\[--skeleton-width\]{max-width:var(--skeleton-width)}.max-w-lg{max-width:32rem}.max-w-max{max-width:-moz-max-content;max-width:max-content}.max-w-md{max-width:28rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.flex-shrink-0,.shrink-0{flex-shrink:0}.grow{flex-grow:1}.grow-0{flex-grow:0}.basis-full{flex-basis:100%}.caption-bottom{caption-side:bottom}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-x-px{--tw-translate-x: -1px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-\[-50\%\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-px{--tw-translate-x: 1px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\[-50\%\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-45{--tw-rotate: 45deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.list-none{list-style-type:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-t-\[10px\]{border-top-left-radius:10px;border-top-right-radius:10px}.rounded-tl-sm{border-top-left-radius:calc(var(--radius) - 4px)}.border{border-width:1px}.border-0{border-width:0px}.border-2{border-width:2px}.border-\[1\.5px\]{border-width:1.5px}.border-y{border-top-width:1px;border-bottom-width:1px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-\[--color-border\]{border-color:var(--color-border)}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-border\/50{border-color:hsl(var(--border) / .5)}.border-current{border-color:currentColor}.border-cyber-accent{--tw-border-opacity: 1;border-color:rgb(15 160 206 / var(--tw-border-opacity, 1))}.border-cyber-accent\/30{border-color:#0fa0ce4d}.border-cyber-muted{--tw-border-opacity: 1;border-color:rgb(58 63 76 / var(--tw-border-opacity, 1))}.border-cyber-muted\/20{border-color:#3a3f4c33}.border-cyber-muted\/30{border-color:#3a3f4c4d}.border-destructive{border-color:hsl(var(--destructive))}.border-destructive\/50{border-color:hsl(var(--destructive) / .5)}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-green-500\/30{border-color:#22c55e4d}.border-input{border-color:hsl(var(--input))}.border-muted{border-color:hsl(var(--muted))}.border-neutral-600{--tw-border-opacity: 1;border-color:rgb(82 82 82 / var(--tw-border-opacity, 1))}.border-neutral-700{--tw-border-opacity: 1;border-color:rgb(64 64 64 / var(--tw-border-opacity, 1))}.border-neutral-800{--tw-border-opacity: 1;border-color:rgb(38 38 38 / var(--tw-border-opacity, 1))}.border-orange-500\/30{border-color:#f973164d}.border-primary{border-color:hsl(var(--primary))}.border-red-400{--tw-border-opacity: 1;border-color:rgb(248 113 113 / var(--tw-border-opacity, 1))}.border-red-400\/30{border-color:#f871714d}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-red-500\/30{border-color:#ef44444d}.border-sidebar-border{border-color:hsl(var(--sidebar-border))}.border-transparent{border-color:transparent}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.border-yellow-500\/30{border-color:#eab3084d}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[--color-bg\]{background-color:var(--color-bg)}.bg-accent{background-color:hsl(var(--accent))}.bg-background{background-color:hsl(var(--background))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/80{background-color:#000c}.bg-black\/95{background-color:#000000f2}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-cyan-500{--tw-bg-opacity: 1;background-color:rgb(6 182 212 / var(--tw-bg-opacity, 1))}.bg-cyber-accent{--tw-bg-opacity: 1;background-color:rgb(15 160 206 / var(--tw-bg-opacity, 1))}.bg-cyber-accent\/10{background-color:#0fa0ce1a}.bg-cyber-accent\/20{background-color:#0fa0ce33}.bg-cyber-dark{--tw-bg-opacity: 1;background-color:rgb(26 31 44 / var(--tw-bg-opacity, 1))}.bg-cyber-dark\/50{background-color:#1a1f2c80}.bg-cyber-muted{--tw-bg-opacity: 1;background-color:rgb(58 63 76 / var(--tw-bg-opacity, 1))}.bg-cyber-muted\/10{background-color:#3a3f4c1a}.bg-cyber-muted\/20{background-color:#3a3f4c33}.bg-cyber-muted\/30{background-color:#3a3f4c4d}.bg-cyber-muted\/50{background-color:#3a3f4c80}.bg-destructive{background-color:hsl(var(--destructive))}.bg-foreground{background-color:hsl(var(--foreground))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-500\/10{background-color:#22c55e1a}.bg-green-500\/20{background-color:#22c55e33}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.bg-green-900\/20{background-color:#14532d33}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\/50{background-color:hsl(var(--muted) / .5)}.bg-neutral-800{--tw-bg-opacity: 1;background-color:rgb(38 38 38 / var(--tw-bg-opacity, 1))}.bg-neutral-900{--tw-bg-opacity: 1;background-color:rgb(23 23 23 / var(--tw-bg-opacity, 1))}.bg-neutral-900\/50{background-color:#17171780}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-orange-500\/10{background-color:#f973161a}.bg-orange-500\/20{background-color:#f9731633}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-500\/10{background-color:#ef44441a}.bg-red-500\/20{background-color:#ef444433}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-secondary{background-color:hsl(var(--secondary))}.bg-sidebar{background-color:hsl(var(--sidebar-background))}.bg-sidebar-border{background-color:hsl(var(--sidebar-border))}.bg-transparent{background-color:transparent}.bg-yellow-100{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-500\/20{background-color:#eab30833}.bg-yellow-900\/20{background-color:#713f1233}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-orange-500{--tw-gradient-from: #f97316 var(--tw-gradient-from-position);--tw-gradient-to: rgb(249 115 22 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-600{--tw-gradient-from: #9333ea var(--tw-gradient-from-position);--tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-transparent{--tw-gradient-from: transparent var(--tw-gradient-from-position);--tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-cyan-400{--tw-gradient-to: rgb(34 211 238 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #22d3ee var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-blue-600{--tw-gradient-to: #2563eb var(--tw-gradient-to-position)}.to-orange-600{--tw-gradient-to: #ea580c var(--tw-gradient-to-position)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.fill-current{fill:currentColor}.object-cover{-o-object-fit:cover;object-fit:cover}.p-0{padding:0}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.p-\[1px\]{padding:1px}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-16{padding-bottom:4rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pl-2\.5{padding-left:.625rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pr-2{padding-right:.5rem}.pr-2\.5{padding-right:.625rem}.pr-8{padding-right:2rem}.pt-0{padding-top:0}.pt-1{padding-top:.25rem}.pt-16{padding-top:4rem}.pt-2{padding-top:.5rem}.pt-24{padding-top:6rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.align-middle{vertical-align:middle}.font-mono{font-family:JetBrains Mono,Menlo,Monaco,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-\[0\.8rem\]{font-size:.8rem}.text-\[10px\]{font-size:10px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.ordinal{--tw-ordinal: ordinal;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-accent-foreground{color:hsl(var(--accent-foreground))}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-current{color:currentColor}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-cyber-accent{--tw-text-opacity: 1;color:rgb(15 160 206 / var(--tw-text-opacity, 1))}.text-cyber-accent\/50{color:#0fa0ce80}.text-cyber-light{--tw-text-opacity: 1;color:rgb(241 241 241 / var(--tw-text-opacity, 1))}.text-cyber-neutral{--tw-text-opacity: 1;color:rgb(142 145 150 / var(--tw-text-opacity, 1))}.text-cyber-neutral\/50{color:#8e919680}.text-cyber-neutral\/70{color:#8e9196b3}.text-cyber-neutral\/80{color:#8e9196cc}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\/50{color:hsl(var(--foreground) / .5)}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-indigo-500{--tw-text-opacity: 1;color:rgb(99 102 241 / var(--tw-text-opacity, 1))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-neutral-300{--tw-text-opacity: 1;color:rgb(212 212 212 / var(--tw-text-opacity, 1))}.text-neutral-400{--tw-text-opacity: 1;color:rgb(163 163 163 / var(--tw-text-opacity, 1))}.text-neutral-500{--tw-text-opacity: 1;color:rgb(115 115 115 / var(--tw-text-opacity, 1))}.text-orange-400{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.text-orange-500{--tw-text-opacity: 1;color:rgb(249 115 22 / var(--tw-text-opacity, 1))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-sidebar-foreground{color:hsl(var(--sidebar-foreground))}.text-sidebar-foreground\/70{color:hsl(var(--sidebar-foreground) / .7)}.text-teal-500{--tw-text-opacity: 1;color:rgb(20 184 166 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.text-yellow-500{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.text-yellow-800{--tw-text-opacity: 1;color:rgb(133 77 14 / var(--tw-text-opacity, 1))}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-80{opacity:.8}.opacity-90{opacity:.9}.mix-blend-overlay{mix-blend-mode:overlay}.shadow-\[0_0_0_1px_hsl\(var\(--sidebar-border\)\)\]{--tw-shadow: 0 0 0 1px hsl(var(--sidebar-border));--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-ring{--tw-ring-color: hsl(var(--ring))}.ring-sidebar-ring{--tw-ring-color: hsl(var(--sidebar-ring))}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.blur-xl{--tw-blur: blur(24px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[left\,right\,width\]{transition-property:left,right,width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[margin\,opa\]{transition-property:margin,opa;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[width\,height\,padding\]{transition-property:width,height,padding;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[width\]{transition-property:width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-1000{transition-duration:1s}.duration-200{transition-duration:.2s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.ease-linear{transition-timing-function:linear}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in-0{--tw-enter-opacity: 0}.fade-in-80{--tw-enter-opacity: .8}.zoom-in-95{--tw-enter-scale: .95}.duration-1000{animation-duration:1s}.duration-200{animation-duration:.2s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.ease-linear{animation-timing-function:linear}@keyframes cyber-flicker{0%,to{opacity:1;filter:drop-shadow(0 0 2px rgba(0,255,255,.8))}8%,10%{opacity:.8;filter:drop-shadow(0 0 5px rgba(0,255,255,.8))}20%,25%{opacity:1;filter:drop-shadow(0 0 1px rgba(0,255,255,.5))}30%{opacity:.6;filter:drop-shadow(0 0 8px rgba(0,255,255,1))}40%,45%{opacity:1;filter:drop-shadow(0 0 2px rgba(0,255,255,.6))}50%,55%{opacity:.9;filter:drop-shadow(0 0 3px rgba(0,255,255,.8))}60%,to{opacity:1;filter:drop-shadow(0 0 2px rgba(0,255,255,.6))}}.cyberpunk-glow{animation:cyber-flicker 8s infinite;will-change:filter,opacity}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.file\:text-foreground::file-selector-button{color:hsl(var(--foreground))}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:-inset-2:after{content:var(--tw-content);inset:-.5rem}.after\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:.25rem}.after\:w-\[2px\]:after{content:var(--tw-content);width:2px}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.first\:rounded-l-md:first-child{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.first\:border-l:first-child{border-left-width:1px}.last\:rounded-r-md:last-child{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.focus-within\:relative:focus-within{position:relative}.focus-within\:z-20:focus-within{z-index:20}.hover\:border-cyber-accent\/30:hover{border-color:#0fa0ce4d}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-cyber-accent\/80:hover{background-color:#0fa0cecc}.hover\:bg-cyber-muted:hover{--tw-bg-opacity: 1;background-color:rgb(58 63 76 / var(--tw-bg-opacity, 1))}.hover\:bg-cyber-muted\/20:hover{background-color:#3a3f4c33}.hover\:bg-cyber-muted\/30:hover{background-color:#3a3f4c4d}.hover\:bg-cyber-muted\/50:hover{background-color:#3a3f4c80}.hover\:bg-destructive\/80:hover{background-color:hsl(var(--destructive) / .8)}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-gray-600:hover{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.hover\:bg-green-600:hover{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.hover\:bg-green-700:hover{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.hover\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\:bg-muted\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\:bg-neutral-800:hover{--tw-bg-opacity: 1;background-color:rgb(38 38 38 / var(--tw-bg-opacity, 1))}.hover\:bg-primary:hover{background-color:hsl(var(--primary))}.hover\:bg-primary\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-red-400:hover{--tw-bg-opacity: 1;background-color:rgb(248 113 113 / var(--tw-bg-opacity, 1))}.hover\:bg-red-400\/10:hover{background-color:#f871711a}.hover\:bg-red-500\/10:hover{background-color:#ef44441a}.hover\:bg-red-700:hover{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.hover\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:bg-sidebar-accent:hover{background-color:hsl(var(--sidebar-accent))}.hover\:bg-yellow-600:hover{--tw-bg-opacity: 1;background-color:rgb(202 138 4 / var(--tw-bg-opacity, 1))}.hover\:from-orange-600:hover{--tw-gradient-from: #ea580c var(--tw-gradient-from-position);--tw-gradient-to: rgb(234 88 12 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-purple-700:hover{--tw-gradient-from: #7e22ce var(--tw-gradient-from-position);--tw-gradient-to: rgb(126 34 206 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:to-blue-700:hover{--tw-gradient-to: #1d4ed8 var(--tw-gradient-to-position)}.hover\:to-orange-700:hover{--tw-gradient-to: #c2410c var(--tw-gradient-to-position)}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:text-blue-400:hover{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.hover\:text-cyber-accent:hover{--tw-text-opacity: 1;color:rgb(15 160 206 / var(--tw-text-opacity, 1))}.hover\:text-cyber-accent\/80:hover{color:#0fa0cecc}.hover\:text-cyber-light:hover{--tw-text-opacity: 1;color:rgb(241 241 241 / var(--tw-text-opacity, 1))}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:text-green-500:hover{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.hover\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\:text-orange-500:hover{--tw-text-opacity: 1;color:rgb(249 115 22 / var(--tw-text-opacity, 1))}.hover\:text-primary-foreground:hover{color:hsl(var(--primary-foreground))}.hover\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\:text-red-500:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-sidebar-accent-foreground:hover{color:hsl(var(--sidebar-accent-foreground))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.hover\:opacity-80:hover{opacity:.8}.hover\:shadow-\[0_0_0_1px_hsl\(var\(--sidebar-accent\)\)\]:hover{--tw-shadow: 0 0 0 1px hsl(var(--sidebar-accent));--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:after\:bg-sidebar-border:hover:after{content:var(--tw-content);background-color:hsl(var(--sidebar-border))}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:bg-primary:focus{background-color:hsl(var(--primary))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:text-orange-400:focus{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.focus\:text-primary-foreground:focus{color:hsl(var(--primary-foreground))}.focus\:text-red-400:focus{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-sidebar-ring:focus-visible{--tw-ring-color: hsl(var(--sidebar-ring))}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.active\:bg-sidebar-accent:active{background-color:hsl(var(--sidebar-accent))}.active\:text-sidebar-accent-foreground:active{color:hsl(var(--sidebar-accent-foreground))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.group\/menu-item:focus-within .group-focus-within\/menu-item\:opacity-100{opacity:1}.group:hover .group-hover\:text-cyber-accent{--tw-text-opacity: 1;color:rgb(15 160 206 / var(--tw-text-opacity, 1))}.group\/menu-item:hover .group-hover\/menu-item\:opacity-100,.group:hover .group-hover\:opacity-100{opacity:1}.group.destructive .group-\[\.destructive\]\:border-muted\/40{border-color:hsl(var(--muted) / .4)}.group.toaster .group-\[\.toaster\]\:border-border{border-color:hsl(var(--border))}.group.toast .group-\[\.toast\]\:bg-muted{background-color:hsl(var(--muted))}.group.toast .group-\[\.toast\]\:bg-primary{background-color:hsl(var(--primary))}.group.toaster .group-\[\.toaster\]\:bg-background{background-color:hsl(var(--background))}.group.destructive .group-\[\.destructive\]\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.group.toast .group-\[\.toast\]\:text-muted-foreground{color:hsl(var(--muted-foreground))}.group.toast .group-\[\.toast\]\:text-primary-foreground{color:hsl(var(--primary-foreground))}.group.toaster .group-\[\.toaster\]\:text-foreground{color:hsl(var(--foreground))}.group.toaster .group-\[\.toaster\]\:shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group.destructive .group-\[\.destructive\]\:hover\:border-destructive\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\[\.destructive\]\:hover\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:hover\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\[\.destructive\]\:hover\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity, 1))}.group.destructive .group-\[\.destructive\]\:focus\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:focus\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity, 1))}.group.destructive .group-\[\.destructive\]\:focus\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer\/menu-button:hover~.peer-hover\/menu-button\:text-sidebar-accent-foreground{color:hsl(var(--sidebar-accent-foreground))}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.has-\[\[data-variant\=inset\]\]\:bg-sidebar:has([data-variant=inset]){background-color:hsl(var(--sidebar-background))}.has-\[\:disabled\]\:opacity-50:has(:disabled){opacity:.5}.group\/menu-item:has([data-sidebar=menu-action]) .group-has-\[\[data-sidebar\=menu-action\]\]\/menu-item\:pr-8{padding-right:2rem}.aria-disabled\:pointer-events-none[aria-disabled=true]{pointer-events:none}.aria-disabled\:opacity-50[aria-disabled=true]{opacity:.5}.aria-selected\:bg-accent[aria-selected=true]{background-color:hsl(var(--accent))}.aria-selected\:bg-accent\/50[aria-selected=true]{background-color:hsl(var(--accent) / .5)}.aria-selected\:text-accent-foreground[aria-selected=true]{color:hsl(var(--accent-foreground))}.aria-selected\:text-muted-foreground[aria-selected=true]{color:hsl(var(--muted-foreground))}.aria-selected\:opacity-100[aria-selected=true]{opacity:1}.aria-selected\:opacity-30[aria-selected=true]{opacity:.3}.data-\[disabled\=true\]\:pointer-events-none[data-disabled=true],.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[panel-group-direction\=vertical\]\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\[panel-group-direction\=vertical\]\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-5[data-state=checked]{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked],.data-\[swipe\=cancel\]\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=end\]\:translate-x-\[var\(--radix-toast-swipe-end-x\)\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=move\]\:translate-x-\[var\(--radix-toast-swipe-move-x\)\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height)}to{height:0}}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up .2s ease-out}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height)}}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down .2s ease-out}.data-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[active\=true\]\:bg-sidebar-accent[data-active=true]{background-color:hsl(var(--sidebar-accent))}.data-\[active\]\:bg-accent\/50[data-active]{background-color:hsl(var(--accent) / .5)}.data-\[selected\=\'true\'\]\:bg-accent[data-selected=true]{background-color:hsl(var(--accent))}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-cyber-accent[data-state=checked]{--tw-bg-opacity: 1;background-color:rgb(15 160 206 / var(--tw-bg-opacity, 1))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=on\]\:bg-accent[data-state=on],.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:bg-accent\/50[data-state=open]{background-color:hsl(var(--accent) / .5)}.data-\[state\=open\]\:bg-secondary[data-state=open]{background-color:hsl(var(--secondary))}.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\[active\=true\]\:font-medium[data-active=true]{font-weight:500}.data-\[active\=true\]\:text-sidebar-accent-foreground[data-active=true]{color:hsl(var(--sidebar-accent-foreground))}.data-\[selected\=true\]\:text-accent-foreground[data-selected=true]{color:hsl(var(--accent-foreground))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=checked\]\:text-primary-foreground[data-state=checked]{color:hsl(var(--primary-foreground))}.data-\[state\=on\]\:text-accent-foreground[data-state=on],.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:hsl(var(--accent-foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\=true\]\:opacity-50[data-disabled=true],.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=open\]\:opacity-100[data-state=open]{opacity:1}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[swipe\=move\]\:transition-none[data-swipe=move]{transition-property:none}.data-\[state\=closed\]\:duration-300[data-state=closed]{transition-duration:.3s}.data-\[state\=open\]\:duration-500[data-state=open]{transition-duration:.5s}.data-\[motion\^\=from-\]\:animate-in[data-motion^=from-],.data-\[state\=open\]\:animate-in[data-state=open],.data-\[state\=visible\]\:animate-in[data-state=visible]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[motion\^\=to-\]\:animate-out[data-motion^=to-],.data-\[state\=closed\]\:animate-out[data-state=closed],.data-\[state\=hidden\]\:animate-out[data-state=hidden],.data-\[swipe\=end\]\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[motion\^\=from-\]\:fade-in[data-motion^=from-]{--tw-enter-opacity: 0}.data-\[motion\^\=to-\]\:fade-out[data-motion^=to-],.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=closed\]\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\[state\=hidden\]\:fade-out[data-state=hidden]{--tw-exit-opacity: 0}.data-\[state\=open\]\:fade-in-0[data-state=open],.data-\[state\=visible\]\:fade-in[data-state=visible]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-90[data-state=open]{--tw-enter-scale: .9}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[motion\=from-end\]\:slide-in-from-right-52[data-motion=from-end]{--tw-enter-translate-x: 13rem}.data-\[motion\=from-start\]\:slide-in-from-left-52[data-motion=from-start]{--tw-enter-translate-x: -13rem}.data-\[motion\=to-end\]\:slide-out-to-right-52[data-motion=to-end]{--tw-exit-translate-x: 13rem}.data-\[motion\=to-start\]\:slide-out-to-left-52[data-motion=to-start]{--tw-exit-translate-x: -13rem}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed],.data-\[state\=closed\]\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=closed\]\:duration-300[data-state=closed]{animation-duration:.3s}.data-\[state\=open\]\:duration-500[data-state=open]{animation-duration:.5s}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:0}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:.25rem}.data-\[panel-group-direction\=vertical\]\:after\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[panel-group-direction\=vertical\]\:after\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=open\]\:hover\:bg-sidebar-accent:hover[data-state=open]{background-color:hsl(var(--sidebar-accent))}.data-\[state\=open\]\:hover\:text-sidebar-accent-foreground:hover[data-state=open]{color:hsl(var(--sidebar-accent-foreground))}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:left-\[calc\(var\(--sidebar-width\)\*-1\)\]{left:calc(var(--sidebar-width) * -1)}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:right-\[calc\(var\(--sidebar-width\)\*-1\)\]{right:calc(var(--sidebar-width) * -1)}.group[data-side=left] .group-data-\[side\=left\]\:-right-4{right:-1rem}.group[data-side=right] .group-data-\[side\=right\]\:left-0{left:0}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:-mt-8{margin-top:-2rem}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:hidden{display:none}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:\!size-8{width:2rem!important;height:2rem!important}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:w-\[--sidebar-width-icon\]{width:var(--sidebar-width-icon)}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)_\+_theme\(spacing\.4\)\)\]{width:calc(var(--sidebar-width-icon) + 1rem)}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)_\+_theme\(spacing\.4\)_\+2px\)\]{width:calc(var(--sidebar-width-icon) + 1rem + 2px)}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:w-0{width:0px}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group[data-side=right] .group-data-\[side\=right\]\:rotate-180,.group[data-state=open] .group-data-\[state\=open\]\:rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:overflow-hidden{overflow:hidden}.group[data-variant=floating] .group-data-\[variant\=floating\]\:rounded-lg{border-radius:var(--radius)}.group[data-variant=floating] .group-data-\[variant\=floating\]\:border{border-width:1px}.group[data-side=left] .group-data-\[side\=left\]\:border-r{border-right-width:1px}.group[data-side=right] .group-data-\[side\=right\]\:border-l{border-left-width:1px}.group[data-variant=floating] .group-data-\[variant\=floating\]\:border-sidebar-border{border-color:hsl(var(--sidebar-border))}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:\!p-0{padding:0!important}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:\!p-2{padding:.5rem!important}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:opacity-0{opacity:0}.group[data-variant=floating] .group-data-\[variant\=floating\]\:shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:after\:left-full:after{content:var(--tw-content);left:100%}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:hover\:bg-sidebar:hover{background-color:hsl(var(--sidebar-background))}.peer\/menu-button[data-size=default]~.peer-data-\[size\=default\]\/menu-button\:top-1\.5{top:.375rem}.peer\/menu-button[data-size=lg]~.peer-data-\[size\=lg\]\/menu-button\:top-2\.5{top:.625rem}.peer\/menu-button[data-size=sm]~.peer-data-\[size\=sm\]\/menu-button\:top-1{top:.25rem}.peer[data-variant=inset]~.peer-data-\[variant\=inset\]\:min-h-\[calc\(100svh-theme\(spacing\.4\)\)\]{min-height:calc(100svh - 1rem)}.peer\/menu-button[data-active=true]~.peer-data-\[active\=true\]\/menu-button\:text-sidebar-accent-foreground{color:hsl(var(--sidebar-accent-foreground))}.dark\:border-destructive:is(.dark *){border-color:hsl(var(--destructive))}@media (min-width: 640px){.sm\:bottom-0{bottom:0}.sm\:right-0{right:0}.sm\:top-auto{top:auto}.sm\:mt-0{margin-top:0}.sm\:flex{display:flex}.sm\:max-w-\[425px\]{max-width:425px}.sm\:max-w-md{max-width:28rem}.sm\:max-w-sm{max-width:24rem}.sm\:flex-row{flex-direction:row}.sm\:flex-col{flex-direction:column}.sm\:justify-end{justify-content:flex-end}.sm\:justify-between{justify-content:space-between}.sm\:gap-2\.5{gap:.625rem}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}.data-\[state\=open\]\:sm\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media (min-width: 768px){.md\:absolute{position:absolute}.md\:block{display:block}.md\:flex{display:flex}.md\:hidden{display:none}.md\:w-\[var\(--radix-navigation-menu-viewport-width\)\]{width:var(--radix-navigation-menu-viewport-width)}.md\:w-auto{width:auto}.md\:max-w-\[420px\]{max-width:420px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:text-3xl{font-size:1.875rem;line-height:2.25rem}.md\:text-sm{font-size:.875rem;line-height:1.25rem}.md\:opacity-0{opacity:0}.after\:md\:hidden:after{content:var(--tw-content);display:none}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:m-2{margin:.5rem}.peer[data-state=collapsed][data-variant=inset]~.md\:peer-data-\[state\=collapsed\]\:peer-data-\[variant\=inset\]\:ml-2{margin-left:.5rem}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:ml-0{margin-left:0}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:rounded-xl{border-radius:.75rem}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}}@media (min-width: 1024px){.lg\:flex{display:flex}.lg\:hidden{display:none}}.\[\&\:has\(\[aria-selected\]\)\]\:bg-accent:has([aria-selected]){background-color:hsl(var(--accent))}.first\:\[\&\:has\(\[aria-selected\]\)\]\:rounded-l-md:has([aria-selected]):first-child{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.last\:\[\&\:has\(\[aria-selected\]\)\]\:rounded-r-md:has([aria-selected]):last-child{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\[\&\:has\(\[aria-selected\]\.day-outside\)\]\:bg-accent\/50:has([aria-selected].day-outside){background-color:hsl(var(--accent) / .5)}.\[\&\:has\(\[aria-selected\]\.day-range-end\)\]\:rounded-r-md:has([aria-selected].day-range-end){border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\&\>button\]\:hidden>button{display:none}.\[\&\>span\:last-child\]\:truncate>span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\>svg\+div\]\:translate-y-\[-3px\]>svg+div{--tw-translate-y: -3px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\>svg\]\:absolute>svg{position:absolute}.\[\&\>svg\]\:left-4>svg{left:1rem}.\[\&\>svg\]\:top-4>svg{top:1rem}.\[\&\>svg\]\:size-3\.5>svg{width:.875rem;height:.875rem}.\[\&\>svg\]\:size-4>svg{width:1rem;height:1rem}.\[\&\>svg\]\:h-2\.5>svg{height:.625rem}.\[\&\>svg\]\:h-3>svg{height:.75rem}.\[\&\>svg\]\:w-2\.5>svg{width:.625rem}.\[\&\>svg\]\:w-3>svg{width:.75rem}.\[\&\>svg\]\:shrink-0>svg{flex-shrink:0}.\[\&\>svg\]\:text-destructive>svg{color:hsl(var(--destructive))}.\[\&\>svg\]\:text-foreground>svg{color:hsl(var(--foreground))}.\[\&\>svg\]\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\[\&\>svg\]\:text-sidebar-accent-foreground>svg{color:hsl(var(--sidebar-accent-foreground))}.\[\&\>svg\~\*\]\:pl-7>svg~*{padding-left:1.75rem}.\[\&\>tr\]\:last\:border-b-0:last-child>tr{border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-none .recharts-layer{outline:2px solid transparent;outline-offset:2px}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector,.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-sector\]\:outline-none .recharts-sector,.\[\&_\.recharts-surface\]\:outline-none .recharts-surface{outline:2px solid transparent;outline-offset:2px}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{font-weight:500}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:3rem}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:1.25rem}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:1.25rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:size-4 svg{width:1rem;height:1rem}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-width:0px}.\[\&_tr\]\:border-b tr{border-bottom-width:1px}[data-side=left][data-collapsible=offcanvas] .\[\[data-side\=left\]\[data-collapsible\=offcanvas\]_\&\]\:-right-2{right:-.5rem}[data-side=left][data-state=collapsed] .\[\[data-side\=left\]\[data-state\=collapsed\]_\&\]\:cursor-e-resize{cursor:e-resize}[data-side=left] .\[\[data-side\=left\]_\&\]\:cursor-w-resize{cursor:w-resize}[data-side=right][data-collapsible=offcanvas] .\[\[data-side\=right\]\[data-collapsible\=offcanvas\]_\&\]\:-left-2{left:-.5rem}[data-side=right][data-state=collapsed] .\[\[data-side\=right\]\[data-state\=collapsed\]_\&\]\:cursor-w-resize{cursor:w-resize}[data-side=right] .\[\[data-side\=right\]_\&\]\:cursor-e-resize{cursor:e-resize} diff --git a/dist/assets/index-COonna6N.js b/dist/assets/index-COonna6N.js new file mode 100644 index 0000000..063d7d8 --- /dev/null +++ b/dist/assets/index-COonna6N.js @@ -0,0 +1 @@ +import{aR as je,ah as mr,aS as Rr,aO as Z}from"./index-Cr5N_0pd.js";var Rt={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh */(function(e,t){var r=je,a=r.Buffer;function o(h,u){for(var f in h)u[f]=h[f]}a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow?e.exports=r:(o(r,t),t.Buffer=c);function c(h,u,f){return a(h,u,f)}c.prototype=Object.create(a.prototype),o(a,c),c.from=function(h,u,f){if(typeof h=="number")throw new TypeError("Argument must not be a number");return a(h,u,f)},c.alloc=function(h,u,f){if(typeof h!="number")throw new TypeError("Argument must be a number");var d=a(h);return u!==void 0?typeof f=="string"?d.fill(u,f):d.fill(u):d.fill(0),d},c.allocUnsafe=function(h){if(typeof h!="number")throw new TypeError("Argument must be a number");return a(h)},c.allocUnsafeSlow=function(h){if(typeof h!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(h)}})(Rt,Rt.exports);var Q=Rt.exports,Tt={exports:{}};typeof Object.create=="function"?Tt.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:Tt.exports=function(t,r){if(r){t.super_=r;var a=function(){};a.prototype=r.prototype,t.prototype=new a,t.prototype.constructor=t}};var V=Tt.exports,Pt={exports:{}},Tr=mr.EventEmitter,ze,$t;function on(){if($t)return ze;$t=1;function e(A,x){var y=Object.keys(A);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(A);x&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(A,E).enumerable})),y.push.apply(y,v)}return y}function t(A){for(var x=1;x0?this.tail.next=v:this.head=v,this.tail=v,++this.length}},{key:"unshift",value:function(y){var v={data:y,next:this.head};this.length===0&&(this.tail=v),this.head=v,++this.length}},{key:"shift",value:function(){if(this.length!==0){var y=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,y}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(y){if(this.length===0)return"";for(var v=this.head,E=""+v.data;v=v.next;)E+=y+v.data;return E}},{key:"concat",value:function(y){if(this.length===0)return d.alloc(0);for(var v=d.allocUnsafe(y>>>0),E=this.head,b=0;E;)N(E.data,v,b),b+=E.data.length,E=E.next;return v}},{key:"consume",value:function(y,v){var E;return yS.length?S.length:y;if(P===S.length?b+=S:b+=S.slice(0,y),y-=P,y===0){P===S.length?(++E,v.next?this.head=v.next:this.head=this.tail=null):(this.head=v,v.data=S.slice(P));break}++E}return this.length-=E,b}},{key:"_getBuffer",value:function(y){var v=d.allocUnsafe(y),E=this.head,b=1;for(E.data.copy(v),y-=E.data.length;E=E.next;){var S=E.data,P=y>S.length?S.length:y;if(S.copy(v,v.length-y,0,P),y-=P,y===0){P===S.length?(++b,E.next?this.head=E.next:this.head=this.tail=null):(this.head=E,E.data=S.slice(P));break}++b}return this.length-=b,v}},{key:R,value:function(y,v){return w(this,t(t({},v),{},{depth:0,customInspect:!1}))}}]),A}(),ze}function fn(e,t){var r=this,a=this._readableState&&this._readableState.destroyed,o=this._writableState&&this._writableState.destroyed;return a||o?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(Bt,this,e)):process.nextTick(Bt,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(c){!t&&c?r._writableState?r._writableState.errorEmitted?process.nextTick(De,r):(r._writableState.errorEmitted=!0,process.nextTick(jt,r,c)):process.nextTick(jt,r,c):t?(process.nextTick(De,r),t(c)):process.nextTick(De,r)}),this)}function jt(e,t){Bt(e,t),De(e)}function De(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function sn(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Bt(e,t){e.emit("error",t)}function ln(e,t){var r=e._readableState,a=e._writableState;r&&r.autoDestroy||a&&a.autoDestroy?e.destroy(t):e.emit("error",t)}var Pr={destroy:fn,undestroy:sn,errorOrDestroy:ln},re={};function un(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var Br={};function k(e,t,r){r||(r=Error);function a(c,h,u){return typeof t=="string"?t:t(c,h,u)}var o=function(c){un(h,c);function h(u,f,d){return c.call(this,a(u,f,d))||this}return h}(r);o.prototype.name=r.name,o.prototype.code=e,Br[e]=o}function Ut(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map(function(a){return String(a)}),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:r===2?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}else return"of ".concat(t," ").concat(String(e))}function cn(e,t,r){return e.substr(0,t.length)===t}function hn(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function dn(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?!1:e.indexOf(t,r)!==-1}k("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError);k("ERR_INVALID_ARG_TYPE",function(e,t,r){var a;typeof t=="string"&&cn(t,"not ")?(a="must not be",t=t.replace(/^not /,"")):a="must be";var o;if(hn(e," argument"))o="The ".concat(e," ").concat(a," ").concat(Ut(t,"type"));else{var c=dn(e,".")?"property":"argument";o='The "'.concat(e,'" ').concat(c," ").concat(a," ").concat(Ut(t,"type"))}return o+=". Received type ".concat(typeof r),o},TypeError);k("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");k("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"});k("ERR_STREAM_PREMATURE_CLOSE","Premature close");k("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"});k("ERR_MULTIPLE_CALLBACK","Callback called multiple times");k("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");k("ERR_STREAM_WRITE_AFTER_END","write after end");k("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);k("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError);k("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");re.codes=Br;var pn=re.codes.ERR_INVALID_OPT_VALUE;function yn(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function vn(e,t,r,a){var o=yn(t,a,r);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0){var c=a?r:"highWaterMark";throw new pn(c,o)}return Math.floor(o)}return e.objectMode?16:16*1024}var Or={getHighWaterMark:vn},bn=_n;function _n(e,t){if(Je("noDeprecation"))return e;var r=!1;function a(){if(!r){if(Je("throwDeprecation"))throw new Error(t);Je("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}return a}function Je(e){try{if(!Z.localStorage)return!1}catch{return!1}var t=Z.localStorage[e];return t==null?!1:String(t).toLowerCase()==="true"}var Xe,qt;function Cr(){if(qt)return Xe;qt=1,Xe=C;function e(l){var s=this;this.next=null,this.entry=null,this.finish=function(){fe(s,l)}}var t;C.WritableState=O;var r={deprecate:bn},a=Tr,o=je.Buffer,c=(typeof Z<"u"?Z:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function h(l){return o.from(l)}function u(l){return o.isBuffer(l)||l instanceof c}var f=Pr,d=Or,g=d.getHighWaterMark,w=re.codes,R=w.ERR_INVALID_ARG_TYPE,N=w.ERR_METHOD_NOT_IMPLEMENTED,A=w.ERR_MULTIPLE_CALLBACK,x=w.ERR_STREAM_CANNOT_PIPE,y=w.ERR_STREAM_DESTROYED,v=w.ERR_STREAM_NULL_VALUES,E=w.ERR_STREAM_WRITE_AFTER_END,b=w.ERR_UNKNOWN_ENCODING,S=f.errorOrDestroy;V(C,a);function P(){}function O(l,s,_){t=t||pe(),l=l||{},typeof _!="boolean"&&(_=s instanceof t),this.objectMode=!!l.objectMode,_&&(this.objectMode=this.objectMode||!!l.writableObjectMode),this.highWaterMark=g(this,l,"writableHighWaterMark",_),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var T=l.decodeStrings===!1;this.decodeStrings=!T,this.defaultEncoding=l.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(D){be(s,D)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=l.emitClose!==!1,this.autoDestroy=!!l.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}O.prototype.getBuffer=function(){for(var s=this.bufferedRequest,_=[];s;)_.push(s),s=s.next;return _},function(){try{Object.defineProperty(O.prototype,"buffer",{get:r.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var L;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(L=Function.prototype[Symbol.hasInstance],Object.defineProperty(C,Symbol.hasInstance,{value:function(s){return L.call(this,s)?!0:this!==C?!1:s&&s._writableState instanceof O}})):L=function(s){return s instanceof this};function C(l){t=t||pe();var s=this instanceof t;if(!s&&!L.call(C,this))return new C(l);this._writableState=new O(l,this,s),this.writable=!0,l&&(typeof l.write=="function"&&(this._write=l.write),typeof l.writev=="function"&&(this._writev=l.writev),typeof l.destroy=="function"&&(this._destroy=l.destroy),typeof l.final=="function"&&(this._final=l.final)),a.call(this)}C.prototype.pipe=function(){S(this,new x)};function B(l,s){var _=new E;S(l,_),process.nextTick(s,_)}function W(l,s,_,T){var D;return _===null?D=new v:typeof _!="string"&&!s.objectMode&&(D=new R("chunk",["string","Buffer"],_)),D?(S(l,D),process.nextTick(T,D),!1):!0}C.prototype.write=function(l,s,_){var T=this._writableState,D=!1,n=!T.objectMode&&u(l);return n&&!o.isBuffer(l)&&(l=h(l)),typeof s=="function"&&(_=s,s=null),n?s="buffer":s||(s=T.defaultEncoding),typeof _!="function"&&(_=P),T.ending?B(this,_):(n||W(this,T,l,_))&&(T.pendingcb++,D=ne(this,T,n,l,s,_)),D},C.prototype.cork=function(){this._writableState.corked++},C.prototype.uncork=function(){var l=this._writableState;l.corked&&(l.corked--,!l.writing&&!l.corked&&!l.bufferProcessing&&l.bufferedRequest&&J(this,l))},C.prototype.setDefaultEncoding=function(s){if(typeof s=="string"&&(s=s.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((s+"").toLowerCase())>-1))throw new b(s);return this._writableState.defaultEncoding=s,this},Object.defineProperty(C.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function ee(l,s,_){return!l.objectMode&&l.decodeStrings!==!1&&typeof s=="string"&&(s=o.from(s,_)),s}Object.defineProperty(C.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function ne(l,s,_,T,D,n){if(!_){var i=ee(s,T,D);T!==i&&(_=!0,D="buffer",T=i)}var p=s.objectMode?1:T.length;s.length+=p;var m=s.length>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function En(e,t,r){var a=t.length-1;if(a=0?(o>0&&(e.lastNeed=o-1),o):--a=0?(o>0&&(e.lastNeed=o-2),o):--a=0?(o>0&&(o===2?o=0:e.lastNeed=o-3),o):0))}function Sn(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"�"}}function xn(e){var t=this.lastTotal-this.lastNeed,r=Sn(this,e);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function An(e,t){var r=En(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var a=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,a),e.toString("utf8",t,a)}function mn(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function Rn(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var a=r.charCodeAt(r.length-1);if(a>=55296&&a<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function Tn(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function Pn(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function Bn(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function On(e){return e.toString(this.encoding)}function Cn(e){return e&&e.length?this.write(e):""}var Ht=re.codes.ERR_STREAM_PREMATURE_CLOSE;function Mn(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,a=new Array(r),o=0;o0)if(typeof i!="string"&&!I.objectMode&&Object.getPrototypeOf(i)!==a.prototype&&(i=c(i)),m)I.endEmitted?P(n,new v):ee(n,I,i,!0);else if(I.ended)P(n,new x);else{if(I.destroyed)return!1;I.reading=!1,I.decoder&&!p?(i=I.decoder.write(i),I.objectMode||i.length!==0?ee(n,I,i,!1):J(n,I)):ee(n,I,i,!1)}else m||(I.reading=!1,J(n,I))}return!I.ended&&(I.length=j?n=j:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function G(n,i){return n<=0||i.length===0&&i.ended?0:i.objectMode?1:n!==n?i.flowing&&i.length?i.buffer.head.data.length:i.length:(n>i.highWaterMark&&(i.highWaterMark=H(n)),n<=i.length?n:i.ended?i.length:(i.needReadable=!0,0))}B.prototype.read=function(n){f("read",n),n=parseInt(n,10);var i=this._readableState,p=n;if(n!==0&&(i.emittedReadable=!1),n===0&&i.needReadable&&((i.highWaterMark!==0?i.length>=i.highWaterMark:i.length>0)||i.ended))return f("read: emitReadable",i.length,i.ended),i.length===0&&i.ended?_(this):z(this),null;if(n=G(n,i),n===0&&i.ended)return i.length===0&&_(this),null;var m=i.needReadable;f("need readable",m),(i.length===0||i.length-n0?$=s(n,i):$=null,$===null?(i.needReadable=i.length<=i.highWaterMark,n=0):(i.length-=n,i.awaitDrain=0),i.length===0&&(i.ended||(i.needReadable=!0),p!==n&&i.ended&&_(this)),$!==null&&this.emit("data",$),$};function be(n,i){if(f("onEofChunk"),!i.ended){if(i.decoder){var p=i.decoder.end();p&&p.length&&(i.buffer.push(p),i.length+=i.objectMode?1:p.length)}i.ended=!0,i.sync?z(n):(i.needReadable=!1,i.emittedReadable||(i.emittedReadable=!0,ie(n)))}}function z(n){var i=n._readableState;f("emitReadable",i.needReadable,i.emittedReadable),i.needReadable=!1,i.emittedReadable||(f("emitReadable",i.flowing),i.emittedReadable=!0,process.nextTick(ie,n))}function ie(n){var i=n._readableState;f("emitReadable_",i.destroyed,i.length,i.ended),!i.destroyed&&(i.length||i.ended)&&(n.emit("readable"),i.emittedReadable=!1),i.needReadable=!i.flowing&&!i.ended&&i.length<=i.highWaterMark,l(n)}function J(n,i){i.readingMore||(i.readingMore=!0,process.nextTick(ae,n,i))}function ae(n,i){for(;!i.reading&&!i.ended&&(i.length1&&D(m.pipes,n)!==-1)&&!Ft&&(f("false write response, pause",m.awaitDrain),m.awaitDrain++),p.pause())}function Ve(le){f("onerror",le),we(),n.removeListener("error",Ve),t(n,"error")===0&&P(n,le)}L(n,"error",Ve);function Ye(){n.removeListener("finish",Ke),we()}n.once("close",Ye);function Ke(){f("onfinish"),n.removeListener("close",Ye),we()}n.once("finish",Ke);function we(){f("unpipe"),p.unpipe(n)}return n.emit("pipe",p),m.flowing||(f("pipe resume"),p.resume()),n};function _e(n){return function(){var p=n._readableState;f("pipeOnDrain",p.awaitDrain),p.awaitDrain&&p.awaitDrain--,p.awaitDrain===0&&t(n,"data")&&(p.flowing=!0,l(n))}}B.prototype.unpipe=function(n){var i=this._readableState,p={hasUnpiped:!1};if(i.pipesCount===0)return this;if(i.pipesCount===1)return n&&n!==i.pipes?this:(n||(n=i.pipes),i.pipes=null,i.pipesCount=0,i.flowing=!1,n&&n.emit("unpipe",this,p),this);if(!n){var m=i.pipes,$=i.pipesCount;i.pipes=null,i.pipesCount=0,i.flowing=!1;for(var I=0;I<$;I++)m[I].emit("unpipe",this,{hasUnpiped:!1});return this}var F=D(i.pipes,n);return F===-1?this:(i.pipes.splice(F,1),i.pipesCount-=1,i.pipesCount===1&&(i.pipes=i.pipes[0]),n.emit("unpipe",this,p),this)},B.prototype.on=function(n,i){var p=r.prototype.on.call(this,n,i),m=this._readableState;return n==="data"?(m.readableListening=this.listenerCount("readable")>0,m.flowing!==!1&&this.resume()):n==="readable"&&!m.endEmitted&&!m.readableListening&&(m.readableListening=m.needReadable=!0,m.flowing=!1,m.emittedReadable=!1,f("on readable",m.length,m.reading),m.length?z(this):m.reading||process.nextTick(Y,this)),p},B.prototype.addListener=B.prototype.on,B.prototype.removeListener=function(n,i){var p=r.prototype.removeListener.call(this,n,i);return n==="readable"&&process.nextTick(oe,this),p},B.prototype.removeAllListeners=function(n){var i=r.prototype.removeAllListeners.apply(this,arguments);return(n==="readable"||n===void 0)&&process.nextTick(oe,this),i};function oe(n){var i=n._readableState;i.readableListening=n.listenerCount("readable")>0,i.resumeScheduled&&!i.paused?i.flowing=!0:n.listenerCount("data")>0&&n.resume()}function Y(n){f("readable nexttick read 0"),n.read(0)}B.prototype.resume=function(){var n=this._readableState;return n.flowing||(f("resume"),n.flowing=!n.readableListening,ge(this,n)),n.paused=!1,this};function ge(n,i){i.resumeScheduled||(i.resumeScheduled=!0,process.nextTick(fe,n,i))}function fe(n,i){f("resume",i.reading),i.reading||n.read(0),i.resumeScheduled=!1,n.emit("resume"),l(n),i.flowing&&!i.reading&&n.read(0)}B.prototype.pause=function(){return f("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(f("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function l(n){var i=n._readableState;for(f("flow",i.flowing);i.flowing&&n.read()!==null;);}B.prototype.wrap=function(n){var i=this,p=this._readableState,m=!1;n.on("end",function(){if(f("wrapped end"),p.decoder&&!p.ended){var F=p.decoder.end();F&&F.length&&i.push(F)}i.push(null)}),n.on("data",function(F){if(f("wrapped data"),p.decoder&&(F=p.decoder.write(F)),!(p.objectMode&&F==null)&&!(!p.objectMode&&(!F||!F.length))){var se=i.push(F);se||(m=!0,n.pause())}});for(var $ in n)this[$]===void 0&&typeof n[$]=="function"&&(this[$]=function(se){return function(){return n[se].apply(n,arguments)}}($));for(var I=0;I=i.length?(i.decoder?p=i.buffer.join(""):i.buffer.length===1?p=i.buffer.first():p=i.buffer.concat(i.length),i.buffer.clear()):p=i.buffer.consume(n,i.decoder),p}function _(n){var i=n._readableState;f("endReadable",i.endEmitted),i.endEmitted||(i.ended=!0,process.nextTick(T,i,n))}function T(n,i){if(f("endReadableNT",n.endEmitted,n.length),!n.endEmitted&&n.length===0&&(n.endEmitted=!0,i.readable=!1,i.emit("end"),n.autoDestroy)){var p=i._writableState;(!p||p.autoDestroy&&p.finished)&&i.destroy()}}typeof Symbol=="function"&&(B.from=function(n,i){return S===void 0&&(S=Fn()),S(B,n,i)});function D(n,i){for(var p=0,m=n.length;p0;return Kn(h,f,d,function(g){o||(o=g),g&&c.forEach(Jt),!f&&(c.forEach(Jt),a(o))})});return t.reduce(zn)}var Qn=Xn;(function(e,t){t=e.exports=Ir(),t.Stream=t,t.Readable=t,t.Writable=Cr(),t.Duplex=pe(),t.Transform=Dr,t.PassThrough=Wn,t.finished=Mt,t.pipeline=Qn})(Pt,Pt.exports);var Bo=Pt.exports,Lr={exports:{}},Zn={}.toString,ei=Array.isArray||function(e){return Zn.call(e)=="[object Array]"},Ae=TypeError,$r=Object,ti=Error,ri=EvalError,ni=RangeError,ii=ReferenceError,jr=SyntaxError,ai=URIError,oi=Math.abs,fi=Math.floor,si=Math.max,li=Math.min,ui=Math.pow,ci=Math.round,hi=Number.isNaN||function(t){return t!==t},di=hi,pi=function(t){return di(t)||t===0?t:t<0?-1:1},yi=Object.getOwnPropertyDescriptor,Ne=yi;if(Ne)try{Ne([],"length")}catch{Ne=null}var me=Ne,Fe=Object.defineProperty||!1;if(Fe)try{Fe({},"a",{value:1})}catch{Fe=!1}var ke=Fe,it,Xt;function Ur(){return Xt||(Xt=1,it=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var t={},r=Symbol("test"),a=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(a)!=="[object Symbol]")return!1;var o=42;t[r]=o;for(var c in t)return!1;if(typeof Object.keys=="function"&&Object.keys(t).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(t).length!==0)return!1;var h=Object.getOwnPropertySymbols(t);if(h.length!==1||h[0]!==r||!Object.prototype.propertyIsEnumerable.call(t,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var u=Object.getOwnPropertyDescriptor(t,r);if(u.value!==o||u.enumerable!==!0)return!1}return!0}),it}var at,Qt;function vi(){if(Qt)return at;Qt=1;var e=typeof Symbol<"u"&&Symbol,t=Ur();return at=function(){return typeof e!="function"||typeof Symbol!="function"||typeof e("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:t()},at}var ot,Zt;function qr(){return Zt||(Zt=1,ot=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),ot}var ft,er;function kr(){if(er)return ft;er=1;var e=$r;return ft=e.getPrototypeOf||null,ft}var bi="Function.prototype.bind called on incompatible ",_i=Object.prototype.toString,gi=Math.max,wi="[object Function]",tr=function(t,r){for(var a=[],o=0;o"u"||!q?M:q(Uint8Array),te={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?M:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?M:ArrayBuffer,"%ArrayIteratorPrototype%":ce&&q?q([][Symbol.iterator]()):M,"%AsyncFromSyncIteratorPrototype%":M,"%AsyncFunction%":he,"%AsyncGenerator%":he,"%AsyncGeneratorFunction%":he,"%AsyncIteratorPrototype%":he,"%Atomics%":typeof Atomics>"u"?M:Atomics,"%BigInt%":typeof BigInt>"u"?M:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?M:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?M:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?M:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Li,"%eval%":eval,"%EvalError%":$i,"%Float16Array%":typeof Float16Array>"u"?M:Float16Array,"%Float32Array%":typeof Float32Array>"u"?M:Float32Array,"%Float64Array%":typeof Float64Array>"u"?M:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?M:FinalizationRegistry,"%Function%":Gr,"%GeneratorFunction%":he,"%Int8Array%":typeof Int8Array>"u"?M:Int8Array,"%Int16Array%":typeof Int16Array>"u"?M:Int16Array,"%Int32Array%":typeof Int32Array>"u"?M:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":ce&&q?q(q([][Symbol.iterator]())):M,"%JSON%":typeof JSON=="object"?JSON:M,"%Map%":typeof Map>"u"?M:Map,"%MapIteratorPrototype%":typeof Map>"u"||!ce||!q?M:q(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Fi,"%Object.getOwnPropertyDescriptor%":Se,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?M:Promise,"%Proxy%":typeof Proxy>"u"?M:Proxy,"%RangeError%":ji,"%ReferenceError%":Ui,"%Reflect%":typeof Reflect>"u"?M:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?M:Set,"%SetIteratorPrototype%":typeof Set>"u"||!ce||!q?M:q(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?M:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":ce&&q?q(""[Symbol.iterator]()):M,"%Symbol%":ce?Symbol:M,"%SyntaxError%":ye,"%ThrowTypeError%":Ji,"%TypedArray%":Zi,"%TypeError%":de,"%Uint8Array%":typeof Uint8Array>"u"?M:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?M:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?M:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?M:Uint32Array,"%URIError%":qi,"%WeakMap%":typeof WeakMap>"u"?M:WeakMap,"%WeakRef%":typeof WeakRef>"u"?M:WeakRef,"%WeakSet%":typeof WeakSet>"u"?M:WeakSet,"%Function.prototype.call%":Te,"%Function.prototype.apply%":Vr,"%Object.defineProperty%":zi,"%Object.getPrototypeOf%":Xi,"%Math.abs%":ki,"%Math.floor%":Wi,"%Math.max%":Hi,"%Math.min%":Gi,"%Math.pow%":Vi,"%Math.round%":Yi,"%Math.sign%":Ki,"%Reflect.getPrototypeOf%":Qi};if(q)try{null.error}catch(e){var ea=q(q(e));te["%Error.prototype%"]=ea}var ta=function e(t){var r;if(t==="%AsyncFunction%")r=ht("async function () {}");else if(t==="%GeneratorFunction%")r=ht("function* () {}");else if(t==="%AsyncGeneratorFunction%")r=ht("async function* () {}");else if(t==="%AsyncGenerator%"){var a=e("%AsyncGeneratorFunction%");a&&(r=a.prototype)}else if(t==="%AsyncIteratorPrototype%"){var o=e("%AsyncGenerator%");o&&q&&(r=q(o.prototype))}return te[t]=r,r},or={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},Pe=Re,Le=Ni(),ra=Pe.call(Te,Array.prototype.concat),na=Pe.call(Vr,Array.prototype.splice),fr=Pe.call(Te,String.prototype.replace),$e=Pe.call(Te,String.prototype.slice),ia=Pe.call(Te,RegExp.prototype.exec),aa=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,oa=/\\(\\)?/g,fa=function(t){var r=$e(t,0,1),a=$e(t,-1);if(r==="%"&&a!=="%")throw new ye("invalid intrinsic syntax, expected closing `%`");if(a==="%"&&r!=="%")throw new ye("invalid intrinsic syntax, expected opening `%`");var o=[];return fr(t,aa,function(c,h,u,f){o[o.length]=u?fr(f,oa,"$1"):h||c}),o},sa=function(t,r){var a=t,o;if(Le(or,a)&&(o=or[a],a="%"+o[0]+"%"),Le(te,a)){var c=te[a];if(c===he&&(c=ta(a)),typeof c>"u"&&!r)throw new de("intrinsic "+t+" exists, but is not available. Please file an issue!");return{alias:o,name:a,value:c}}throw new ye("intrinsic "+t+" does not exist!")},Yr=function(t,r){if(typeof t!="string"||t.length===0)throw new de("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new de('"allowMissing" argument must be a boolean');if(ia(/^%?[^%]*%?$/,t)===null)throw new ye("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var a=fa(t),o=a.length>0?a[0]:"",c=sa("%"+o+"%",r),h=c.name,u=c.value,f=!1,d=c.alias;d&&(o=d[0],na(a,ra([0,1],d)));for(var g=1,w=!0;g=a.length){var x=Se(u,R);w=!!x,w&&"get"in x&&!("originalValue"in x.get)?u=x.get:u=u[R]}else w=Le(u,R),u=u[R];w&&!f&&(te[h]=u)}}return u},Kr=Yr,zr=Nt,la=zr([Kr("%String.prototype.indexOf%")]),Jr=function(t,r){var a=Kr(t,!!r);return typeof a=="function"&&la(t,".prototype.")>-1?zr([a]):a},pt,sr;function ua(){if(sr)return pt;sr=1;var e=Function.prototype.toString,t=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,a;if(typeof t=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw a}}),a={},t(function(){throw 42},null,r)}catch(E){E!==a&&(t=null)}else t=null;var o=/^\s*class\b/,c=function(b){try{var S=e.call(b);return o.test(S)}catch{return!1}},h=function(b){try{return c(b)?!1:(e.call(b),!0)}catch{return!1}},u=Object.prototype.toString,f="[object Object]",d="[object Function]",g="[object GeneratorFunction]",w="[object HTMLAllCollection]",R="[object HTML document.all class]",N="[object HTMLCollection]",A=typeof Symbol=="function"&&!!Symbol.toStringTag,x=!(0 in[,]),y=function(){return!1};if(typeof document=="object"){var v=document.all;u.call(v)===u.call(document.all)&&(y=function(b){if((x||!b)&&(typeof b>"u"||typeof b=="object"))try{var S=u.call(b);return(S===w||S===R||S===N||S===f)&&b("")==null}catch{}return!1})}return pt=t?function(b){if(y(b))return!0;if(!b||typeof b!="function"&&typeof b!="object")return!1;try{t(b,null,r)}catch(S){if(S!==a)return!1}return!c(b)&&h(b)}:function(b){if(y(b))return!0;if(!b||typeof b!="function"&&typeof b!="object")return!1;if(A)return h(b);if(c(b))return!1;var S=u.call(b);return S!==d&&S!==g&&!/^\[object HTML/.test(S)?!1:h(b)},pt}var yt,lr;function ca(){if(lr)return yt;lr=1;var e=ua(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty,a=function(f,d,g){for(var w=0,R=f.length;w=3&&(w=g),h(f)?a(f,d,w):typeof f=="string"?o(f,d,w):c(f,d,w)},yt}var vt,ur;function ha(){return ur||(ur=1,vt=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),vt}var bt,cr;function da(){if(cr)return bt;cr=1;var e=ha(),t=typeof globalThis>"u"?Z:globalThis;return bt=function(){for(var a=[],o=0;o3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new r("`loose`, if provided, must be a boolean");var f=arguments.length>3?arguments[3]:null,d=arguments.length>4?arguments[4]:null,g=arguments.length>5?arguments[5]:null,w=arguments.length>6?arguments[6]:!1,R=!!a&&a(c,h);if(e)e(c,h,{configurable:g===null&&R?R.configurable:!g,enumerable:f===null&&R?R.enumerable:!f,value:u,writable:d===null&&R?R.writable:!d});else if(w||!f&&!d&&!g)c[h]=u;else throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},gt}var wt,dr;function ya(){if(dr)return wt;dr=1;var e=ke,t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return e([],"length",{value:1}).length!==1}catch{return!0}},wt=t,wt}var Et,pr;function va(){if(pr)return Et;pr=1;var e=Yr,t=pa(),r=ya()(),a=me,o=Ae,c=e("%Math.floor%");return Et=function(u,f){if(typeof u!="function")throw new o("`fn` is not a function");if(typeof f!="number"||f<0||f>4294967295||c(f)!==f)throw new o("`length` must be a positive 32-bit integer");var d=arguments.length>2&&!!arguments[2],g=!0,w=!0;if("length"in u&&a){var R=a(u,"length");R&&!R.configurable&&(g=!1),R&&!R.writable&&(w=!1)}return(g||w||!d)&&(r?t(u,"length",f,!0,!0):t(u,"length",f)),u},Et}var St,yr;function ba(){if(yr)return St;yr=1;var e=Re,t=Dt(),r=Wr;return St=function(){return r(e,t,arguments)},St}var vr;function _a(){return vr||(vr=1,function(e){var t=va(),r=ke,a=Nt,o=ba();e.exports=function(h){var u=a(arguments),f=h.length-(arguments.length-1);return t(u,1+(f>0?f:0),!0)},r?r(e.exports,"apply",{value:o}):e.exports.apply=o}(_t)),_t.exports}var xt,br;function ga(){if(br)return xt;br=1;var e=Ur();return xt=function(){return e()&&!!Symbol.toStringTag},xt}var At,_r;function wa(){if(_r)return At;_r=1;var e=ca(),t=da(),r=_a(),a=Jr,o=me,c=Hr(),h=a("Object.prototype.toString"),u=ga()(),f=typeof globalThis>"u"?Z:globalThis,d=t(),g=a("String.prototype.slice"),w=a("Array.prototype.indexOf",!0)||function(y,v){for(var E=0;E-1?v:v!=="Object"?!1:A(y)}return o?N(y):null},At}var mt,gr;function Ea(){if(gr)return mt;gr=1;var e=wa();return mt=function(r){return!!e(r)},mt}var Sa=Ae,xa=Jr,Aa=xa("TypedArray.prototype.buffer",!0),ma=Ea(),Ra=Aa||function(t){if(!ma(t))throw new Sa("Not a Typed Array");return t.buffer},K=Q.Buffer,Ta=ei,Pa=Ra,Ba=ArrayBuffer.isView||function(t){try{return Pa(t),!0}catch{return!1}},Oa=typeof Uint8Array<"u",Xr=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",Ca=Xr&&(K.prototype instanceof Uint8Array||K.TYPED_ARRAY_SUPPORT),Ma=function(t,r){if(t instanceof K)return t;if(typeof t=="string")return K.from(t,r);if(Xr&&Ba(t)){if(t.byteLength===0)return K.alloc(0);if(Ca){var a=K.from(t.buffer,t.byteOffset,t.byteLength);if(a.byteLength===t.byteLength)return a}var o=t instanceof Uint8Array?t:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),c=K.from(o);if(c.length===t.byteLength)return c}if(Oa&&t instanceof Uint8Array)return K.from(t);var h=Ta(t);if(h)for(var u=0;u255||~~f!==f)throw new RangeError("Array items must be numbers in the range 0-255.")}if(h||K.isBuffer(t)&&t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t))return K.from(t);throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.')},Ia=Q.Buffer,Da=Ma;function We(e,t){this._block=Ia.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}We.prototype.update=function(e,t){e=Da(e,t||"utf8");for(var r=this._block,a=this._blockSize,o=e.length,c=this._len,h=0;h=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=this._len*8;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var a=(r&4294967295)>>>0,o=(r-a)/4294967296;this._block.writeUInt32BE(o,this._blockSize-8),this._block.writeUInt32BE(a,this._blockSize-4)}this._update(this._block);var c=this._hash();return e?c.toString(e):c};We.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var ve=We,Na=V,Qr=ve,Fa=Q.Buffer,La=[1518500249,1859775393,-1894007588,-899497514],$a=new Array(80);function Be(){this.init(),this._w=$a,Qr.call(this,64,56)}Na(Be,Qr);Be.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function ja(e){return e<<5|e>>>27}function Ua(e){return e<<30|e>>>2}function qa(e,t,r,a){return e===0?t&r|~t&a:e===2?t&r|t&a|r&a:t^r^a}Be.prototype._update=function(e){for(var t=this._w,r=this._a|0,a=this._b|0,o=this._c|0,c=this._d|0,h=this._e|0,u=0;u<16;++u)t[u]=e.readInt32BE(u*4);for(;u<80;++u)t[u]=t[u-3]^t[u-8]^t[u-14]^t[u-16];for(var f=0;f<80;++f){var d=~~(f/20),g=ja(r)+qa(d,a,o,c)+h+t[f]+La[d]|0;h=c,c=o,o=Ua(a),a=r,r=g}this._a=r+this._a|0,this._b=a+this._b|0,this._c=o+this._c|0,this._d=c+this._d|0,this._e=h+this._e|0};Be.prototype._hash=function(){var e=Fa.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};var ka=Be,Wa=V,Zr=ve,Ha=Q.Buffer,Ga=[1518500249,1859775393,-1894007588,-899497514],Va=new Array(80);function Oe(){this.init(),this._w=Va,Zr.call(this,64,56)}Wa(Oe,Zr);Oe.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function Ya(e){return e<<1|e>>>31}function Ka(e){return e<<5|e>>>27}function za(e){return e<<30|e>>>2}function Ja(e,t,r,a){return e===0?t&r|~t&a:e===2?t&r|t&a|r&a:t^r^a}Oe.prototype._update=function(e){for(var t=this._w,r=this._a|0,a=this._b|0,o=this._c|0,c=this._d|0,h=this._e|0,u=0;u<16;++u)t[u]=e.readInt32BE(u*4);for(;u<80;++u)t[u]=Ya(t[u-3]^t[u-8]^t[u-14]^t[u-16]);for(var f=0;f<80;++f){var d=~~(f/20),g=Ka(r)+Ja(d,a,o,c)+h+t[f]+Ga[d]|0;h=c,c=o,o=za(a),a=r,r=g}this._a=r+this._a|0,this._b=a+this._b|0,this._c=o+this._c|0,this._d=c+this._d|0,this._e=h+this._e|0};Oe.prototype._hash=function(){var e=Ha.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};var Xa=Oe,Qa=V,en=ve,Za=Q.Buffer,eo=[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],to=new Array(64);function Ce(){this.init(),this._w=to,en.call(this,64,56)}Qa(Ce,en);Ce.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function ro(e,t,r){return r^e&(t^r)}function no(e,t,r){return e&t|r&(e|t)}function io(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function ao(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function oo(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}function fo(e){return(e>>>17|e<<15)^(e>>>19|e<<13)^e>>>10}Ce.prototype._update=function(e){for(var t=this._w,r=this._a|0,a=this._b|0,o=this._c|0,c=this._d|0,h=this._e|0,u=this._f|0,f=this._g|0,d=this._h|0,g=0;g<16;++g)t[g]=e.readInt32BE(g*4);for(;g<64;++g)t[g]=fo(t[g-2])+t[g-7]+oo(t[g-15])+t[g-16]|0;for(var w=0;w<64;++w){var R=d+ao(h)+ro(h,u,f)+eo[w]+t[w]|0,N=io(r)+no(r,a,o)|0;d=f,f=u,u=h,h=c+R|0,c=o,o=a,a=r,r=R+N|0}this._a=r+this._a|0,this._b=a+this._b|0,this._c=o+this._c|0,this._d=c+this._d|0,this._e=h+this._e|0,this._f=u+this._f|0,this._g=f+this._g|0,this._h=d+this._h|0};Ce.prototype._hash=function(){var e=Za.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e};var tn=Ce,so=V,lo=tn,uo=ve,co=Q.Buffer,ho=new Array(64);function He(){this.init(),this._w=ho,uo.call(this,64,56)}so(He,lo);He.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this};He.prototype._hash=function(){var e=co.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e};var po=He,yo=V,rn=ve,vo=Q.Buffer,wr=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],bo=new Array(160);function Me(){this.init(),this._w=bo,rn.call(this,128,112)}yo(Me,rn);Me.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function Er(e,t,r){return r^e&(t^r)}function Sr(e,t,r){return e&t|r&(e|t)}function xr(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function Ar(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function _o(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function go(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function wo(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function Eo(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function U(e,t){return e>>>0>>0?1:0}Me.prototype._update=function(e){for(var t=this._w,r=this._ah|0,a=this._bh|0,o=this._ch|0,c=this._dh|0,h=this._eh|0,u=this._fh|0,f=this._gh|0,d=this._hh|0,g=this._al|0,w=this._bl|0,R=this._cl|0,N=this._dl|0,A=this._el|0,x=this._fl|0,y=this._gl|0,v=this._hl|0,E=0;E<32;E+=2)t[E]=e.readInt32BE(E*4),t[E+1]=e.readInt32BE(E*4+4);for(;E<160;E+=2){var b=t[E-30],S=t[E-15*2+1],P=_o(b,S),O=go(S,b);b=t[E-2*2],S=t[E-2*2+1];var L=wo(b,S),C=Eo(S,b),B=t[E-7*2],W=t[E-7*2+1],ee=t[E-16*2],ne=t[E-16*2+1],j=O+W|0,H=P+B+U(j,O)|0;j=j+C|0,H=H+L+U(j,C)|0,j=j+ne|0,H=H+ee+U(j,ne)|0,t[E]=H,t[E+1]=j}for(var G=0;G<160;G+=2){H=t[G],j=t[G+1];var be=Sr(r,a,o),z=Sr(g,w,R),ie=xr(r,g),J=xr(g,r),ae=Ar(h,A),_e=Ar(A,h),oe=wr[G],Y=wr[G+1],ge=Er(h,u,f),fe=Er(A,x,y),l=v+_e|0,s=d+ae+U(l,v)|0;l=l+fe|0,s=s+ge+U(l,fe)|0,l=l+Y|0,s=s+oe+U(l,Y)|0,l=l+j|0,s=s+H+U(l,j)|0;var _=J+z|0,T=ie+be+U(_,J)|0;d=f,v=y,f=u,y=x,u=h,x=A,A=N+l|0,h=c+s+U(A,N)|0,c=o,N=R,o=a,R=w,a=r,w=g,g=l+_|0,r=s+T+U(g,l)|0}this._al=this._al+g|0,this._bl=this._bl+w|0,this._cl=this._cl+R|0,this._dl=this._dl+N|0,this._el=this._el+A|0,this._fl=this._fl+x|0,this._gl=this._gl+y|0,this._hl=this._hl+v|0,this._ah=this._ah+r+U(this._al,g)|0,this._bh=this._bh+a+U(this._bl,w)|0,this._ch=this._ch+o+U(this._cl,R)|0,this._dh=this._dh+c+U(this._dl,N)|0,this._eh=this._eh+h+U(this._el,A)|0,this._fh=this._fh+u+U(this._fl,x)|0,this._gh=this._gh+f+U(this._gl,y)|0,this._hh=this._hh+d+U(this._hl,v)|0};Me.prototype._hash=function(){var e=vo.allocUnsafe(64);function t(r,a,o){e.writeInt32BE(r,o),e.writeInt32BE(a,o+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e};var nn=Me,So=V,xo=nn,Ao=ve,mo=Q.Buffer,Ro=new Array(160);function Ge(){this.init(),this._w=Ro,Ao.call(this,128,112)}So(Ge,xo);Ge.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this};Ge.prototype._hash=function(){var e=mo.allocUnsafe(48);function t(r,a,o){e.writeInt32BE(r,o),e.writeInt32BE(a,o+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e};var To=Ge;(function(e){e.exports=function(r){var a=r.toLowerCase(),o=e.exports[a];if(!o)throw new Error(a+" is not supported (we accept pull requests)");return new o},e.exports.sha=ka,e.exports.sha1=Xa,e.exports.sha224=po,e.exports.sha256=tn,e.exports.sha384=To,e.exports.sha512=nn})(Lr);var Oo=Lr.exports;export{Ot as a,Oo as b,V as i,Bo as r,Q as s}; diff --git a/dist/assets/index-Cl4M8jG7.js b/dist/assets/index-Cl4M8jG7.js new file mode 100644 index 0000000..a25904a --- /dev/null +++ b/dist/assets/index-Cl4M8jG7.js @@ -0,0 +1 @@ +import{aO as O,aP as q,aQ as _t}from"./index-Cr5N_0pd.js";import{h as Tt}from"./hashTypedData-D0Cx__mD.js";const Ee=()=>"9.1.0",It=e=>e.toString(16).padStart(2,"0"),At=e=>{const s=new Uint8Array(e/2);return window.crypto.getRandomValues(s),Array.from(s,It).join("")},vt=()=>typeof window<"u"?At(10):new Date().getTime().toString(36);class P{}P.makeRequest=(e,s)=>({id:vt(),method:e,params:s,env:{sdkVersion:Ee()}});P.makeResponse=(e,s,t)=>({id:e,success:!0,version:t,data:s});P.makeErrorResponse=(e,s,t)=>({id:e,success:!1,error:s,version:t});var h;(function(e){e.sendTransactions="sendTransactions",e.rpcCall="rpcCall",e.getChainInfo="getChainInfo",e.getSafeInfo="getSafeInfo",e.getTxBySafeTxHash="getTxBySafeTxHash",e.getSafeBalances="getSafeBalances",e.signMessage="signMessage",e.signTypedMessage="signTypedMessage",e.getEnvironmentInfo="getEnvironmentInfo",e.getOffChainSignature="getOffChainSignature",e.requestAddressBook="requestAddressBook",e.wallet_getPermissions="wallet_getPermissions",e.wallet_requestPermissions="wallet_requestPermissions"})(h||(h={}));var w;(function(e){e.requestAddressBook="requestAddressBook"})(w||(w={}));class pt{constructor(s=null,t=!1){this.allowedOrigins=null,this.callbacks=new Map,this.debugMode=!1,this.isServer=typeof window>"u",this.isValidMessage=({origin:n,data:c,source:i})=>{const u=!c,f=!this.isServer&&i===window.parent,E=typeof c.version<"u"&&parseInt(c.version.split(".")[0]),p=typeof E=="number"&&E>=1;let _=!0;return Array.isArray(this.allowedOrigins)&&(_=this.allowedOrigins.find(S=>S.test(n))!==void 0),!u&&f&&p&&_},this.logIncomingMessage=n=>{console.info(`Safe Apps SDK v1: A message was received from origin ${n.origin}. `,n.data)},this.onParentMessage=n=>{this.isValidMessage(n)&&(this.debugMode&&this.logIncomingMessage(n),this.handleIncomingMessage(n.data))},this.handleIncomingMessage=n=>{const{id:c}=n,i=this.callbacks.get(c);i&&(i(n),this.callbacks.delete(c))},this.send=(n,c)=>{const i=P.makeRequest(n,c);if(this.isServer)throw new Error("Window doesn't exist");return window.parent.postMessage(i,"*"),new Promise((u,f)=>{this.callbacks.set(i.id,E=>{if(!E.success){f(new Error(E.error));return}u(E)})})},this.allowedOrigins=s,this.debugMode=t,this.isServer||window.addEventListener("message",this.onParentMessage)}}const V=e=>typeof e=="object"&&e!=null&&"domain"in e&&"types"in e&&"message"in e;var b={},C={},D={},W=O&&O.__awaiter||function(e,s,t,n){function c(i){return i instanceof t?i:new t(function(u){u(i)})}return new(t||(t=Promise))(function(i,u){function f(_){try{p(n.next(_))}catch(S){u(S)}}function E(_){try{p(n.throw(_))}catch(S){u(S)}}function p(_){_.done?i(_.value):c(_.value).then(f,E)}p((n=n.apply(e,s||[])).next())})};Object.defineProperty(D,"__esModule",{value:!0});D.insertParams=Ot;D.stringifyQuery=yt;D.fetchData=mt;D.getData=Ct;const St=e=>typeof e=="object"&&e!==null&&("code"in e||"statusCode"in e)&&"message"in e;function Nt(e,s,t){return e.replace(new RegExp(`\\{${s}\\}`,"g"),t)}function Ot(e,s){return s?Object.keys(s).reduce((t,n)=>Nt(t,n,String(s[n])),e):e}function yt(e){if(!e)return"";const s=new URLSearchParams;Object.keys(e).forEach(n=>{e[n]!=null&&s.append(n,String(e[n]))});const t=s.toString();return t?`?${t}`:""}function _e(e){return W(this,void 0,void 0,function*(){var s;let t;try{t=yield e.json()}catch{t={}}if(!e.ok){const n=St(t)?`CGW error - ${(s=t.code)!==null&&s!==void 0?s:t.statusCode}: ${t.message}`:`CGW error - status ${e.statusText}`;throw new Error(n)}return t})}function mt(e,s,t,n,c){return W(this,void 0,void 0,function*(){const i=Object.assign({"Content-Type":"application/json"},n),u={method:s??"POST",headers:i};c&&(u.credentials=c),t!=null&&(u.body=typeof t=="string"?t:JSON.stringify(t));const f=yield fetch(e,u);return _e(f)})}function Ct(e,s,t){return W(this,void 0,void 0,function*(){const n={method:"GET"};s&&(n.headers=Object.assign(Object.assign({},s),{"Content-Type":"application/json"})),t&&(n.credentials=t);const c=yield fetch(e,n);return _e(c)})}Object.defineProperty(C,"__esModule",{value:!0});C.postEndpoint=Dt;C.putEndpoint=bt;C.deleteEndpoint=Rt;C.getEndpoint=Pt;const N=D;function L(e,s,t,n){const c=(0,N.insertParams)(s,t),i=(0,N.stringifyQuery)(n);return`${e}${c}${i}`}function Dt(e,s,t){const n=L(e,s,t?.path,t?.query);return(0,N.fetchData)(n,"POST",t?.body,t?.headers,t?.credentials)}function bt(e,s,t){const n=L(e,s,t?.path,t?.query);return(0,N.fetchData)(n,"PUT",t?.body,t?.headers,t?.credentials)}function Rt(e,s,t){const n=L(e,s,t?.path,t?.query);return(0,N.fetchData)(n,"DELETE",t?.body,t?.headers,t?.credentials)}function Pt(e,s,t,n){if(n)return(0,N.getData)(n,void 0,t?.credentials);const c=L(e,s,t?.path,t?.query);return(0,N.getData)(c,t?.headers,t?.credentials)}var M={};Object.defineProperty(M,"__esModule",{value:!0});M.DEFAULT_BASE_URL=void 0;M.DEFAULT_BASE_URL="https://safe-client.safe.global";var B={};Object.defineProperty(B,"__esModule",{value:!0});B.ImplementationVersionState=void 0;var K;(function(e){e.UP_TO_DATE="UP_TO_DATE",e.OUTDATED="OUTDATED",e.UNKNOWN="UNKNOWN"})(K||(B.ImplementationVersionState=K={}));var A={};Object.defineProperty(A,"__esModule",{value:!0});A.SafeAppSocialPlatforms=A.SafeAppFeatures=A.SafeAppAccessPolicyTypes=void 0;var k;(function(e){e.NoRestrictions="NO_RESTRICTIONS",e.DomainAllowlist="DOMAIN_ALLOWLIST"})(k||(A.SafeAppAccessPolicyTypes=k={}));var F;(function(e){e.BATCHED_TRANSACTIONS="BATCHED_TRANSACTIONS"})(F||(A.SafeAppFeatures=F={}));var X;(function(e){e.TWITTER="TWITTER",e.GITHUB="GITHUB",e.DISCORD="DISCORD",e.TELEGRAM="TELEGRAM"})(X||(A.SafeAppSocialPlatforms=X={}));var l={};Object.defineProperty(l,"__esModule",{value:!0});l.LabelValue=l.StartTimeValue=l.DurationType=l.DetailedExecutionInfoType=l.TransactionListItemType=l.ConflictType=l.TransactionInfoType=l.SettingsInfoType=l.TransactionTokenType=l.TransferDirection=l.TransactionStatus=l.Operation=void 0;var Q;(function(e){e[e.CALL=0]="CALL",e[e.DELEGATE=1]="DELEGATE"})(Q||(l.Operation=Q={}));var $;(function(e){e.AWAITING_CONFIRMATIONS="AWAITING_CONFIRMATIONS",e.AWAITING_EXECUTION="AWAITING_EXECUTION",e.CANCELLED="CANCELLED",e.FAILED="FAILED",e.SUCCESS="SUCCESS"})($||(l.TransactionStatus=$={}));var Y;(function(e){e.INCOMING="INCOMING",e.OUTGOING="OUTGOING",e.UNKNOWN="UNKNOWN"})(Y||(l.TransferDirection=Y={}));var J;(function(e){e.ERC20="ERC20",e.ERC721="ERC721",e.NATIVE_COIN="NATIVE_COIN"})(J||(l.TransactionTokenType=J={}));var z;(function(e){e.SET_FALLBACK_HANDLER="SET_FALLBACK_HANDLER",e.ADD_OWNER="ADD_OWNER",e.REMOVE_OWNER="REMOVE_OWNER",e.SWAP_OWNER="SWAP_OWNER",e.CHANGE_THRESHOLD="CHANGE_THRESHOLD",e.CHANGE_IMPLEMENTATION="CHANGE_IMPLEMENTATION",e.ENABLE_MODULE="ENABLE_MODULE",e.DISABLE_MODULE="DISABLE_MODULE",e.SET_GUARD="SET_GUARD",e.DELETE_GUARD="DELETE_GUARD"})(z||(l.SettingsInfoType=z={}));var Z;(function(e){e.TRANSFER="Transfer",e.SETTINGS_CHANGE="SettingsChange",e.CUSTOM="Custom",e.CREATION="Creation",e.SWAP_ORDER="SwapOrder",e.TWAP_ORDER="TwapOrder",e.SWAP_TRANSFER="SwapTransfer",e.NATIVE_STAKING_DEPOSIT="NativeStakingDeposit",e.NATIVE_STAKING_VALIDATORS_EXIT="NativeStakingValidatorsExit",e.NATIVE_STAKING_WITHDRAW="NativeStakingWithdraw"})(Z||(l.TransactionInfoType=Z={}));var x;(function(e){e.NONE="None",e.HAS_NEXT="HasNext",e.END="End"})(x||(l.ConflictType=x={}));var ee;(function(e){e.TRANSACTION="TRANSACTION",e.LABEL="LABEL",e.CONFLICT_HEADER="CONFLICT_HEADER",e.DATE_LABEL="DATE_LABEL"})(ee||(l.TransactionListItemType=ee={}));var te;(function(e){e.MULTISIG="MULTISIG",e.MODULE="MODULE"})(te||(l.DetailedExecutionInfoType=te={}));var ne;(function(e){e.AUTO="AUTO",e.LIMIT_DURATION="LIMIT_DURATION"})(ne||(l.DurationType=ne={}));var se;(function(e){e.AT_MINING_TIME="AT_MINING_TIME",e.AT_EPOCH="AT_EPOCH"})(se||(l.StartTimeValue=se={}));var ae;(function(e){e.Queued="Queued",e.Next="Next"})(ae||(l.LabelValue=ae={}));var v={};Object.defineProperty(v,"__esModule",{value:!0});v.FEATURES=v.GAS_PRICE_TYPE=v.RPC_AUTHENTICATION=void 0;var ie;(function(e){e.API_KEY_PATH="API_KEY_PATH",e.NO_AUTHENTICATION="NO_AUTHENTICATION",e.UNKNOWN="UNKNOWN"})(ie||(v.RPC_AUTHENTICATION=ie={}));var re;(function(e){e.ORACLE="ORACLE",e.FIXED="FIXED",e.FIXED_1559="FIXED1559",e.UNKNOWN="UNKNOWN"})(re||(v.GAS_PRICE_TYPE=re={}));var oe;(function(e){e.ERC721="ERC721",e.SAFE_APPS="SAFE_APPS",e.CONTRACT_INTERACTION="CONTRACT_INTERACTION",e.DOMAIN_LOOKUP="DOMAIN_LOOKUP",e.SPENDING_LIMIT="SPENDING_LIMIT",e.EIP1559="EIP1559",e.SAFE_TX_GAS_OPTIONAL="SAFE_TX_GAS_OPTIONAL",e.TX_SIMULATION="TX_SIMULATION",e.EIP1271="EIP1271"})(oe||(v.FEATURES=oe={}));var G={};Object.defineProperty(G,"__esModule",{value:!0});G.TokenType=void 0;var ce;(function(e){e.ERC20="ERC20",e.ERC721="ERC721",e.NATIVE_TOKEN="NATIVE_TOKEN",e.UNKNOWN="UNKNOWN"})(ce||(G.TokenType=ce={}));var Te={};Object.defineProperty(Te,"__esModule",{value:!0});var y={};Object.defineProperty(y,"__esModule",{value:!0});y.NativeStakingStatus=y.ConfirmationViewTypes=void 0;var de;(function(e){e.GENERIC="GENERIC",e.COW_SWAP_ORDER="COW_SWAP_ORDER",e.COW_SWAP_TWAP_ORDER="COW_SWAP_TWAP_ORDER",e.KILN_NATIVE_STAKING_DEPOSIT="KILN_NATIVE_STAKING_DEPOSIT",e.KILN_NATIVE_STAKING_VALIDATORS_EXIT="KILN_NATIVE_STAKING_VALIDATORS_EXIT",e.KILN_NATIVE_STAKING_WITHDRAW="KILN_NATIVE_STAKING_WITHDRAW"})(de||(y.ConfirmationViewTypes=de={}));var ue;(function(e){e.NOT_STAKED="NOT_STAKED",e.ACTIVATING="ACTIVATING",e.DEPOSIT_IN_PROGRESS="DEPOSIT_IN_PROGRESS",e.ACTIVE="ACTIVE",e.EXIT_REQUESTED="EXIT_REQUESTED",e.EXITING="EXITING",e.EXITED="EXITED",e.SLASHED="SLASHED"})(ue||(y.NativeStakingStatus=ue={}));var m={};Object.defineProperty(m,"__esModule",{value:!0});m.SafeMessageStatus=m.SafeMessageListItemType=void 0;var le;(function(e){e.DATE_LABEL="DATE_LABEL",e.MESSAGE="MESSAGE"})(le||(m.SafeMessageListItemType=le={}));var fe;(function(e){e.NEEDS_CONFIRMATION="NEEDS_CONFIRMATION",e.CONFIRMED="CONFIRMED"})(fe||(m.SafeMessageStatus=fe={}));var H={};Object.defineProperty(H,"__esModule",{value:!0});H.DeviceType=void 0;var he;(function(e){e.ANDROID="ANDROID",e.IOS="IOS",e.WEB="WEB"})(he||(H.DeviceType=he={}));var Ie={};Object.defineProperty(Ie,"__esModule",{value:!0});(function(e){var s=O&&O.__createBinding||(Object.create?function(a,r,o,d){d===void 0&&(d=o);var T=Object.getOwnPropertyDescriptor(r,o);(!T||("get"in T?!r.__esModule:T.writable||T.configurable))&&(T={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(a,d,T)}:function(a,r,o,d){d===void 0&&(d=o),a[d]=r[o]}),t=O&&O.__exportStar||function(a,r){for(var o in a)o!=="default"&&!Object.prototype.hasOwnProperty.call(r,o)&&s(r,a,o)};Object.defineProperty(e,"__esModule",{value:!0}),e.setBaseUrl=void 0,e.relayTransaction=f,e.getRelayCount=E,e.getSafeInfo=p,e.getIncomingTransfers=_,e.getModuleTransactions=S,e.getMultisigTransactions=pe,e.getBalances=Se,e.getFiatCurrencies=Ne,e.getOwnedSafes=Oe,e.getAllOwnedSafes=ye,e.getCollectibles=me,e.getCollectiblesPage=Ce,e.getTransactionHistory=De,e.getTransactionQueue=be,e.getTransactionDetails=Re,e.deleteTransaction=Pe,e.postSafeGasEstimation=we,e.getNonces=Le,e.proposeTransaction=Me,e.getConfirmationView=Be,e.getTxPreview=Ge,e.getChainsConfig=He,e.getChainConfig=Ue,e.getSafeApps=je,e.getMasterCopies=Ve,e.getDecodedData=We,e.getSafeMessages=qe,e.getSafeMessage=Ke,e.proposeSafeMessage=ke,e.confirmSafeMessage=Fe,e.getDelegates=Xe,e.registerDevice=Qe,e.unregisterSafe=$e,e.unregisterDevice=Ye,e.registerEmail=Je,e.changeEmail=ze,e.resendEmailVerificationCode=Ze,e.verifyEmail=xe,e.getRegisteredEmail=et,e.deleteRegisteredEmail=tt,e.registerRecoveryModule=nt,e.unsubscribeSingle=st,e.unsubscribeAll=at,e.getSafeOverviews=it,e.getContract=rt,e.getAuthNonce=ot,e.verifyAuth=ct,e.createAccount=dt,e.getAccount=ut,e.deleteAccount=lt,e.getAccountDataTypes=ft,e.getAccountDataSettings=ht,e.putAccountDataSettings=gt,e.getIndexingStatus=Et;const n=C,c=M;t(B,e),t(A,e),t(l,e),t(v,e),t(G,e),t(Te,e),t(y,e),t(m,e),t(H,e),t(Ie,e);let i=c.DEFAULT_BASE_URL;const u=a=>{i=a};e.setBaseUrl=u;function f(a,r){return(0,n.postEndpoint)(i,"/v1/chains/{chainId}/relay",{path:{chainId:a},body:r})}function E(a,r){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/relay/{address}",{path:{chainId:a,address:r}})}function p(a,r){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{address}",{path:{chainId:a,address:r}})}function _(a,r,o,d){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{address}/incoming-transfers/",{path:{chainId:a,address:r},query:o},d)}function S(a,r,o,d){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{address}/module-transactions/",{path:{chainId:a,address:r},query:o},d)}function pe(a,r,o,d){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{address}/multisig-transactions/",{path:{chainId:a,address:r},query:o},d)}function Se(a,r,o="usd",d={}){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{address}/balances/{currency}",{path:{chainId:a,address:r,currency:o},query:d})}function Ne(){return(0,n.getEndpoint)(i,"/v1/balances/supported-fiat-codes")}function Oe(a,r){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/owners/{address}/safes",{path:{chainId:a,address:r}})}function ye(a){return(0,n.getEndpoint)(i,"/v1/owners/{address}/safes",{path:{address:a}})}function me(a,r,o={}){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{address}/collectibles",{path:{chainId:a,address:r},query:o})}function Ce(a,r,o={},d){return(0,n.getEndpoint)(i,"/v2/chains/{chainId}/safes/{address}/collectibles",{path:{chainId:a,address:r},query:o},d)}function De(a,r,o={},d){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/transactions/history",{path:{chainId:a,safe_address:r},query:o},d)}function be(a,r,o={},d){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/transactions/queued",{path:{chainId:a,safe_address:r},query:o},d)}function Re(a,r){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/transactions/{transactionId}",{path:{chainId:a,transactionId:r}})}function Pe(a,r,o){return(0,n.deleteEndpoint)(i,"/v1/chains/{chainId}/transactions/{safeTxHash}",{path:{chainId:a,safeTxHash:r},body:{signature:o}})}function we(a,r,o){return(0,n.postEndpoint)(i,"/v2/chains/{chainId}/safes/{safe_address}/multisig-transactions/estimations",{path:{chainId:a,safe_address:r},body:o})}function Le(a,r){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/nonces",{path:{chainId:a,safe_address:r}})}function Me(a,r,o){return(0,n.postEndpoint)(i,"/v1/chains/{chainId}/transactions/{safe_address}/propose",{path:{chainId:a,safe_address:r},body:o})}function Be(a,r,o,d,T,U){return(0,n.postEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/views/transaction-confirmation",{path:{chainId:a,safe_address:r},body:{operation:o,data:d,to:T,value:U}})}function Ge(a,r,o,d,T,U){return(0,n.postEndpoint)(i,"/v1/chains/{chainId}/transactions/{safe_address}/preview",{path:{chainId:a,safe_address:r},body:{operation:o,data:d,to:T,value:U}})}function He(a){return(0,n.getEndpoint)(i,"/v1/chains",{query:a})}function Ue(a){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}",{path:{chainId:a}})}function je(a,r={}){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safe-apps",{path:{chainId:a},query:r})}function Ve(a){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/about/master-copies",{path:{chainId:a}})}function We(a,r,o,d){return(0,n.postEndpoint)(i,"/v1/chains/{chainId}/data-decoder",{path:{chainId:a},body:{operation:r,data:o,to:d}})}function qe(a,r,o){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/messages",{path:{chainId:a,safe_address:r},query:{}},o)}function Ke(a,r){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/messages/{message_hash}",{path:{chainId:a,message_hash:r}})}function ke(a,r,o){return(0,n.postEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/messages",{path:{chainId:a,safe_address:r},body:o})}function Fe(a,r,o){return(0,n.postEndpoint)(i,"/v1/chains/{chainId}/messages/{message_hash}/signatures",{path:{chainId:a,message_hash:r},body:o})}function Xe(a,r={}){return(0,n.getEndpoint)(i,"/v2/chains/{chainId}/delegates",{path:{chainId:a},query:r})}function Qe(a){return(0,n.postEndpoint)(i,"/v1/register/notifications",{body:a})}function $e(a,r,o){return(0,n.deleteEndpoint)(i,"/v1/chains/{chainId}/notifications/devices/{uuid}/safes/{safe_address}",{path:{chainId:a,safe_address:r,uuid:o}})}function Ye(a,r){return(0,n.deleteEndpoint)(i,"/v1/chains/{chainId}/notifications/devices/{uuid}",{path:{chainId:a,uuid:r}})}function Je(a,r,o,d){return(0,n.postEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/emails",{path:{chainId:a,safe_address:r},body:o,headers:d})}function ze(a,r,o,d,T){return(0,n.putEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}",{path:{chainId:a,safe_address:r,signer:o},body:d,headers:T})}function Ze(a,r,o){return(0,n.postEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}/verify-resend",{path:{chainId:a,safe_address:r,signer:o},body:""})}function xe(a,r,o,d){return(0,n.putEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}/verify",{path:{chainId:a,safe_address:r,signer:o},body:d})}function et(a,r,o,d){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}",{path:{chainId:a,safe_address:r,signer:o},headers:d})}function tt(a,r,o,d){return(0,n.deleteEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/emails/{signer}",{path:{chainId:a,safe_address:r,signer:o},headers:d})}function nt(a,r,o){return(0,n.postEndpoint)(i,"/v1/chains/{chainId}/safes/{safe_address}/recovery",{path:{chainId:a,safe_address:r},body:o})}function st(a){return(0,n.deleteEndpoint)(i,"/v1/subscriptions",{query:a})}function at(a){return(0,n.deleteEndpoint)(i,"/v1/subscriptions/all",{query:a})}function it(a,r){return(0,n.getEndpoint)(i,"/v1/safes",{query:Object.assign(Object.assign({},r),{safes:a.join(",")})})}function rt(a,r){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/contracts/{contractAddress}",{path:{chainId:a,contractAddress:r}})}function ot(){return(0,n.getEndpoint)(i,"/v1/auth/nonce",{credentials:"include"})}function ct(a){return(0,n.postEndpoint)(i,"/v1/auth/verify",{body:a,credentials:"include"})}function dt(a){return(0,n.postEndpoint)(i,"/v1/accounts",{body:a,credentials:"include"})}function ut(a){return(0,n.getEndpoint)(i,"/v1/accounts/{address}",{path:{address:a},credentials:"include"})}function lt(a){return(0,n.deleteEndpoint)(i,"/v1/accounts/{address}",{path:{address:a},credentials:"include"})}function ft(){return(0,n.getEndpoint)(i,"/v1/accounts/data-types")}function ht(a){return(0,n.getEndpoint)(i,"/v1/accounts/{address}/data-settings",{path:{address:a},credentials:"include"})}function gt(a,r){return(0,n.putEndpoint)(i,"/v1/accounts/{address}/data-settings",{path:{address:a},body:r,credentials:"include"})}function Et(a){return(0,n.getEndpoint)(i,"/v1/chains/{chainId}/about/indexing",{path:{chainId:a}})}})(b);class wt{constructor(s){this.communicator=s}async getBySafeTxHash(s){if(!s)throw new Error("Invalid safeTxHash");return(await this.communicator.send(h.getTxBySafeTxHash,{safeTxHash:s})).data}async signMessage(s){const t={message:s};return(await this.communicator.send(h.signMessage,t)).data}async signTypedMessage(s){if(!V(s))throw new Error("Invalid typed data");return(await this.communicator.send(h.signTypedMessage,{typedData:s})).data}async send({txs:s,params:t}){if(!s||!s.length)throw new Error("No transactions were passed");const n={txs:s,params:t};return(await this.communicator.send(h.sendTransactions,n)).data}}const g={eth_call:"eth_call",eth_gasPrice:"eth_gasPrice",eth_getLogs:"eth_getLogs",eth_getBalance:"eth_getBalance",eth_getCode:"eth_getCode",eth_getBlockByHash:"eth_getBlockByHash",eth_getBlockByNumber:"eth_getBlockByNumber",eth_getStorageAt:"eth_getStorageAt",eth_getTransactionByHash:"eth_getTransactionByHash",eth_getTransactionReceipt:"eth_getTransactionReceipt",eth_getTransactionCount:"eth_getTransactionCount",eth_estimateGas:"eth_estimateGas",safe_setSettings:"safe_setSettings"},I={defaultBlockParam:(e="latest")=>e,returnFullTxObjectParam:(e=!1)=>e,blockNumberToHex:e=>Number.isInteger(e)?`0x${e.toString(16)}`:e};class Lt{constructor(s){this.communicator=s,this.call=this.buildRequest({call:g.eth_call,formatters:[null,I.defaultBlockParam]}),this.getBalance=this.buildRequest({call:g.eth_getBalance,formatters:[null,I.defaultBlockParam]}),this.getCode=this.buildRequest({call:g.eth_getCode,formatters:[null,I.defaultBlockParam]}),this.getStorageAt=this.buildRequest({call:g.eth_getStorageAt,formatters:[null,I.blockNumberToHex,I.defaultBlockParam]}),this.getPastLogs=this.buildRequest({call:g.eth_getLogs}),this.getBlockByHash=this.buildRequest({call:g.eth_getBlockByHash,formatters:[null,I.returnFullTxObjectParam]}),this.getBlockByNumber=this.buildRequest({call:g.eth_getBlockByNumber,formatters:[I.blockNumberToHex,I.returnFullTxObjectParam]}),this.getTransactionByHash=this.buildRequest({call:g.eth_getTransactionByHash}),this.getTransactionReceipt=this.buildRequest({call:g.eth_getTransactionReceipt}),this.getTransactionCount=this.buildRequest({call:g.eth_getTransactionCount,formatters:[null,I.defaultBlockParam]}),this.getGasPrice=this.buildRequest({call:g.eth_gasPrice}),this.getEstimateGas=t=>this.buildRequest({call:g.eth_estimateGas})([t]),this.setSafeSettings=this.buildRequest({call:g.safe_setSettings})}buildRequest(s){const{call:t,formatters:n}=s;return async c=>{n&&Array.isArray(c)&&n.forEach((f,E)=>{f&&(c[E]=f(c[E]))});const i={call:t,params:c||[]};return(await this.communicator.send(h.rpcCall,i)).data}}}const Mt="0x1626ba7e",Bt="0x20c13b0b",j=4001;class R extends Error{constructor(s,t,n){super(s),this.code=t,this.data=n,Object.setPrototypeOf(this,R.prototype)}}class Ae{constructor(s){this.communicator=s}async getPermissions(){return(await this.communicator.send(h.wallet_getPermissions,void 0)).data}async requestPermissions(s){if(!this.isPermissionRequestValid(s))throw new R("Permissions request is invalid",j);try{return(await this.communicator.send(h.wallet_requestPermissions,s)).data}catch{throw new R("Permissions rejected",j)}}isPermissionRequestValid(s){return s.every(t=>typeof t=="object"?Object.keys(t).every(n=>!!Object.values(w).includes(n)):!1)}}const ge=(e,s)=>s.some(t=>t.parentCapability===e),Gt=()=>(e,s,t)=>{const n=t.value;return t.value=async function(){const c=new Ae(this.communicator);let i=await c.getPermissions();if(ge(s,i)||(i=await c.requestPermissions([{[s]:{}}])),!ge(s,i))throw new R("Permissions rejected",j);return n.apply(this)},t};var Ht=function(e,s,t,n){var c=arguments.length,i=c<3?s:n===null?n=Object.getOwnPropertyDescriptor(s,t):n,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(e,s,t,n);else for(var f=e.length-1;f>=0;f--)(u=e[f])&&(i=(c<3?u(i):c>3?u(s,t,i):u(s,t))||i);return c>3&&i&&Object.defineProperty(s,t,i),i};class ve{constructor(s){this.communicator=s}async getChainInfo(){return(await this.communicator.send(h.getChainInfo,void 0)).data}async getInfo(){return(await this.communicator.send(h.getSafeInfo,void 0)).data}async experimental_getBalances({currency:s="usd"}={}){return(await this.communicator.send(h.getSafeBalances,{currency:s})).data}async check1271Signature(s,t="0x"){const n=await this.getInfo(),c=q({abi:[{constant:!1,inputs:[{name:"_dataHash",type:"bytes32"},{name:"_signature",type:"bytes"}],name:"isValidSignature",outputs:[{name:"",type:"bytes4"}],payable:!1,stateMutability:"nonpayable",type:"function"}],functionName:"isValidSignature",args:[s,t]}),i={call:g.eth_call,params:[{to:n.safeAddress,data:c},"latest"]};try{return(await this.communicator.send(h.rpcCall,i)).data.slice(0,10).toLowerCase()===Mt}catch{return!1}}async check1271SignatureBytes(s,t="0x"){const n=await this.getInfo(),c=q({abi:[{constant:!1,inputs:[{name:"_data",type:"bytes"},{name:"_signature",type:"bytes"}],name:"isValidSignature",outputs:[{name:"",type:"bytes4"}],payable:!1,stateMutability:"nonpayable",type:"function"}],functionName:"isValidSignature",args:[s,t]}),i={call:g.eth_call,params:[{to:n.safeAddress,data:c},"latest"]};try{return(await this.communicator.send(h.rpcCall,i)).data.slice(0,10).toLowerCase()===Bt}catch{return!1}}calculateMessageHash(s){return _t(s)}calculateTypedMessageHash(s){const t=typeof s.domain.chainId=="object"?s.domain.chainId.toNumber():Number(s.domain.chainId);let n=s.primaryType;if(!n){const c=Object.values(s.types),i=Object.keys(s.types).filter(u=>c.every(f=>f.every(({type:E})=>E.replace("[","").replace("]","")!==u)));if(i.length===0||i.length>1)throw new Error("Please specify primaryType");n=i[0]}return Tt({message:s.message,domain:{...s.domain,chainId:t,verifyingContract:s.domain.verifyingContract,salt:s.domain.salt},types:s.types,primaryType:n})}async getOffChainSignature(s){return(await this.communicator.send(h.getOffChainSignature,s)).data}async isMessageSigned(s,t="0x"){let n;if(typeof s=="string"&&(n=async()=>{const c=this.calculateMessageHash(s);return await this.isMessageHashSigned(c,t)}),V(s)&&(n=async()=>{const c=this.calculateTypedMessageHash(s);return await this.isMessageHashSigned(c,t)}),n)return await n();throw new Error("Invalid message type")}async isMessageHashSigned(s,t="0x"){const n=[this.check1271Signature.bind(this),this.check1271SignatureBytes.bind(this)];for(const c of n)if(await c(s,t))return!0;return!1}async getEnvironmentInfo(){return(await this.communicator.send(h.getEnvironmentInfo,void 0)).data}async requestAddressBook(){return(await this.communicator.send(h.requestAddressBook,void 0)).data}}Ht([Gt()],ve.prototype,"requestAddressBook",null);class Ut{constructor(s={}){const{allowedDomains:t=null,debug:n=!1}=s;this.communicator=new pt(t,n),this.eth=new Lt(this.communicator),this.txs=new wt(this.communicator),this.safe=new ve(this.communicator),this.wallet=new Ae(this.communicator)}}const Wt=Object.freeze(Object.defineProperty({__proto__:null,MessageFormatter:P,get Methods(){return h},Operation:b.Operation,RPC_CALLS:g,get RestrictedMethods(){return w},TokenType:b.TokenType,TransactionStatus:b.TransactionStatus,TransferDirection:b.TransferDirection,default:Ut,getSDKVersion:Ee,isObjectEIP712TypedData:V},Symbol.toStringTag,{value:"Module"}));export{Wt as e}; diff --git a/dist/assets/index-CqL7mnh0.js b/dist/assets/index-CqL7mnh0.js new file mode 100644 index 0000000..450d107 --- /dev/null +++ b/dist/assets/index-CqL7mnh0.js @@ -0,0 +1,2 @@ +import{aR as Xf,aS as Kr,aO as af,ai as Qf}from"./index-Cr5N_0pd.js";import{s as ut,r as jf,i as ct,a as ei,b as ti}from"./index-COonna6N.js";function ri(f,t){for(var n=0;nh[d]})}}}return Object.freeze(Object.defineProperty(f,Symbol.toStringTag,{value:"Module"}))}var y0=ut.Buffer,fi=9007199254740991;function S0(f){if(f<0||f>fi||f%1!==0)throw new RangeError("value out of range")}function Nr(f,t,n){if(S0(f),t||(t=y0.allocUnsafe(nf(f))),!y0.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),f<253?(t.writeUInt8(f,n),Nr.bytes=1):f<=65535?(t.writeUInt8(253,n),t.writeUInt16LE(f,n+1),Nr.bytes=3):f<=4294967295?(t.writeUInt8(254,n),t.writeUInt32LE(f,n+1),Nr.bytes=5):(t.writeUInt8(255,n),t.writeUInt32LE(f>>>0,n+1),t.writeUInt32LE(f/4294967296|0,n+5),Nr.bytes=9),t}function Tr(f,t){if(!y0.isBuffer(f))throw new TypeError("buffer must be a Buffer instance");t||(t=0);var n=f.readUInt8(t);if(n<253)return Tr.bytes=1,n;if(n===253)return Tr.bytes=3,f.readUInt16LE(t+1);if(n===254)return Tr.bytes=5,f.readUInt32LE(t+1);Tr.bytes=9;var h=f.readUInt32LE(t+1),d=f.readUInt32LE(t+5),a=d*4294967296+h;return S0(a),a}function nf(f){return S0(f),f<253?1:f<=65535?3:f<=4294967295?5:9}var ii={encode:Nr,decode:Tr,encodingLength:nf},kr=ut.Buffer,hf=jf.Transform,ai=ct;function ni(f,t){if(!kr.isBuffer(f)&&typeof f!="string")throw new TypeError(t+" must be a string or a buffer")}function gt(f){hf.call(this),this._block=kr.allocUnsafe(f),this._blockSize=f,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}ai(gt,hf);gt.prototype._transform=function(f,t,n){var h=null;try{this.update(f,t)}catch(d){h=d}n(h)};gt.prototype._flush=function(f){var t=null;try{this.push(this.digest())}catch(n){t=n}f(t)};gt.prototype.update=function(f,t){if(ni(f,"Data"),this._finalized)throw new Error("Digest already called");kr.isBuffer(f)||(f=kr.from(f,t));for(var n=this._block,h=0;this._blockOffset+f.length-h>=this._blockSize;){for(var d=this._blockOffset;d0;++a)this._length[a]+=m,m=this._length[a]/4294967296|0,m>0&&(this._length[a]-=4294967296*m);return this};gt.prototype._update=function(){throw new Error("_update is not implemented")};gt.prototype.digest=function(f){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();f!==void 0&&(t=t.toString(f)),this._block.fill(0),this._blockOffset=0;for(var n=0;n<4;++n)this._length[n]=0;return t};gt.prototype._digest=function(){throw new Error("_digest is not implemented")};var sf=gt,hi=ct,df=sf,si=ut.Buffer,di=new Array(16);function Hr(){df.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}hi(Hr,df);Hr.prototype._update=function(){for(var f=di,t=0;t<16;++t)f[t]=this._block.readInt32LE(t*4);var n=this._a,h=this._b,d=this._c,a=this._d;n=ze(n,h,d,a,f[0],3614090360,7),a=ze(a,n,h,d,f[1],3905402710,12),d=ze(d,a,n,h,f[2],606105819,17),h=ze(h,d,a,n,f[3],3250441966,22),n=ze(n,h,d,a,f[4],4118548399,7),a=ze(a,n,h,d,f[5],1200080426,12),d=ze(d,a,n,h,f[6],2821735955,17),h=ze(h,d,a,n,f[7],4249261313,22),n=ze(n,h,d,a,f[8],1770035416,7),a=ze(a,n,h,d,f[9],2336552879,12),d=ze(d,a,n,h,f[10],4294925233,17),h=ze(h,d,a,n,f[11],2304563134,22),n=ze(n,h,d,a,f[12],1804603682,7),a=ze(a,n,h,d,f[13],4254626195,12),d=ze(d,a,n,h,f[14],2792965006,17),h=ze(h,d,a,n,f[15],1236535329,22),n=qe(n,h,d,a,f[1],4129170786,5),a=qe(a,n,h,d,f[6],3225465664,9),d=qe(d,a,n,h,f[11],643717713,14),h=qe(h,d,a,n,f[0],3921069994,20),n=qe(n,h,d,a,f[5],3593408605,5),a=qe(a,n,h,d,f[10],38016083,9),d=qe(d,a,n,h,f[15],3634488961,14),h=qe(h,d,a,n,f[4],3889429448,20),n=qe(n,h,d,a,f[9],568446438,5),a=qe(a,n,h,d,f[14],3275163606,9),d=qe(d,a,n,h,f[3],4107603335,14),h=qe(h,d,a,n,f[8],1163531501,20),n=qe(n,h,d,a,f[13],2850285829,5),a=qe(a,n,h,d,f[2],4243563512,9),d=qe(d,a,n,h,f[7],1735328473,14),h=qe(h,d,a,n,f[12],2368359562,20),n=Ve(n,h,d,a,f[5],4294588738,4),a=Ve(a,n,h,d,f[8],2272392833,11),d=Ve(d,a,n,h,f[11],1839030562,16),h=Ve(h,d,a,n,f[14],4259657740,23),n=Ve(n,h,d,a,f[1],2763975236,4),a=Ve(a,n,h,d,f[4],1272893353,11),d=Ve(d,a,n,h,f[7],4139469664,16),h=Ve(h,d,a,n,f[10],3200236656,23),n=Ve(n,h,d,a,f[13],681279174,4),a=Ve(a,n,h,d,f[0],3936430074,11),d=Ve(d,a,n,h,f[3],3572445317,16),h=Ve(h,d,a,n,f[6],76029189,23),n=Ve(n,h,d,a,f[9],3654602809,4),a=Ve(a,n,h,d,f[12],3873151461,11),d=Ve(d,a,n,h,f[15],530742520,16),h=Ve(h,d,a,n,f[2],3299628645,23),n=Ye(n,h,d,a,f[0],4096336452,6),a=Ye(a,n,h,d,f[7],1126891415,10),d=Ye(d,a,n,h,f[14],2878612391,15),h=Ye(h,d,a,n,f[5],4237533241,21),n=Ye(n,h,d,a,f[12],1700485571,6),a=Ye(a,n,h,d,f[3],2399980690,10),d=Ye(d,a,n,h,f[10],4293915773,15),h=Ye(h,d,a,n,f[1],2240044497,21),n=Ye(n,h,d,a,f[8],1873313359,6),a=Ye(a,n,h,d,f[15],4264355552,10),d=Ye(d,a,n,h,f[6],2734768916,15),h=Ye(h,d,a,n,f[13],1309151649,21),n=Ye(n,h,d,a,f[4],4149444226,6),a=Ye(a,n,h,d,f[11],3174756917,10),d=Ye(d,a,n,h,f[2],718787259,15),h=Ye(h,d,a,n,f[9],3951481745,21),this._a=this._a+n|0,this._b=this._b+h|0,this._c=this._c+d|0,this._d=this._d+a|0};Hr.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var f=si.allocUnsafe(16);return f.writeInt32LE(this._a,0),f.writeInt32LE(this._b,4),f.writeInt32LE(this._c,8),f.writeInt32LE(this._d,12),f};function Gr(f,t){return f<>>32-t}function ze(f,t,n,h,d,a,m){return Gr(f+(t&n|~t&h)+d+a|0,m)+t|0}function qe(f,t,n,h,d,a,m){return Gr(f+(t&h|n&~h)+d+a|0,m)+t|0}function Ve(f,t,n,h,d,a,m){return Gr(f+(t^n^h)+d+a|0,m)+t|0}function Ye(f,t,n,h,d,a,m){return Gr(f+(n^(t|~h))+d+a|0,m)+t|0}var oi=Hr,d0=Xf.Buffer,ui=ct,of=sf,ci=new Array(16),wr=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],Ar=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],Er=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],Ir=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],Sr=[0,1518500249,1859775393,2400959708,2840853838],Lr=[1352829926,1548603684,1836072691,2053994217,0];function Zr(){of.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}ui(Zr,of);Zr.prototype._update=function(){for(var f=ci,t=0;t<16;++t)f[t]=this._block.readInt32LE(t*4);for(var n=this._a|0,h=this._b|0,d=this._c|0,a=this._d|0,m=this._e|0,x=this._a|0,_=this._b|0,A=this._c|0,y=this._d|0,g=this._e|0,M=0;M<80;M+=1){var w,E;M<16?(w=V0(n,h,d,a,m,f[wr[M]],Sr[0],Er[M]),E=U0(x,_,A,y,g,f[Ar[M]],Lr[0],Ir[M])):M<32?(w=Y0(n,h,d,a,m,f[wr[M]],Sr[1],Er[M]),E=$0(x,_,A,y,g,f[Ar[M]],Lr[1],Ir[M])):M<48?(w=k0(n,h,d,a,m,f[wr[M]],Sr[2],Er[M]),E=k0(x,_,A,y,g,f[Ar[M]],Lr[2],Ir[M])):M<64?(w=$0(n,h,d,a,m,f[wr[M]],Sr[3],Er[M]),E=Y0(x,_,A,y,g,f[Ar[M]],Lr[3],Ir[M])):(w=U0(n,h,d,a,m,f[wr[M]],Sr[4],Er[M]),E=V0(x,_,A,y,g,f[Ar[M]],Lr[4],Ir[M])),n=m,m=a,a=Ot(d,10),d=h,h=w,x=g,g=y,y=Ot(A,10),A=_,_=E}var P=this._b+d+y|0;this._b=this._c+a+g|0,this._c=this._d+m+x|0,this._d=this._e+n+_|0,this._e=this._a+h+A|0,this._a=P};Zr.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var f=d0.alloc?d0.alloc(20):new d0(20);return f.writeInt32LE(this._a,0),f.writeInt32LE(this._b,4),f.writeInt32LE(this._c,8),f.writeInt32LE(this._d,12),f.writeInt32LE(this._e,16),f};function Ot(f,t){return f<>>32-t}function V0(f,t,n,h,d,a,m,x){return Ot(f+(t^n^h)+a+m|0,x)+d|0}function Y0(f,t,n,h,d,a,m,x){return Ot(f+(t&n|~t&h)+a+m|0,x)+d|0}function k0(f,t,n,h,d,a,m,x){return Ot(f+((t|~n)^h)+a+m|0,x)+d|0}function $0(f,t,n,h,d,a,m,x){return Ot(f+(t&h|n&~h)+a+m|0,x)+d|0}function U0(f,t,n,h,d,a,m,x){return Ot(f+(t^(n|~h))+a+m|0,x)+d|0}var li=Zr,je=ut.Buffer,uf=Kr.Transform,vi=ei.StringDecoder,bi=ct;function Xe(f){uf.call(this),this.hashMode=typeof f=="string",this.hashMode?this[f]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}bi(Xe,uf);var pi=typeof Uint8Array<"u",xi=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&ArrayBuffer.isView&&(je.prototype instanceof Uint8Array||je.TYPED_ARRAY_SUPPORT);function mi(f,t){if(f instanceof je)return f;if(typeof f=="string")return je.from(f,t);if(xi&&ArrayBuffer.isView(f)){if(f.byteLength===0)return je.alloc(0);var n=je.from(f.buffer,f.byteOffset,f.byteLength);if(n.byteLength===f.byteLength)return n}if(pi&&f instanceof Uint8Array||je.isBuffer(f)&&f.constructor&&typeof f.constructor.isBuffer=="function"&&f.constructor.isBuffer(f))return je.from(f);throw new TypeError('The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.')}Xe.prototype.update=function(f,t,n){var h=mi(f,t),d=this._update(h);return this.hashMode?this:(n&&(d=this._toString(d,n)),d)};Xe.prototype.setAutoPadding=function(){};Xe.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")};Xe.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")};Xe.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")};Xe.prototype._transform=function(f,t,n){var h;try{this.hashMode?this._update(f):this.push(this._update(f))}catch(d){h=d}finally{n(h)}};Xe.prototype._flush=function(f){var t;try{this.push(this.__final())}catch(n){t=n}f(t)};Xe.prototype._finalOrDigest=function(f){var t=this.__final()||je.alloc(0);return f&&(t=this._toString(t,f,!0)),t};Xe.prototype._toString=function(f,t,n){if(this._decoder||(this._decoder=new vi(t),this._encoding=t),this._encoding!==t)throw new Error("can’t switch encodings");var h=this._decoder.write(f);return n&&(h+=this._decoder.end()),h};var gi=Xe,_i=ct,yi=oi,Mi=li,wi=ti,cf=gi;function Wr(f){cf.call(this,"digest"),this._hash=f}_i(Wr,cf);Wr.prototype._update=function(f){this._hash.update(f)};Wr.prototype._final=function(){return this._hash.digest()};var L0=function(t){return t=t.toLowerCase(),t==="md5"?new yi:t==="rmd160"||t==="ripemd160"?new Mi:new Wr(wi(t))},lf={};const Ai="elliptic",Ei="6.6.1",Ii="EC cryptography",Si="lib/elliptic.js",Li=["lib"],Pi={lint:"eslint lib test","lint:fix":"npm run lint -- --fix",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},Bi={type:"git",url:"git@github.com:indutny/elliptic"},Ri=["EC","Elliptic","curve","Cryptography"],Ni="Fedor Indutny ",Ti="MIT",Ci={url:"https://github.com/indutny/elliptic/issues"},Di="https://github.com/indutny/elliptic",zi={brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},qi={"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"},Vi={name:Ai,version:Ei,description:Ii,main:Si,files:Li,scripts:Pi,repository:Bi,keywords:Ri,author:Ni,license:Ti,bugs:Ci,homepage:Di,devDependencies:zi,dependencies:qi};var Oe={},P0={exports:{}};P0.exports;(function(f){(function(t,n){function h(v,e){if(!v)throw new Error(e||"Assertion failed")}function d(v,e){v.super_=e;var i=function(){};i.prototype=e.prototype,v.prototype=new i,v.prototype.constructor=v}function a(v,e,i){if(a.isBN(v))return v;this.negative=0,this.words=null,this.length=0,this.red=null,v!==null&&((e==="le"||e==="be")&&(i=e,e=10),this._init(v||0,e||10,i||"be"))}typeof t=="object"?t.exports=a:n.BN=a,a.BN=a,a.wordSize=26;var m;try{typeof window<"u"&&typeof window.Buffer<"u"?m=window.Buffer:m=Kr.Buffer}catch{}a.isBN=function(e){return e instanceof a?!0:e!==null&&typeof e=="object"&&e.constructor.wordSize===a.wordSize&&Array.isArray(e.words)},a.max=function(e,i){return e.cmp(i)>0?e:i},a.min=function(e,i){return e.cmp(i)<0?e:i},a.prototype._init=function(e,i,s){if(typeof e=="number")return this._initNumber(e,i,s);if(typeof e=="object")return this._initArray(e,i,s);i==="hex"&&(i=16),h(i===(i|0)&&i>=2&&i<=36),e=e.toString().replace(/\s+/g,"");var o=0;e[0]==="-"&&(o++,this.negative=1),o=0;o-=3)b=e[o]|e[o-1]<<8|e[o-2]<<16,this.words[l]|=b<>>26-p&67108863,p+=24,p>=26&&(p-=26,l++);else if(s==="le")for(o=0,l=0;o>>26-p&67108863,p+=24,p>=26&&(p-=26,l++);return this.strip()};function x(v,e){var i=v.charCodeAt(e);return i>=65&&i<=70?i-55:i>=97&&i<=102?i-87:i-48&15}function _(v,e,i){var s=x(v,i);return i-1>=e&&(s|=x(v,i-1)<<4),s}a.prototype._parseHex=function(e,i,s){this.length=Math.ceil((e.length-i)/6),this.words=new Array(this.length);for(var o=0;o=i;o-=2)p=_(e,i,o)<=18?(l-=18,b+=1,this.words[b]|=p>>>26):l+=8;else{var u=e.length-i;for(o=u%2===0?i+1:i;o=18?(l-=18,b+=1,this.words[b]|=p>>>26):l+=8}this.strip()};function A(v,e,i,s){for(var o=0,l=Math.min(v.length,i),b=e;b=49?o+=p-49+10:p>=17?o+=p-17+10:o+=p}return o}a.prototype._parseBase=function(e,i,s){this.words=[0],this.length=1;for(var o=0,l=1;l<=67108863;l*=i)o++;o--,l=l/i|0;for(var b=e.length-s,p=b%o,u=Math.min(b,b-p)+s,r=0,c=s;c1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},a.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},a.prototype.inspect=function(){return(this.red?""};var y=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],g=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],M=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];a.prototype.toString=function(e,i){e=e||10,i=i|0||1;var s;if(e===16||e==="hex"){s="";for(var o=0,l=0,b=0;b>>24-o&16777215,o+=2,o>=26&&(o-=26,b--),l!==0||b!==this.length-1?s=y[6-u.length]+u+s:s=u+s}for(l!==0&&(s=l.toString(16)+s);s.length%i!==0;)s="0"+s;return this.negative!==0&&(s="-"+s),s}if(e===(e|0)&&e>=2&&e<=36){var r=g[e],c=M[e];s="";var I=this.clone();for(I.negative=0;!I.isZero();){var S=I.modn(c).toString(e);I=I.idivn(c),I.isZero()?s=S+s:s=y[r-S.length]+S+s}for(this.isZero()&&(s="0"+s);s.length%i!==0;)s="0"+s;return this.negative!==0&&(s="-"+s),s}h(!1,"Base should be between 2 and 36")},a.prototype.toNumber=function(){var e=this.words[0];return this.length===2?e+=this.words[1]*67108864:this.length===3&&this.words[2]===1?e+=4503599627370496+this.words[1]*67108864:this.length>2&&h(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-e:e},a.prototype.toJSON=function(){return this.toString(16)},a.prototype.toBuffer=function(e,i){return h(typeof m<"u"),this.toArrayLike(m,e,i)},a.prototype.toArray=function(e,i){return this.toArrayLike(Array,e,i)},a.prototype.toArrayLike=function(e,i,s){var o=this.byteLength(),l=s||Math.max(1,o);h(o<=l,"byte array longer than desired length"),h(l>0,"Requested array length <= 0"),this.strip();var b=i==="le",p=new e(l),u,r,c=this.clone();if(b){for(r=0;!c.isZero();r++)u=c.andln(255),c.iushrn(8),p[r]=u;for(;r=4096&&(s+=13,i>>>=13),i>=64&&(s+=7,i>>>=7),i>=8&&(s+=4,i>>>=4),i>=2&&(s+=2,i>>>=2),s+i},a.prototype._zeroBits=function(e){if(e===0)return 26;var i=e,s=0;return i&8191||(s+=13,i>>>=13),i&127||(s+=7,i>>>=7),i&15||(s+=4,i>>>=4),i&3||(s+=2,i>>>=2),i&1||s++,s},a.prototype.bitLength=function(){var e=this.words[this.length-1],i=this._countBits(e);return(this.length-1)*26+i};function w(v){for(var e=new Array(v.bitLength()),i=0;i>>o}return e}a.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,i=0;ie.length?this.clone().ior(e):e.clone().ior(this)},a.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},a.prototype.iuand=function(e){var i;this.length>e.length?i=e:i=this;for(var s=0;se.length?this.clone().iand(e):e.clone().iand(this)},a.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},a.prototype.iuxor=function(e){var i,s;this.length>e.length?(i=this,s=e):(i=e,s=this);for(var o=0;oe.length?this.clone().ixor(e):e.clone().ixor(this)},a.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},a.prototype.inotn=function(e){h(typeof e=="number"&&e>=0);var i=Math.ceil(e/26)|0,s=e%26;this._expand(i),s>0&&i--;for(var o=0;o0&&(this.words[o]=~this.words[o]&67108863>>26-s),this.strip()},a.prototype.notn=function(e){return this.clone().inotn(e)},a.prototype.setn=function(e,i){h(typeof e=="number"&&e>=0);var s=e/26|0,o=e%26;return this._expand(s+1),i?this.words[s]=this.words[s]|1<e.length?(s=this,o=e):(s=e,o=this);for(var l=0,b=0;b>>26;for(;l!==0&&b>>26;if(this.length=s.length,l!==0)this.words[this.length]=l,this.length++;else if(s!==this)for(;be.length?this.clone().iadd(e):e.clone().iadd(this)},a.prototype.isub=function(e){if(e.negative!==0){e.negative=0;var i=this.iadd(e);return e.negative=1,i._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var s=this.cmp(e);if(s===0)return this.negative=0,this.length=1,this.words[0]=0,this;var o,l;s>0?(o=this,l=e):(o=e,l=this);for(var b=0,p=0;p>26,this.words[p]=i&67108863;for(;b!==0&&p>26,this.words[p]=i&67108863;if(b===0&&p>>26,I=u&67108863,S=Math.min(r,e.length-1),L=Math.max(0,r-v.length+1);L<=S;L++){var B=r-L|0;o=v.words[B]|0,l=e.words[L]|0,b=o*l+I,c+=b/67108864|0,I=b&67108863}i.words[r]=I|0,u=c|0}return u!==0?i.words[r]=u|0:i.length--,i.strip()}var P=function(e,i,s){var o=e.words,l=i.words,b=s.words,p=0,u,r,c,I=o[0]|0,S=I&8191,L=I>>>13,B=o[1]|0,z=B&8191,V=B>>>13,Ce=o[2]|0,Y=Ce&8191,$=Ce>>>13,nr=o[3]|0,U=nr&8191,O=nr>>>13,hr=o[4]|0,F=hr&8191,K=hr>>>13,sr=o[5]|0,H=sr&8191,G=sr>>>13,dr=o[6]|0,Z=dr&8191,W=dr>>>13,or=o[7]|0,J=or&8191,X=or>>>13,ur=o[8]|0,Q=ur&8191,j=ur>>>13,cr=o[9]|0,ee=cr&8191,te=cr>>>13,lr=l[0]|0,re=lr&8191,fe=lr>>>13,vr=l[1]|0,ie=vr&8191,ae=vr>>>13,br=l[2]|0,ne=br&8191,he=br>>>13,pr=l[3]|0,se=pr&8191,de=pr>>>13,xr=l[4]|0,oe=xr&8191,ue=xr>>>13,mr=l[5]|0,ce=mr&8191,le=mr>>>13,gr=l[6]|0,ve=gr&8191,be=gr>>>13,_r=l[7]|0,pe=_r&8191,xe=_r>>>13,yr=l[8]|0,me=yr&8191,ge=yr>>>13,Mr=l[9]|0,_e=Mr&8191,ye=Mr>>>13;s.negative=e.negative^i.negative,s.length=19,u=Math.imul(S,re),r=Math.imul(S,fe),r=r+Math.imul(L,re)|0,c=Math.imul(L,fe);var yt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(yt>>>26)|0,yt&=67108863,u=Math.imul(z,re),r=Math.imul(z,fe),r=r+Math.imul(V,re)|0,c=Math.imul(V,fe),u=u+Math.imul(S,ie)|0,r=r+Math.imul(S,ae)|0,r=r+Math.imul(L,ie)|0,c=c+Math.imul(L,ae)|0;var Mt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,u=Math.imul(Y,re),r=Math.imul(Y,fe),r=r+Math.imul($,re)|0,c=Math.imul($,fe),u=u+Math.imul(z,ie)|0,r=r+Math.imul(z,ae)|0,r=r+Math.imul(V,ie)|0,c=c+Math.imul(V,ae)|0,u=u+Math.imul(S,ne)|0,r=r+Math.imul(S,he)|0,r=r+Math.imul(L,ne)|0,c=c+Math.imul(L,he)|0;var wt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(wt>>>26)|0,wt&=67108863,u=Math.imul(U,re),r=Math.imul(U,fe),r=r+Math.imul(O,re)|0,c=Math.imul(O,fe),u=u+Math.imul(Y,ie)|0,r=r+Math.imul(Y,ae)|0,r=r+Math.imul($,ie)|0,c=c+Math.imul($,ae)|0,u=u+Math.imul(z,ne)|0,r=r+Math.imul(z,he)|0,r=r+Math.imul(V,ne)|0,c=c+Math.imul(V,he)|0,u=u+Math.imul(S,se)|0,r=r+Math.imul(S,de)|0,r=r+Math.imul(L,se)|0,c=c+Math.imul(L,de)|0;var At=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(At>>>26)|0,At&=67108863,u=Math.imul(F,re),r=Math.imul(F,fe),r=r+Math.imul(K,re)|0,c=Math.imul(K,fe),u=u+Math.imul(U,ie)|0,r=r+Math.imul(U,ae)|0,r=r+Math.imul(O,ie)|0,c=c+Math.imul(O,ae)|0,u=u+Math.imul(Y,ne)|0,r=r+Math.imul(Y,he)|0,r=r+Math.imul($,ne)|0,c=c+Math.imul($,he)|0,u=u+Math.imul(z,se)|0,r=r+Math.imul(z,de)|0,r=r+Math.imul(V,se)|0,c=c+Math.imul(V,de)|0,u=u+Math.imul(S,oe)|0,r=r+Math.imul(S,ue)|0,r=r+Math.imul(L,oe)|0,c=c+Math.imul(L,ue)|0;var Et=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Et>>>26)|0,Et&=67108863,u=Math.imul(H,re),r=Math.imul(H,fe),r=r+Math.imul(G,re)|0,c=Math.imul(G,fe),u=u+Math.imul(F,ie)|0,r=r+Math.imul(F,ae)|0,r=r+Math.imul(K,ie)|0,c=c+Math.imul(K,ae)|0,u=u+Math.imul(U,ne)|0,r=r+Math.imul(U,he)|0,r=r+Math.imul(O,ne)|0,c=c+Math.imul(O,he)|0,u=u+Math.imul(Y,se)|0,r=r+Math.imul(Y,de)|0,r=r+Math.imul($,se)|0,c=c+Math.imul($,de)|0,u=u+Math.imul(z,oe)|0,r=r+Math.imul(z,ue)|0,r=r+Math.imul(V,oe)|0,c=c+Math.imul(V,ue)|0,u=u+Math.imul(S,ce)|0,r=r+Math.imul(S,le)|0,r=r+Math.imul(L,ce)|0,c=c+Math.imul(L,le)|0;var It=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(It>>>26)|0,It&=67108863,u=Math.imul(Z,re),r=Math.imul(Z,fe),r=r+Math.imul(W,re)|0,c=Math.imul(W,fe),u=u+Math.imul(H,ie)|0,r=r+Math.imul(H,ae)|0,r=r+Math.imul(G,ie)|0,c=c+Math.imul(G,ae)|0,u=u+Math.imul(F,ne)|0,r=r+Math.imul(F,he)|0,r=r+Math.imul(K,ne)|0,c=c+Math.imul(K,he)|0,u=u+Math.imul(U,se)|0,r=r+Math.imul(U,de)|0,r=r+Math.imul(O,se)|0,c=c+Math.imul(O,de)|0,u=u+Math.imul(Y,oe)|0,r=r+Math.imul(Y,ue)|0,r=r+Math.imul($,oe)|0,c=c+Math.imul($,ue)|0,u=u+Math.imul(z,ce)|0,r=r+Math.imul(z,le)|0,r=r+Math.imul(V,ce)|0,c=c+Math.imul(V,le)|0,u=u+Math.imul(S,ve)|0,r=r+Math.imul(S,be)|0,r=r+Math.imul(L,ve)|0,c=c+Math.imul(L,be)|0;var St=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(St>>>26)|0,St&=67108863,u=Math.imul(J,re),r=Math.imul(J,fe),r=r+Math.imul(X,re)|0,c=Math.imul(X,fe),u=u+Math.imul(Z,ie)|0,r=r+Math.imul(Z,ae)|0,r=r+Math.imul(W,ie)|0,c=c+Math.imul(W,ae)|0,u=u+Math.imul(H,ne)|0,r=r+Math.imul(H,he)|0,r=r+Math.imul(G,ne)|0,c=c+Math.imul(G,he)|0,u=u+Math.imul(F,se)|0,r=r+Math.imul(F,de)|0,r=r+Math.imul(K,se)|0,c=c+Math.imul(K,de)|0,u=u+Math.imul(U,oe)|0,r=r+Math.imul(U,ue)|0,r=r+Math.imul(O,oe)|0,c=c+Math.imul(O,ue)|0,u=u+Math.imul(Y,ce)|0,r=r+Math.imul(Y,le)|0,r=r+Math.imul($,ce)|0,c=c+Math.imul($,le)|0,u=u+Math.imul(z,ve)|0,r=r+Math.imul(z,be)|0,r=r+Math.imul(V,ve)|0,c=c+Math.imul(V,be)|0,u=u+Math.imul(S,pe)|0,r=r+Math.imul(S,xe)|0,r=r+Math.imul(L,pe)|0,c=c+Math.imul(L,xe)|0;var Lt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,u=Math.imul(Q,re),r=Math.imul(Q,fe),r=r+Math.imul(j,re)|0,c=Math.imul(j,fe),u=u+Math.imul(J,ie)|0,r=r+Math.imul(J,ae)|0,r=r+Math.imul(X,ie)|0,c=c+Math.imul(X,ae)|0,u=u+Math.imul(Z,ne)|0,r=r+Math.imul(Z,he)|0,r=r+Math.imul(W,ne)|0,c=c+Math.imul(W,he)|0,u=u+Math.imul(H,se)|0,r=r+Math.imul(H,de)|0,r=r+Math.imul(G,se)|0,c=c+Math.imul(G,de)|0,u=u+Math.imul(F,oe)|0,r=r+Math.imul(F,ue)|0,r=r+Math.imul(K,oe)|0,c=c+Math.imul(K,ue)|0,u=u+Math.imul(U,ce)|0,r=r+Math.imul(U,le)|0,r=r+Math.imul(O,ce)|0,c=c+Math.imul(O,le)|0,u=u+Math.imul(Y,ve)|0,r=r+Math.imul(Y,be)|0,r=r+Math.imul($,ve)|0,c=c+Math.imul($,be)|0,u=u+Math.imul(z,pe)|0,r=r+Math.imul(z,xe)|0,r=r+Math.imul(V,pe)|0,c=c+Math.imul(V,xe)|0,u=u+Math.imul(S,me)|0,r=r+Math.imul(S,ge)|0,r=r+Math.imul(L,me)|0,c=c+Math.imul(L,ge)|0;var Pt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,u=Math.imul(ee,re),r=Math.imul(ee,fe),r=r+Math.imul(te,re)|0,c=Math.imul(te,fe),u=u+Math.imul(Q,ie)|0,r=r+Math.imul(Q,ae)|0,r=r+Math.imul(j,ie)|0,c=c+Math.imul(j,ae)|0,u=u+Math.imul(J,ne)|0,r=r+Math.imul(J,he)|0,r=r+Math.imul(X,ne)|0,c=c+Math.imul(X,he)|0,u=u+Math.imul(Z,se)|0,r=r+Math.imul(Z,de)|0,r=r+Math.imul(W,se)|0,c=c+Math.imul(W,de)|0,u=u+Math.imul(H,oe)|0,r=r+Math.imul(H,ue)|0,r=r+Math.imul(G,oe)|0,c=c+Math.imul(G,ue)|0,u=u+Math.imul(F,ce)|0,r=r+Math.imul(F,le)|0,r=r+Math.imul(K,ce)|0,c=c+Math.imul(K,le)|0,u=u+Math.imul(U,ve)|0,r=r+Math.imul(U,be)|0,r=r+Math.imul(O,ve)|0,c=c+Math.imul(O,be)|0,u=u+Math.imul(Y,pe)|0,r=r+Math.imul(Y,xe)|0,r=r+Math.imul($,pe)|0,c=c+Math.imul($,xe)|0,u=u+Math.imul(z,me)|0,r=r+Math.imul(z,ge)|0,r=r+Math.imul(V,me)|0,c=c+Math.imul(V,ge)|0,u=u+Math.imul(S,_e)|0,r=r+Math.imul(S,ye)|0,r=r+Math.imul(L,_e)|0,c=c+Math.imul(L,ye)|0;var Bt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,u=Math.imul(ee,ie),r=Math.imul(ee,ae),r=r+Math.imul(te,ie)|0,c=Math.imul(te,ae),u=u+Math.imul(Q,ne)|0,r=r+Math.imul(Q,he)|0,r=r+Math.imul(j,ne)|0,c=c+Math.imul(j,he)|0,u=u+Math.imul(J,se)|0,r=r+Math.imul(J,de)|0,r=r+Math.imul(X,se)|0,c=c+Math.imul(X,de)|0,u=u+Math.imul(Z,oe)|0,r=r+Math.imul(Z,ue)|0,r=r+Math.imul(W,oe)|0,c=c+Math.imul(W,ue)|0,u=u+Math.imul(H,ce)|0,r=r+Math.imul(H,le)|0,r=r+Math.imul(G,ce)|0,c=c+Math.imul(G,le)|0,u=u+Math.imul(F,ve)|0,r=r+Math.imul(F,be)|0,r=r+Math.imul(K,ve)|0,c=c+Math.imul(K,be)|0,u=u+Math.imul(U,pe)|0,r=r+Math.imul(U,xe)|0,r=r+Math.imul(O,pe)|0,c=c+Math.imul(O,xe)|0,u=u+Math.imul(Y,me)|0,r=r+Math.imul(Y,ge)|0,r=r+Math.imul($,me)|0,c=c+Math.imul($,ge)|0,u=u+Math.imul(z,_e)|0,r=r+Math.imul(z,ye)|0,r=r+Math.imul(V,_e)|0,c=c+Math.imul(V,ye)|0;var Rt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,u=Math.imul(ee,ne),r=Math.imul(ee,he),r=r+Math.imul(te,ne)|0,c=Math.imul(te,he),u=u+Math.imul(Q,se)|0,r=r+Math.imul(Q,de)|0,r=r+Math.imul(j,se)|0,c=c+Math.imul(j,de)|0,u=u+Math.imul(J,oe)|0,r=r+Math.imul(J,ue)|0,r=r+Math.imul(X,oe)|0,c=c+Math.imul(X,ue)|0,u=u+Math.imul(Z,ce)|0,r=r+Math.imul(Z,le)|0,r=r+Math.imul(W,ce)|0,c=c+Math.imul(W,le)|0,u=u+Math.imul(H,ve)|0,r=r+Math.imul(H,be)|0,r=r+Math.imul(G,ve)|0,c=c+Math.imul(G,be)|0,u=u+Math.imul(F,pe)|0,r=r+Math.imul(F,xe)|0,r=r+Math.imul(K,pe)|0,c=c+Math.imul(K,xe)|0,u=u+Math.imul(U,me)|0,r=r+Math.imul(U,ge)|0,r=r+Math.imul(O,me)|0,c=c+Math.imul(O,ge)|0,u=u+Math.imul(Y,_e)|0,r=r+Math.imul(Y,ye)|0,r=r+Math.imul($,_e)|0,c=c+Math.imul($,ye)|0;var Nt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,u=Math.imul(ee,se),r=Math.imul(ee,de),r=r+Math.imul(te,se)|0,c=Math.imul(te,de),u=u+Math.imul(Q,oe)|0,r=r+Math.imul(Q,ue)|0,r=r+Math.imul(j,oe)|0,c=c+Math.imul(j,ue)|0,u=u+Math.imul(J,ce)|0,r=r+Math.imul(J,le)|0,r=r+Math.imul(X,ce)|0,c=c+Math.imul(X,le)|0,u=u+Math.imul(Z,ve)|0,r=r+Math.imul(Z,be)|0,r=r+Math.imul(W,ve)|0,c=c+Math.imul(W,be)|0,u=u+Math.imul(H,pe)|0,r=r+Math.imul(H,xe)|0,r=r+Math.imul(G,pe)|0,c=c+Math.imul(G,xe)|0,u=u+Math.imul(F,me)|0,r=r+Math.imul(F,ge)|0,r=r+Math.imul(K,me)|0,c=c+Math.imul(K,ge)|0,u=u+Math.imul(U,_e)|0,r=r+Math.imul(U,ye)|0,r=r+Math.imul(O,_e)|0,c=c+Math.imul(O,ye)|0;var Tt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,u=Math.imul(ee,oe),r=Math.imul(ee,ue),r=r+Math.imul(te,oe)|0,c=Math.imul(te,ue),u=u+Math.imul(Q,ce)|0,r=r+Math.imul(Q,le)|0,r=r+Math.imul(j,ce)|0,c=c+Math.imul(j,le)|0,u=u+Math.imul(J,ve)|0,r=r+Math.imul(J,be)|0,r=r+Math.imul(X,ve)|0,c=c+Math.imul(X,be)|0,u=u+Math.imul(Z,pe)|0,r=r+Math.imul(Z,xe)|0,r=r+Math.imul(W,pe)|0,c=c+Math.imul(W,xe)|0,u=u+Math.imul(H,me)|0,r=r+Math.imul(H,ge)|0,r=r+Math.imul(G,me)|0,c=c+Math.imul(G,ge)|0,u=u+Math.imul(F,_e)|0,r=r+Math.imul(F,ye)|0,r=r+Math.imul(K,_e)|0,c=c+Math.imul(K,ye)|0;var Ct=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,u=Math.imul(ee,ce),r=Math.imul(ee,le),r=r+Math.imul(te,ce)|0,c=Math.imul(te,le),u=u+Math.imul(Q,ve)|0,r=r+Math.imul(Q,be)|0,r=r+Math.imul(j,ve)|0,c=c+Math.imul(j,be)|0,u=u+Math.imul(J,pe)|0,r=r+Math.imul(J,xe)|0,r=r+Math.imul(X,pe)|0,c=c+Math.imul(X,xe)|0,u=u+Math.imul(Z,me)|0,r=r+Math.imul(Z,ge)|0,r=r+Math.imul(W,me)|0,c=c+Math.imul(W,ge)|0,u=u+Math.imul(H,_e)|0,r=r+Math.imul(H,ye)|0,r=r+Math.imul(G,_e)|0,c=c+Math.imul(G,ye)|0;var Dt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Dt>>>26)|0,Dt&=67108863,u=Math.imul(ee,ve),r=Math.imul(ee,be),r=r+Math.imul(te,ve)|0,c=Math.imul(te,be),u=u+Math.imul(Q,pe)|0,r=r+Math.imul(Q,xe)|0,r=r+Math.imul(j,pe)|0,c=c+Math.imul(j,xe)|0,u=u+Math.imul(J,me)|0,r=r+Math.imul(J,ge)|0,r=r+Math.imul(X,me)|0,c=c+Math.imul(X,ge)|0,u=u+Math.imul(Z,_e)|0,r=r+Math.imul(Z,ye)|0,r=r+Math.imul(W,_e)|0,c=c+Math.imul(W,ye)|0;var zt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(zt>>>26)|0,zt&=67108863,u=Math.imul(ee,pe),r=Math.imul(ee,xe),r=r+Math.imul(te,pe)|0,c=Math.imul(te,xe),u=u+Math.imul(Q,me)|0,r=r+Math.imul(Q,ge)|0,r=r+Math.imul(j,me)|0,c=c+Math.imul(j,ge)|0,u=u+Math.imul(J,_e)|0,r=r+Math.imul(J,ye)|0,r=r+Math.imul(X,_e)|0,c=c+Math.imul(X,ye)|0;var qt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(qt>>>26)|0,qt&=67108863,u=Math.imul(ee,me),r=Math.imul(ee,ge),r=r+Math.imul(te,me)|0,c=Math.imul(te,ge),u=u+Math.imul(Q,_e)|0,r=r+Math.imul(Q,ye)|0,r=r+Math.imul(j,_e)|0,c=c+Math.imul(j,ye)|0;var Vt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Vt>>>26)|0,Vt&=67108863,u=Math.imul(ee,_e),r=Math.imul(ee,ye),r=r+Math.imul(te,_e)|0,c=Math.imul(te,ye);var Yt=(p+u|0)+((r&8191)<<13)|0;return p=(c+(r>>>13)|0)+(Yt>>>26)|0,Yt&=67108863,b[0]=yt,b[1]=Mt,b[2]=wt,b[3]=At,b[4]=Et,b[5]=It,b[6]=St,b[7]=Lt,b[8]=Pt,b[9]=Bt,b[10]=Rt,b[11]=Nt,b[12]=Tt,b[13]=Ct,b[14]=Dt,b[15]=zt,b[16]=qt,b[17]=Vt,b[18]=Yt,p!==0&&(b[19]=p,s.length++),s};Math.imul||(P=E);function N(v,e,i){i.negative=e.negative^v.negative,i.length=v.length+e.length;for(var s=0,o=0,l=0;l>>26)|0,o+=b>>>26,b&=67108863}i.words[l]=p,s=b,b=o}return s!==0?i.words[l]=s:i.length--,i.strip()}function R(v,e,i){var s=new D;return s.mulp(v,e,i)}a.prototype.mulTo=function(e,i){var s,o=this.length+e.length;return this.length===10&&e.length===10?s=P(this,e,i):o<63?s=E(this,e,i):o<1024?s=N(this,e,i):s=R(this,e,i),s};function D(v,e){this.x=v,this.y=e}D.prototype.makeRBT=function(e){for(var i=new Array(e),s=a.prototype._countBits(e)-1,o=0;o>=1;return o},D.prototype.permute=function(e,i,s,o,l,b){for(var p=0;p>>1)l++;return 1<>>13,s[2*b+1]=l&8191,l=l>>>13;for(b=2*i;b>=26,i+=o/67108864|0,i+=l>>>26,this.words[s]=l&67108863}return i!==0&&(this.words[s]=i,this.length++),this.length=e===0?1:this.length,this},a.prototype.muln=function(e){return this.clone().imuln(e)},a.prototype.sqr=function(){return this.mul(this)},a.prototype.isqr=function(){return this.imul(this.clone())},a.prototype.pow=function(e){var i=w(e);if(i.length===0)return new a(1);for(var s=this,o=0;o=0);var i=e%26,s=(e-i)/26,o=67108863>>>26-i<<26-i,l;if(i!==0){var b=0;for(l=0;l>>26-i}b&&(this.words[l]=b,this.length++)}if(s!==0){for(l=this.length-1;l>=0;l--)this.words[l+s]=this.words[l];for(l=0;l=0);var o;i?o=(i-i%26)/26:o=0;var l=e%26,b=Math.min((e-l)/26,this.length),p=67108863^67108863>>>l<b)for(this.length-=b,r=0;r=0&&(c!==0||r>=o);r--){var I=this.words[r]|0;this.words[r]=c<<26-l|I>>>l,c=I&p}return u&&c!==0&&(u.words[u.length++]=c),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},a.prototype.ishrn=function(e,i,s){return h(this.negative===0),this.iushrn(e,i,s)},a.prototype.shln=function(e){return this.clone().ishln(e)},a.prototype.ushln=function(e){return this.clone().iushln(e)},a.prototype.shrn=function(e){return this.clone().ishrn(e)},a.prototype.ushrn=function(e){return this.clone().iushrn(e)},a.prototype.testn=function(e){h(typeof e=="number"&&e>=0);var i=e%26,s=(e-i)/26,o=1<=0);var i=e%26,s=(e-i)/26;if(h(this.negative===0,"imaskn works only with positive numbers"),this.length<=s)return this;if(i!==0&&s++,this.length=Math.min(s,this.length),i!==0){var o=67108863^67108863>>>i<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},a.prototype.isubn=function(e){if(h(typeof e=="number"),h(e<67108864),e<0)return this.iaddn(-e);if(this.negative!==0)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(u/67108864|0),this.words[l+s]=b&67108863}for(;l>26,this.words[l+s]=b&67108863;if(p===0)return this.strip();for(h(p===-1),p=0,l=0;l>26,this.words[l]=b&67108863;return this.negative=1,this.strip()},a.prototype._wordDiv=function(e,i){var s=this.length-e.length,o=this.clone(),l=e,b=l.words[l.length-1]|0,p=this._countBits(b);s=26-p,s!==0&&(l=l.ushln(s),o.iushln(s),b=l.words[l.length-1]|0);var u=o.length-l.length,r;if(i!=="mod"){r=new a(null),r.length=u+1,r.words=new Array(r.length);for(var c=0;c=0;S--){var L=(o.words[l.length+S]|0)*67108864+(o.words[l.length+S-1]|0);for(L=Math.min(L/b|0,67108863),o._ishlnsubmul(l,L,S);o.negative!==0;)L--,o.negative=0,o._ishlnsubmul(l,1,S),o.isZero()||(o.negative^=1);r&&(r.words[S]=L)}return r&&r.strip(),o.strip(),i!=="div"&&s!==0&&o.iushrn(s),{div:r||null,mod:o}},a.prototype.divmod=function(e,i,s){if(h(!e.isZero()),this.isZero())return{div:new a(0),mod:new a(0)};var o,l,b;return this.negative!==0&&e.negative===0?(b=this.neg().divmod(e,i),i!=="mod"&&(o=b.div.neg()),i!=="div"&&(l=b.mod.neg(),s&&l.negative!==0&&l.iadd(e)),{div:o,mod:l}):this.negative===0&&e.negative!==0?(b=this.divmod(e.neg(),i),i!=="mod"&&(o=b.div.neg()),{div:o,mod:b.mod}):this.negative&e.negative?(b=this.neg().divmod(e.neg(),i),i!=="div"&&(l=b.mod.neg(),s&&l.negative!==0&&l.isub(e)),{div:b.div,mod:l}):e.length>this.length||this.cmp(e)<0?{div:new a(0),mod:this}:e.length===1?i==="div"?{div:this.divn(e.words[0]),mod:null}:i==="mod"?{div:null,mod:new a(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new a(this.modn(e.words[0]))}:this._wordDiv(e,i)},a.prototype.div=function(e){return this.divmod(e,"div",!1).div},a.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},a.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},a.prototype.divRound=function(e){var i=this.divmod(e);if(i.mod.isZero())return i.div;var s=i.div.negative!==0?i.mod.isub(e):i.mod,o=e.ushrn(1),l=e.andln(1),b=s.cmp(o);return b<0||l===1&&b===0?i.div:i.div.negative!==0?i.div.isubn(1):i.div.iaddn(1)},a.prototype.modn=function(e){h(e<=67108863);for(var i=(1<<26)%e,s=0,o=this.length-1;o>=0;o--)s=(i*s+(this.words[o]|0))%e;return s},a.prototype.idivn=function(e){h(e<=67108863);for(var i=0,s=this.length-1;s>=0;s--){var o=(this.words[s]|0)+i*67108864;this.words[s]=o/e|0,i=o%e}return this.strip()},a.prototype.divn=function(e){return this.clone().idivn(e)},a.prototype.egcd=function(e){h(e.negative===0),h(!e.isZero());var i=this,s=e.clone();i.negative!==0?i=i.umod(e):i=i.clone();for(var o=new a(1),l=new a(0),b=new a(0),p=new a(1),u=0;i.isEven()&&s.isEven();)i.iushrn(1),s.iushrn(1),++u;for(var r=s.clone(),c=i.clone();!i.isZero();){for(var I=0,S=1;!(i.words[0]&S)&&I<26;++I,S<<=1);if(I>0)for(i.iushrn(I);I-- >0;)(o.isOdd()||l.isOdd())&&(o.iadd(r),l.isub(c)),o.iushrn(1),l.iushrn(1);for(var L=0,B=1;!(s.words[0]&B)&&L<26;++L,B<<=1);if(L>0)for(s.iushrn(L);L-- >0;)(b.isOdd()||p.isOdd())&&(b.iadd(r),p.isub(c)),b.iushrn(1),p.iushrn(1);i.cmp(s)>=0?(i.isub(s),o.isub(b),l.isub(p)):(s.isub(i),b.isub(o),p.isub(l))}return{a:b,b:p,gcd:s.iushln(u)}},a.prototype._invmp=function(e){h(e.negative===0),h(!e.isZero());var i=this,s=e.clone();i.negative!==0?i=i.umod(e):i=i.clone();for(var o=new a(1),l=new a(0),b=s.clone();i.cmpn(1)>0&&s.cmpn(1)>0;){for(var p=0,u=1;!(i.words[0]&u)&&p<26;++p,u<<=1);if(p>0)for(i.iushrn(p);p-- >0;)o.isOdd()&&o.iadd(b),o.iushrn(1);for(var r=0,c=1;!(s.words[0]&c)&&r<26;++r,c<<=1);if(r>0)for(s.iushrn(r);r-- >0;)l.isOdd()&&l.iadd(b),l.iushrn(1);i.cmp(s)>=0?(i.isub(s),o.isub(l)):(s.isub(i),l.isub(o))}var I;return i.cmpn(1)===0?I=o:I=l,I.cmpn(0)<0&&I.iadd(e),I},a.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var i=this.clone(),s=e.clone();i.negative=0,s.negative=0;for(var o=0;i.isEven()&&s.isEven();o++)i.iushrn(1),s.iushrn(1);do{for(;i.isEven();)i.iushrn(1);for(;s.isEven();)s.iushrn(1);var l=i.cmp(s);if(l<0){var b=i;i=s,s=b}else if(l===0||s.cmpn(1)===0)break;i.isub(s)}while(!0);return s.iushln(o)},a.prototype.invm=function(e){return this.egcd(e).a.umod(e)},a.prototype.isEven=function(){return(this.words[0]&1)===0},a.prototype.isOdd=function(){return(this.words[0]&1)===1},a.prototype.andln=function(e){return this.words[0]&e},a.prototype.bincn=function(e){h(typeof e=="number");var i=e%26,s=(e-i)/26,o=1<>>26,p&=67108863,this.words[b]=p}return l!==0&&(this.words[b]=l,this.length++),this},a.prototype.isZero=function(){return this.length===1&&this.words[0]===0},a.prototype.cmpn=function(e){var i=e<0;if(this.negative!==0&&!i)return-1;if(this.negative===0&&i)return 1;this.strip();var s;if(this.length>1)s=1;else{i&&(e=-e),h(e<=67108863,"Number is too big");var o=this.words[0]|0;s=o===e?0:oe.length)return 1;if(this.length=0;s--){var o=this.words[s]|0,l=e.words[s]|0;if(o!==l){ol&&(i=1);break}}return i},a.prototype.gtn=function(e){return this.cmpn(e)===1},a.prototype.gt=function(e){return this.cmp(e)===1},a.prototype.gten=function(e){return this.cmpn(e)>=0},a.prototype.gte=function(e){return this.cmp(e)>=0},a.prototype.ltn=function(e){return this.cmpn(e)===-1},a.prototype.lt=function(e){return this.cmp(e)===-1},a.prototype.lten=function(e){return this.cmpn(e)<=0},a.prototype.lte=function(e){return this.cmp(e)<=0},a.prototype.eqn=function(e){return this.cmpn(e)===0},a.prototype.eq=function(e){return this.cmp(e)===0},a.red=function(e){return new q(e)},a.prototype.toRed=function(e){return h(!this.red,"Already a number in reduction context"),h(this.negative===0,"red works only with positives"),e.convertTo(this)._forceRed(e)},a.prototype.fromRed=function(){return h(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},a.prototype._forceRed=function(e){return this.red=e,this},a.prototype.forceRed=function(e){return h(!this.red,"Already a number in reduction context"),this._forceRed(e)},a.prototype.redAdd=function(e){return h(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},a.prototype.redIAdd=function(e){return h(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},a.prototype.redSub=function(e){return h(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},a.prototype.redISub=function(e){return h(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},a.prototype.redShl=function(e){return h(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},a.prototype.redMul=function(e){return h(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},a.prototype.redIMul=function(e){return h(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},a.prototype.redSqr=function(){return h(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},a.prototype.redISqr=function(){return h(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},a.prototype.redSqrt=function(){return h(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},a.prototype.redInvm=function(){return h(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},a.prototype.redNeg=function(){return h(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},a.prototype.redPow=function(e){return h(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var Me={k256:null,p224:null,p192:null,p25519:null};function k(v,e){this.name=v,this.p=new a(e,16),this.n=this.p.bitLength(),this.k=new a(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}k.prototype._tmp=function(){var e=new a(null);return e.words=new Array(Math.ceil(this.n/13)),e},k.prototype.ireduce=function(e){var i=e,s;do this.split(i,this.tmp),i=this.imulK(i),i=i.iadd(this.tmp),s=i.bitLength();while(s>this.n);var o=s0?i.isub(this.p):i.strip!==void 0?i.strip():i._strip(),i},k.prototype.split=function(e,i){e.iushrn(this.n,0,i)},k.prototype.imulK=function(e){return e.imul(this.k)};function Ae(){k.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}d(Ae,k),Ae.prototype.split=function(e,i){for(var s=4194303,o=Math.min(e.length,9),l=0;l>>22,b=p}b>>>=22,e.words[l-10]=b,b===0&&e.length>10?e.length-=10:e.length-=9},Ae.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var i=0,s=0;s>>=26,e.words[s]=l,i=o}return i!==0&&(e.words[e.length++]=i),e},a._prime=function(e){if(Me[e])return Me[e];var i;if(e==="k256")i=new Ae;else if(e==="p224")i=new Ie;else if(e==="p192")i=new Ee;else if(e==="p25519")i=new Le;else throw new Error("Unknown prime "+e);return Me[e]=i,i};function q(v){if(typeof v=="string"){var e=a._prime(v);this.m=e.p,this.prime=e}else h(v.gtn(1),"modulus must be greater than 1"),this.m=v,this.prime=null}q.prototype._verify1=function(e){h(e.negative===0,"red works only with positives"),h(e.red,"red works only with red numbers")},q.prototype._verify2=function(e,i){h((e.negative|i.negative)===0,"red works only with positives"),h(e.red&&e.red===i.red,"red works only with red numbers")},q.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},q.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},q.prototype.add=function(e,i){this._verify2(e,i);var s=e.add(i);return s.cmp(this.m)>=0&&s.isub(this.m),s._forceRed(this)},q.prototype.iadd=function(e,i){this._verify2(e,i);var s=e.iadd(i);return s.cmp(this.m)>=0&&s.isub(this.m),s},q.prototype.sub=function(e,i){this._verify2(e,i);var s=e.sub(i);return s.cmpn(0)<0&&s.iadd(this.m),s._forceRed(this)},q.prototype.isub=function(e,i){this._verify2(e,i);var s=e.isub(i);return s.cmpn(0)<0&&s.iadd(this.m),s},q.prototype.shl=function(e,i){return this._verify1(e),this.imod(e.ushln(i))},q.prototype.imul=function(e,i){return this._verify2(e,i),this.imod(e.imul(i))},q.prototype.mul=function(e,i){return this._verify2(e,i),this.imod(e.mul(i))},q.prototype.isqr=function(e){return this.imul(e,e.clone())},q.prototype.sqr=function(e){return this.mul(e,e)},q.prototype.sqrt=function(e){if(e.isZero())return e.clone();var i=this.m.andln(3);if(h(i%2===1),i===3){var s=this.m.add(new a(1)).iushrn(2);return this.pow(e,s)}for(var o=this.m.subn(1),l=0;!o.isZero()&&o.andln(1)===0;)l++,o.iushrn(1);h(!o.isZero());var b=new a(1).toRed(this),p=b.redNeg(),u=this.m.subn(1).iushrn(1),r=this.m.bitLength();for(r=new a(2*r*r).toRed(this);this.pow(r,u).cmp(p)!==0;)r.redIAdd(p);for(var c=this.pow(r,o),I=this.pow(e,o.addn(1).iushrn(1)),S=this.pow(e,o),L=l;S.cmp(b)!==0;){for(var B=S,z=0;B.cmp(b)!==0;z++)B=B.redSqr();h(z=0;l--){for(var c=i.words[l],I=r-1;I>=0;I--){var S=c>>I&1;if(b!==o[0]&&(b=this.sqr(b)),S===0&&p===0){u=0;continue}p<<=1,p|=S,u++,!(u!==s&&(l!==0||I!==0))&&(b=this.mul(b,o[p]),u=0,p=0)}r=26}return b},q.prototype.convertTo=function(e){var i=e.umod(this.m);return i===e?i.clone():i},q.prototype.convertFrom=function(e){var i=e.clone();return i.red=null,i},a.mont=function(e){return new Be(e)};function Be(v){q.call(this,v),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new a(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}d(Be,q),Be.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},Be.prototype.convertFrom=function(e){var i=this.imod(e.mul(this.rinv));return i.red=null,i},Be.prototype.imul=function(e,i){if(e.isZero()||i.isZero())return e.words[0]=0,e.length=1,e;var s=e.imul(i),o=s.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),l=s.isub(o).iushrn(this.shift),b=l;return l.cmp(this.m)>=0?b=l.isub(this.m):l.cmpn(0)<0&&(b=l.iadd(this.m)),b._forceRed(this)},Be.prototype.mul=function(e,i){if(e.isZero()||i.isZero())return new a(0)._forceRed(this);var s=e.mul(i),o=s.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),l=s.isub(o).iushrn(this.shift),b=l;return l.cmp(this.m)>=0?b=l.isub(this.m):l.cmpn(0)<0&&(b=l.iadd(this.m)),b._forceRed(this)},Be.prototype.invm=function(e){var i=this.imod(e._invmp(this.m).mul(this.r2));return i._forceRed(this)}})(f,af)})(P0);var lt=P0.exports,Kt=vf;function vf(f,t){if(!f)throw new Error(t||"Assertion failed")}vf.equal=function(t,n,h){if(t!=n)throw new Error(h||"Assertion failed: "+t+" != "+n)};var B0={};(function(f){var t=f;function n(a,m){if(Array.isArray(a))return a.slice();if(!a)return[];var x=[];if(typeof a!="string"){for(var _=0;_>8,g=A&255;y?x.push(y,g):x.push(g)}return x}t.toArray=n;function h(a){return a.length===1?"0"+a:a}t.zero2=h;function d(a){for(var m="",x=0;x(P>>1)-1?R=(P>>1)-D:R=D,N.isubn(R)):R=0,w[E]=R,N.iushrn(1)}return w}t.getNAF=a;function m(y,g){var M=[[],[]];y=y.clone(),g=g.clone();for(var w=0,E=0,P;y.cmpn(-w)>0||g.cmpn(-E)>0;){var N=y.andln(3)+w&3,R=g.andln(3)+E&3;N===3&&(N=-1),R===3&&(R=-1);var D;N&1?(P=y.andln(7)+w&7,(P===3||P===5)&&R===2?D=-N:D=N):D=0,M[0].push(D);var Me;R&1?(P=g.andln(7)+E&7,(P===3||P===5)&&N===2?Me=-R:Me=R):Me=0,M[1].push(Me),2*w===D+1&&(w=1-w),2*E===Me+1&&(E=1-E),y.iushrn(1),g.iushrn(1)}return M}t.getJSF=m;function x(y,g,M){var w="_"+g;y.prototype[g]=function(){return this[w]!==void 0?this[w]:this[w]=M.call(this)}}t.cachedProperty=x;function _(y){return typeof y=="string"?t.toArray(y,"hex"):y}t.parseBytes=_;function A(y){return new n(y,"hex","le")}t.intFromLE=A})(Oe);var R0={exports:{}},o0;R0.exports=function(t){return o0||(o0=new pt(null)),o0.generate(t)};function pt(f){this.rand=f}R0.exports.Rand=pt;pt.prototype.generate=function(t){return this._rand(t)};pt.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var n=new Uint8Array(t),h=0;h0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Jr=_t;_t.prototype.point=function(){throw new Error("Not implemented")};_t.prototype.validate=function(){throw new Error("Not implemented")};_t.prototype._fixedNafMul=function(t,n){Ur(t.precomputed);var h=t._getDoubles(),d=$r(n,1,this._bitLength),a=(1<=x;A--)_=(_<<1)+d[A];m.push(_)}for(var y=this.jpoint(null,null,null),g=this.jpoint(null,null,null),M=a;M>0;M--){for(x=0;x=0;_--){for(var A=0;_>=0&&m[_]===0;_--)A++;if(_>=0&&A++,x=x.dblp(A),_<0)break;var y=m[_];Ur(y!==0),t.type==="affine"?y>0?x=x.mixedAdd(a[y-1>>1]):x=x.mixedAdd(a[-y-1>>1].neg()):y>0?x=x.add(a[y-1>>1]):x=x.add(a[-y-1>>1].neg())}return t.type==="affine"?x.toP():x};_t.prototype._wnafMulAdd=function(t,n,h,d,a){var m=this._wnafT1,x=this._wnafT2,_=this._wnafT3,A=0,y,g,M;for(y=0;y=1;y-=2){var E=y-1,P=y;if(m[E]!==1||m[P]!==1){_[E]=$r(h[E],m[E],this._bitLength),_[P]=$r(h[P],m[P],this._bitLength),A=Math.max(_[E].length,A),A=Math.max(_[P].length,A);continue}var N=[n[E],null,null,n[P]];n[E].y.cmp(n[P].y)===0?(N[1]=n[E].add(n[P]),N[2]=n[E].toJ().mixedAdd(n[P].neg())):n[E].y.cmp(n[P].y.redNeg())===0?(N[1]=n[E].toJ().mixedAdd(n[P]),N[2]=n[E].add(n[P].neg())):(N[1]=n[E].toJ().mixedAdd(n[P]),N[2]=n[E].toJ().mixedAdd(n[P].neg()));var R=[-3,-1,-5,-7,0,7,5,1,3],D=Yi(h[E],h[P]);for(A=Math.max(D[0].length,A),_[E]=new Array(A),_[P]=new Array(A),g=0;g=0;y--){for(var Ee=0;y>=0;){var Le=!0;for(g=0;g=0&&Ee++,Ae=Ae.dblp(Ee),y<0)break;for(g=0;g0?M=x[g][q-1>>1]:q<0&&(M=x[g][-q-1>>1].neg()),M.type==="affine"?Ae=Ae.mixedAdd(M):Ae=Ae.add(M))}}for(y=0;y=Math.ceil((t.bitLength()+1)/n.step):!1};Ke.prototype._getDoubles=function(t,n){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var h=[this],d=this,a=0;a=0&&(w=A,E=y),g.negative&&(g=g.neg(),M=M.neg()),w.negative&&(w=w.neg(),E=E.neg()),[{a:g,b:M},{a:w,b:E}]};He.prototype._endoSplit=function(t){var n=this.endo.basis,h=n[0],d=n[1],a=d.b.mul(t).divRound(this.n),m=h.b.neg().mul(t).divRound(this.n),x=a.mul(h.a),_=m.mul(d.a),A=a.mul(h.b),y=m.mul(d.b),g=t.sub(x).sub(_),M=A.add(y).neg();return{k1:g,k2:M}};He.prototype.pointFromX=function(t,n){t=new Pe(t,16),t.red||(t=t.toRed(this.red));var h=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),d=h.redSqrt();if(d.redSqr().redSub(h).cmp(this.zero)!==0)throw new Error("invalid point");var a=d.fromRed().isOdd();return(n&&!a||!n&&a)&&(d=d.redNeg()),this.point(t,d)};He.prototype.validate=function(t){if(t.inf)return!0;var n=t.x,h=t.y,d=this.a.redMul(n),a=n.redSqr().redMul(n).redIAdd(d).redIAdd(this.b);return h.redSqr().redISub(a).cmpn(0)===0};He.prototype._endoWnafMulAdd=function(t,n,h){for(var d=this._endoWnafT1,a=this._endoWnafT2,m=0;m":""};Te.prototype.isInfinity=function(){return this.inf};Te.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(this.x.cmp(t.x)===0)return this.curve.point(null,null);var n=this.y.redSub(t.y);n.cmpn(0)!==0&&(n=n.redMul(this.x.redSub(t.x).redInvm()));var h=n.redSqr().redISub(this.x).redISub(t.x),d=n.redMul(this.x.redSub(h)).redISub(this.y);return this.curve.point(h,d)};Te.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(t.cmpn(0)===0)return this.curve.point(null,null);var n=this.curve.a,h=this.x.redSqr(),d=t.redInvm(),a=h.redAdd(h).redIAdd(h).redIAdd(n).redMul(d),m=a.redSqr().redISub(this.x.redAdd(this.x)),x=a.redMul(this.x.redSub(m)).redISub(this.y);return this.curve.point(m,x)};Te.prototype.getX=function(){return this.x.fromRed()};Te.prototype.getY=function(){return this.y.fromRed()};Te.prototype.mul=function(t){return t=new Pe(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)};Te.prototype.mulAdd=function(t,n,h){var d=[this,n],a=[t,h];return this.curve.endo?this.curve._endoWnafMulAdd(d,a):this.curve._wnafMulAdd(1,d,a,2)};Te.prototype.jmulAdd=function(t,n,h){var d=[this,n],a=[t,h];return this.curve.endo?this.curve._endoWnafMulAdd(d,a,!0):this.curve._wnafMulAdd(1,d,a,2,!0)};Te.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||this.x.cmp(t.x)===0&&this.y.cmp(t.y)===0)};Te.prototype.neg=function(t){if(this.inf)return this;var n=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var h=this.precomputed,d=function(a){return a.neg()};n.precomputed={naf:h.naf&&{wnd:h.naf.wnd,points:h.naf.points.map(d)},doubles:h.doubles&&{step:h.doubles.step,points:h.doubles.points.map(d)}}}return n};Te.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var t=this.curve.jpoint(this.x,this.y,this.curve.one);return t};function De(f,t,n,h){jt.BasePoint.call(this,f,"jacobian"),t===null&&n===null&&h===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new Pe(0)):(this.x=new Pe(t,16),this.y=new Pe(n,16),this.z=new Pe(h,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}T0(De,jt.BasePoint);He.prototype.jpoint=function(t,n,h){return new De(this,t,n,h)};De.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),n=t.redSqr(),h=this.x.redMul(n),d=this.y.redMul(n).redMul(t);return this.curve.point(h,d)};De.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)};De.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var n=t.z.redSqr(),h=this.z.redSqr(),d=this.x.redMul(n),a=t.x.redMul(h),m=this.y.redMul(n.redMul(t.z)),x=t.y.redMul(h.redMul(this.z)),_=d.redSub(a),A=m.redSub(x);if(_.cmpn(0)===0)return A.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var y=_.redSqr(),g=y.redMul(_),M=d.redMul(y),w=A.redSqr().redIAdd(g).redISub(M).redISub(M),E=A.redMul(M.redISub(w)).redISub(m.redMul(g)),P=this.z.redMul(t.z).redMul(_);return this.curve.jpoint(w,E,P)};De.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var n=this.z.redSqr(),h=this.x,d=t.x.redMul(n),a=this.y,m=t.y.redMul(n).redMul(this.z),x=h.redSub(d),_=a.redSub(m);if(x.cmpn(0)===0)return _.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var A=x.redSqr(),y=A.redMul(x),g=h.redMul(A),M=_.redSqr().redIAdd(y).redISub(g).redISub(g),w=_.redMul(g.redISub(M)).redISub(a.redMul(y)),E=this.z.redMul(x);return this.curve.jpoint(M,w,E)};De.prototype.dblp=function(t){if(t===0)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var n;if(this.curve.zeroA||this.curve.threeA){var h=this;for(n=0;n=0)return!1;if(h.redIAdd(a),this.x.cmp(h)===0)return!0}};De.prototype.inspect=function(){return this.isInfinity()?"":""};De.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var Gt=lt,pf=ct,Xr=Jr,Oi=Oe;function er(f){Xr.call(this,"mont",f),this.a=new Gt(f.a,16).toRed(this.red),this.b=new Gt(f.b,16).toRed(this.red),this.i4=new Gt(4).toRed(this.red).redInvm(),this.two=new Gt(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}pf(er,Xr);var Fi=er;er.prototype.validate=function(t){var n=t.normalize().x,h=n.redSqr(),d=h.redMul(n).redAdd(h.redMul(this.a)).redAdd(n),a=d.redSqrt();return a.redSqr().cmp(d)===0};function Ne(f,t,n){Xr.BasePoint.call(this,f,"projective"),t===null&&n===null?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new Gt(t,16),this.z=new Gt(n,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}pf(Ne,Xr.BasePoint);er.prototype.decodePoint=function(t,n){return this.point(Oi.toArray(t,n),1)};er.prototype.point=function(t,n){return new Ne(this,t,n)};er.prototype.pointFromJSON=function(t){return Ne.fromJSON(this,t)};Ne.prototype.precompute=function(){};Ne.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())};Ne.fromJSON=function(t,n){return new Ne(t,n[0],n[1]||t.one)};Ne.prototype.inspect=function(){return this.isInfinity()?"":""};Ne.prototype.isInfinity=function(){return this.z.cmpn(0)===0};Ne.prototype.dbl=function(){var t=this.x.redAdd(this.z),n=t.redSqr(),h=this.x.redSub(this.z),d=h.redSqr(),a=n.redSub(d),m=n.redMul(d),x=a.redMul(d.redAdd(this.curve.a24.redMul(a)));return this.curve.point(m,x)};Ne.prototype.add=function(){throw new Error("Not supported on Montgomery curve")};Ne.prototype.diffAdd=function(t,n){var h=this.x.redAdd(this.z),d=this.x.redSub(this.z),a=t.x.redAdd(t.z),m=t.x.redSub(t.z),x=m.redMul(h),_=a.redMul(d),A=n.z.redMul(x.redAdd(_).redSqr()),y=n.x.redMul(x.redISub(_).redSqr());return this.curve.point(A,y)};Ne.prototype.mul=function(t){for(var n=t.clone(),h=this,d=this.curve.point(null,null),a=this,m=[];n.cmpn(0)!==0;n.iushrn(1))m.push(n.andln(1));for(var x=m.length-1;x>=0;x--)m[x]===0?(h=h.diffAdd(d,a),d=d.dbl()):(d=h.diffAdd(d,a),h=h.dbl());return d};Ne.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")};Ne.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")};Ne.prototype.eq=function(t){return this.getX().cmp(t.getX())===0};Ne.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this};Ne.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var Ki=Oe,st=lt,xf=ct,Qr=Jr,Hi=Ki.assert;function nt(f){this.twisted=(f.a|0)!==1,this.mOneA=this.twisted&&(f.a|0)===-1,this.extended=this.mOneA,Qr.call(this,"edwards",f),this.a=new st(f.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new st(f.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new st(f.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Hi(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(f.c|0)===1}xf(nt,Qr);var Gi=nt;nt.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)};nt.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)};nt.prototype.jpoint=function(t,n,h,d){return this.point(t,n,h,d)};nt.prototype.pointFromX=function(t,n){t=new st(t,16),t.red||(t=t.toRed(this.red));var h=t.redSqr(),d=this.c2.redSub(this.a.redMul(h)),a=this.one.redSub(this.c2.redMul(this.d).redMul(h)),m=d.redMul(a.redInvm()),x=m.redSqrt();if(x.redSqr().redSub(m).cmp(this.zero)!==0)throw new Error("invalid point");var _=x.fromRed().isOdd();return(n&&!_||!n&&_)&&(x=x.redNeg()),this.point(t,x)};nt.prototype.pointFromY=function(t,n){t=new st(t,16),t.red||(t=t.toRed(this.red));var h=t.redSqr(),d=h.redSub(this.c2),a=h.redMul(this.d).redMul(this.c2).redSub(this.a),m=d.redMul(a.redInvm());if(m.cmp(this.zero)===0){if(n)throw new Error("invalid point");return this.point(this.zero,t)}var x=m.redSqrt();if(x.redSqr().redSub(m).cmp(this.zero)!==0)throw new Error("invalid point");return x.fromRed().isOdd()!==n&&(x=x.redNeg()),this.point(x,t)};nt.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var n=t.x.redSqr(),h=t.y.redSqr(),d=n.redMul(this.a).redAdd(h),a=this.c2.redMul(this.one.redAdd(this.d.redMul(n).redMul(h)));return d.cmp(a)===0};function Se(f,t,n,h,d){Qr.BasePoint.call(this,f,"projective"),t===null&&n===null&&h===null?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new st(t,16),this.y=new st(n,16),this.z=h?new st(h,16):this.curve.one,this.t=d&&new st(d,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}xf(Se,Qr.BasePoint);nt.prototype.pointFromJSON=function(t){return Se.fromJSON(this,t)};nt.prototype.point=function(t,n,h,d){return new Se(this,t,n,h,d)};Se.fromJSON=function(t,n){return new Se(t,n[0],n[1],n[2])};Se.prototype.inspect=function(){return this.isInfinity()?"":""};Se.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)};Se.prototype._extDbl=function(){var t=this.x.redSqr(),n=this.y.redSqr(),h=this.z.redSqr();h=h.redIAdd(h);var d=this.curve._mulA(t),a=this.x.redAdd(this.y).redSqr().redISub(t).redISub(n),m=d.redAdd(n),x=m.redSub(h),_=d.redSub(n),A=a.redMul(x),y=m.redMul(_),g=a.redMul(_),M=x.redMul(m);return this.curve.point(A,y,M,g)};Se.prototype._projDbl=function(){var t=this.x.redAdd(this.y).redSqr(),n=this.x.redSqr(),h=this.y.redSqr(),d,a,m,x,_,A;if(this.curve.twisted){x=this.curve._mulA(n);var y=x.redAdd(h);this.zOne?(d=t.redSub(n).redSub(h).redMul(y.redSub(this.curve.two)),a=y.redMul(x.redSub(h)),m=y.redSqr().redSub(y).redSub(y)):(_=this.z.redSqr(),A=y.redSub(_).redISub(_),d=t.redSub(n).redISub(h).redMul(A),a=y.redMul(x.redSub(h)),m=y.redMul(A))}else x=n.redAdd(h),_=this.curve._mulC(this.z).redSqr(),A=x.redSub(_).redSub(_),d=this.curve._mulC(t.redISub(x)).redMul(A),a=this.curve._mulC(x).redMul(n.redISub(h)),m=x.redMul(A);return this.curve.point(d,a,m)};Se.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()};Se.prototype._extAdd=function(t){var n=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),h=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),d=this.t.redMul(this.curve.dd).redMul(t.t),a=this.z.redMul(t.z.redAdd(t.z)),m=h.redSub(n),x=a.redSub(d),_=a.redAdd(d),A=h.redAdd(n),y=m.redMul(x),g=_.redMul(A),M=m.redMul(A),w=x.redMul(_);return this.curve.point(y,g,w,M)};Se.prototype._projAdd=function(t){var n=this.z.redMul(t.z),h=n.redSqr(),d=this.x.redMul(t.x),a=this.y.redMul(t.y),m=this.curve.d.redMul(d).redMul(a),x=h.redSub(m),_=h.redAdd(m),A=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(d).redISub(a),y=n.redMul(x).redMul(A),g,M;return this.curve.twisted?(g=n.redMul(_).redMul(a.redSub(this.curve._mulA(d))),M=x.redMul(_)):(g=n.redMul(_).redMul(a.redSub(d)),M=this.curve._mulC(x).redMul(_)),this.curve.point(y,g,M)};Se.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)};Se.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)};Se.prototype.mulAdd=function(t,n,h){return this.curve._wnafMulAdd(1,[this,n],[t,h],2,!1)};Se.prototype.jmulAdd=function(t,n,h){return this.curve._wnafMulAdd(1,[this,n],[t,h],2,!0)};Se.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this};Se.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())};Se.prototype.getX=function(){return this.normalize(),this.x.fromRed()};Se.prototype.getY=function(){return this.normalize(),this.y.fromRed()};Se.prototype.eq=function(t){return this===t||this.getX().cmp(t.getX())===0&&this.getY().cmp(t.getY())===0};Se.prototype.eqXToP=function(t){var n=t.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(n)===0)return!0;for(var h=t.clone(),d=this.curve.redN.redMul(this.z);;){if(h.iadd(this.curve.n),h.cmp(this.curve.p)>=0)return!1;if(n.redIAdd(d),this.x.cmp(n)===0)return!0}};Se.prototype.toP=Se.prototype.normalize;Se.prototype.mixedAdd=Se.prototype.add;(function(f){var t=f;t.base=Jr,t.short=Ui,t.mont=Fi,t.edwards=Gi})(N0);var jr={},e0={},we={},Zi=Kt,Wi=ct;we.inherits=Wi;function Ji(f,t){return(f.charCodeAt(t)&64512)!==55296||t<0||t+1>=f.length?!1:(f.charCodeAt(t+1)&64512)===56320}function Xi(f,t){if(Array.isArray(f))return f.slice();if(!f)return[];var n=[];if(typeof f=="string")if(t){if(t==="hex")for(f=f.replace(/[^a-z0-9]+/ig,""),f.length%2!==0&&(f="0"+f),d=0;d>6|192,n[h++]=a&63|128):Ji(f,d)?(a=65536+((a&1023)<<10)+(f.charCodeAt(++d)&1023),n[h++]=a>>18|240,n[h++]=a>>12&63|128,n[h++]=a>>6&63|128,n[h++]=a&63|128):(n[h++]=a>>12|224,n[h++]=a>>6&63|128,n[h++]=a&63|128)}else for(d=0;d>>24|f>>>8&65280|f<<8&16711680|(f&255)<<24;return t>>>0}we.htonl=mf;function ji(f,t){for(var n="",h=0;h>>0}return a}we.join32=ea;function ta(f,t){for(var n=new Array(f.length*4),h=0,d=0;h>>24,n[d+1]=a>>>16&255,n[d+2]=a>>>8&255,n[d+3]=a&255):(n[d+3]=a>>>24,n[d+2]=a>>>16&255,n[d+1]=a>>>8&255,n[d]=a&255)}return n}we.split32=ta;function ra(f,t){return f>>>t|f<<32-t}we.rotr32=ra;function fa(f,t){return f<>>32-t}we.rotl32=fa;function ia(f,t){return f+t>>>0}we.sum32=ia;function aa(f,t,n){return f+t+n>>>0}we.sum32_3=aa;function na(f,t,n,h){return f+t+n+h>>>0}we.sum32_4=na;function ha(f,t,n,h,d){return f+t+n+h+d>>>0}we.sum32_5=ha;function sa(f,t,n,h){var d=f[t],a=f[t+1],m=h+a>>>0,x=(m>>0,f[t+1]=m}we.sum64=sa;function da(f,t,n,h){var d=t+h>>>0,a=(d>>0}we.sum64_hi=da;function oa(f,t,n,h){var d=t+h;return d>>>0}we.sum64_lo=oa;function ua(f,t,n,h,d,a,m,x){var _=0,A=t;A=A+h>>>0,_+=A>>0,_+=A>>0,_+=A>>0}we.sum64_4_hi=ua;function ca(f,t,n,h,d,a,m,x){var _=t+h+a+x;return _>>>0}we.sum64_4_lo=ca;function la(f,t,n,h,d,a,m,x,_,A){var y=0,g=t;g=g+h>>>0,y+=g>>0,y+=g>>0,y+=g>>0,y+=g>>0}we.sum64_5_hi=la;function va(f,t,n,h,d,a,m,x,_,A){var y=t+h+a+x+A;return y>>>0}we.sum64_5_lo=va;function ba(f,t,n){var h=t<<32-n|f>>>n;return h>>>0}we.rotr64_hi=ba;function pa(f,t,n){var h=f<<32-n|t>>>n;return h>>>0}we.rotr64_lo=pa;function xa(f,t,n){return f>>>n}we.shr64_hi=xa;function ma(f,t,n){var h=f<<32-n|t>>>n;return h>>>0}we.shr64_lo=ma;var tr={},F0=we,ga=Kt;function t0(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}tr.BlockHash=t0;t0.prototype.update=function(t,n){if(t=F0.toArray(t,n),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;var h=t.length%this._delta8;this.pending=t.slice(t.length-h,t.length),this.pending.length===0&&(this.pending=null),t=F0.join32(t,0,t.length-h,this.endian);for(var d=0;d>>24&255,d[a++]=t>>>16&255,d[a++]=t>>>8&255,d[a++]=t&255}else for(d[a++]=t&255,d[a++]=t>>>8&255,d[a++]=t>>>16&255,d[a++]=t>>>24&255,d[a++]=0,d[a++]=0,d[a++]=0,d[a++]=0,m=8;m>>3}ht.g0_256=Aa;function Ea(f){return et(f,17)^et(f,19)^f>>>10}ht.g1_256=Ea;var Wt=we,Ia=tr,Sa=ht,u0=Wt.rotl32,Pr=Wt.sum32,La=Wt.sum32_5,Pa=Sa.ft_1,Af=Ia.BlockHash,Ba=[1518500249,1859775393,2400959708,3395469782];function ft(){if(!(this instanceof ft))return new ft;Af.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Wt.inherits(ft,Af);var Ra=ft;ft.blockSize=512;ft.outSize=160;ft.hmacStrength=80;ft.padLength=64;ft.prototype._update=function(t,n){for(var h=this.W,d=0;d<16;d++)h[d]=t[n+d];for(;dthis.blockSize&&(t=new this.Hash().update(t).digest()),gn(t.length<=this.blockSize);for(var n=t.length;n=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,n,h)}var wn=mt;mt.prototype._init=function(t,n,h){var d=t.concat(n).concat(h);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var a=0;a=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(h||[])),this._reseed=1};mt.prototype.generate=function(t,n,h,d){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof n!="string"&&(d=h,h=n,n=null),h&&(h=Ut.toArray(h,d||"hex"),this._update(h));for(var a=[];a.length"};var Or=lt,C0=Oe,Sn=C0.assert;function r0(f,t){if(f instanceof r0)return f;this._importDER(f,t)||(Sn(f.r&&f.s,"Signature without r or s"),this.r=new Or(f.r,16),this.s=new Or(f.s,16),f.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=f.recoveryParam)}var Ln=r0;function Pn(){this.place=0}function b0(f,t){var n=f[t.place++];if(!(n&128))return n;var h=n&15;if(h===0||h>4||f[t.place]===0)return!1;for(var d=0,a=0,m=t.place;a>>=0;return d<=127?!1:(t.place=m,d)}function W0(f){for(var t=0,n=f.length-1;!f[t]&&!(f[t+1]&128)&&t>>3);for(f.push(n|128);--n;)f.push(t>>>(n<<3)&255);f.push(t)}r0.prototype.toDER=function(t){var n=this.r.toArray(),h=this.s.toArray();for(n[0]&128&&(n=[0].concat(n)),h[0]&128&&(h=[0].concat(h)),n=W0(n),h=W0(h);!h[0]&&!(h[1]&128);)h=h.slice(1);var d=[2];p0(d,n.length),d=d.concat(n),d.push(2),p0(d,h.length);var a=d.concat(h),m=[48];return p0(m,a.length),m=m.concat(a),C0.encode(m,t)};var Ze=lt,zf=wn,Bn=Oe,x0=jr,Rn=bf,$t=Bn.assert,D0=In,f0=Ln;function Fe(f){if(!(this instanceof Fe))return new Fe(f);typeof f=="string"&&($t(Object.prototype.hasOwnProperty.call(x0,f),"Unknown curve "+f),f=x0[f]),f instanceof x0.PresetCurve&&(f={curve:f}),this.curve=f.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=f.curve.g,this.g.precompute(f.curve.n.bitLength()+1),this.hash=f.hash||f.curve.hash}var Nn=Fe;Fe.prototype.keyPair=function(t){return new D0(this,t)};Fe.prototype.keyFromPrivate=function(t,n){return D0.fromPrivate(this,t,n)};Fe.prototype.keyFromPublic=function(t,n){return D0.fromPublic(this,t,n)};Fe.prototype.genKeyPair=function(t){t||(t={});for(var n=new zf({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Rn(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),h=this.n.byteLength(),d=this.n.sub(new Ze(2));;){var a=new Ze(n.generate(h));if(!(a.cmp(d)>0))return a.iaddn(1),this.keyFromPrivate(a)}};Fe.prototype._truncateToN=function(t,n,h){var d;if(Ze.isBN(t)||typeof t=="number")t=new Ze(t,16),d=t.byteLength();else if(typeof t=="object")d=t.length,t=new Ze(t,16);else{var a=t.toString();d=a.length+1>>>1,t=new Ze(a,16)}typeof h!="number"&&(h=d*8);var m=h-this.n.bitLength();return m>0&&(t=t.ushrn(m)),!n&&t.cmp(this.n)>=0?t.sub(this.n):t};Fe.prototype.sign=function(t,n,h,d){if(typeof h=="object"&&(d=h,h=null),d||(d={}),typeof t!="string"&&typeof t!="number"&&!Ze.isBN(t)){$t(typeof t=="object"&&t&&typeof t.length=="number","Expected message to be an array-like, a hex string, or a BN instance"),$t(t.length>>>0===t.length);for(var a=0;a=0)){var w=this.g.mul(M);if(!w.isInfinity()){var E=w.getX(),P=E.umod(this.n);if(P.cmpn(0)!==0){var N=M.invm(this.n).mul(P.mul(n.getPrivate()).iadd(t));if(N=N.umod(this.n),N.cmpn(0)!==0){var R=(w.getY().isOdd()?1:0)|(E.cmp(P)!==0?2:0);return d.canonical&&N.cmp(this.nh)>0&&(N=this.n.sub(N),R^=1),new f0({r:P,s:N,recoveryParam:R})}}}}}};Fe.prototype.verify=function(t,n,h,d,a){a||(a={}),t=this._truncateToN(t,!1,a.msgBitLength),h=this.keyFromPublic(h,d),n=new f0(n,"hex");var m=n.r,x=n.s;if(m.cmpn(1)<0||m.cmp(this.n)>=0||x.cmpn(1)<0||x.cmp(this.n)>=0)return!1;var _=x.invm(this.n),A=_.mul(t).umod(this.n),y=_.mul(m).umod(this.n),g;return this.curve._maxwellTrick?(g=this.g.jmulAdd(A,h.getPublic(),y),g.isInfinity()?!1:g.eqXToP(m)):(g=this.g.mulAdd(A,h.getPublic(),y),g.isInfinity()?!1:g.getX().umod(this.n).cmp(m)===0)};Fe.prototype.recoverPubKey=function(f,t,n,h){$t((3&n)===n,"The recovery param is more than two bits"),t=new f0(t,h);var d=this.n,a=new Ze(f),m=t.r,x=t.s,_=n&1,A=n>>1;if(m.cmp(this.curve.p.umod(this.curve.n))>=0&&A)throw new Error("Unable to find sencond key candinate");A?m=this.curve.pointFromX(m.add(this.curve.n),_):m=this.curve.pointFromX(m,_);var y=t.r.invm(d),g=d.sub(a).mul(y).umod(d),M=x.mul(y).umod(d);return this.g.mulAdd(g,m,M)};Fe.prototype.getKeyRecoveryParam=function(f,t,n,h){if(t=new f0(t,h),t.recoveryParam!==null)return t.recoveryParam;for(var d=0;d<4;d++){var a;try{a=this.recoverPubKey(f,t,d)}catch{continue}if(a.eq(n))return d}throw new Error("Unable to find valid recovery factor")};var Dr=Oe,qf=Dr.assert,J0=Dr.parseBytes,ir=Dr.cachedProperty;function Re(f,t){this.eddsa=f,this._secret=J0(t.secret),f.isPoint(t.pub)?this._pub=t.pub:this._pubBytes=J0(t.pub)}Re.fromPublic=function(t,n){return n instanceof Re?n:new Re(t,{pub:n})};Re.fromSecret=function(t,n){return n instanceof Re?n:new Re(t,{secret:n})};Re.prototype.secret=function(){return this._secret};ir(Re,"pubBytes",function(){return this.eddsa.encodePoint(this.pub())});ir(Re,"pub",function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())});ir(Re,"privBytes",function(){var t=this.eddsa,n=this.hash(),h=t.encodingLength-1,d=n.slice(0,t.encodingLength);return d[0]&=248,d[h]&=127,d[h]|=64,d});ir(Re,"priv",function(){return this.eddsa.decodeInt(this.privBytes())});ir(Re,"hash",function(){return this.eddsa.hash().update(this.secret()).digest()});ir(Re,"messagePrefix",function(){return this.hash().slice(this.eddsa.encodingLength)});Re.prototype.sign=function(t){return qf(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)};Re.prototype.verify=function(t,n){return this.eddsa.verify(t,n,this)};Re.prototype.getSecret=function(t){return qf(this._secret,"KeyPair is public only"),Dr.encode(this.secret(),t)};Re.prototype.getPublic=function(t){return Dr.encode(this.pubBytes(),t)};var Tn=Re,Cn=lt,i0=Oe,X0=i0.assert,a0=i0.cachedProperty,Dn=i0.parseBytes;function Ht(f,t){this.eddsa=f,typeof t!="object"&&(t=Dn(t)),Array.isArray(t)&&(X0(t.length===f.encodingLength*2,"Signature has invalid size"),t={R:t.slice(0,f.encodingLength),S:t.slice(f.encodingLength)}),X0(t.R&&t.S,"Signature without R or S"),f.isPoint(t.R)&&(this._R=t.R),t.S instanceof Cn&&(this._S=t.S),this._Rencoded=Array.isArray(t.R)?t.R:t.Rencoded,this._Sencoded=Array.isArray(t.S)?t.S:t.Sencoded}a0(Ht,"S",function(){return this.eddsa.decodeInt(this.Sencoded())});a0(Ht,"R",function(){return this.eddsa.decodePoint(this.Rencoded())});a0(Ht,"Rencoded",function(){return this.eddsa.encodePoint(this.R())});a0(Ht,"Sencoded",function(){return this.eddsa.encodeInt(this.S())});Ht.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())};Ht.prototype.toHex=function(){return i0.encode(this.toBytes(),"hex").toUpperCase()};var zn=Ht,qn=e0,Vn=jr,Qt=Oe,Yn=Qt.assert,Vf=Qt.parseBytes,Yf=Tn,Q0=zn;function Ue(f){if(Yn(f==="ed25519","only tested with ed25519 so far"),!(this instanceof Ue))return new Ue(f);f=Vn[f].curve,this.curve=f,this.g=f.g,this.g.precompute(f.n.bitLength()+1),this.pointClass=f.point().constructor,this.encodingLength=Math.ceil(f.n.bitLength()/8),this.hash=qn.sha512}var kn=Ue;Ue.prototype.sign=function(t,n){t=Vf(t);var h=this.keyFromSecret(n),d=this.hashInt(h.messagePrefix(),t),a=this.g.mul(d),m=this.encodePoint(a),x=this.hashInt(m,h.pubBytes(),t).mul(h.priv()),_=d.add(x).umod(this.curve.n);return this.makeSignature({R:a,S:_,Rencoded:m})};Ue.prototype.verify=function(t,n,h){if(t=Vf(t),n=this.makeSignature(n),n.S().gte(n.eddsa.curve.n)||n.S().isNeg())return!1;var d=this.keyFromPublic(h),a=this.hashInt(n.Rencoded(),d.pubBytes(),t),m=this.g.mul(n.S()),x=n.R().add(d.pub().mul(a));return x.eq(m)};Ue.prototype.hashInt=function(){for(var t=this.hash(),n=0;n=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,Me=new Uint8Array(D);N!==R;){for(var k=w[N],Ae=0,Ie=D-1;(k!==0||Ae>>0,Me[Ie]=k%m>>>0,k=k/m>>>0;if(k!==0)throw new Error("Non-zero carry");P=Ae,N++}for(var Ee=D-P;Ee!==D&&Me[Ee]===0;)Ee++;for(var Le=x.repeat(E);Ee>>0,D=new Uint8Array(R);E255)return;var k=t[Me];if(k===255)return;for(var Ae=0,Ie=R-1;(k!==0||Ae>>0,D[Ie]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");N=Ae,E++}for(var Ee=R-N;Ee!==R&&D[Ee]===0;)Ee++;var Le=qr.allocUnsafe(P+(R-Ee));Le.fill(0,0,P);for(var q=P;Ee!==R;)Le[q++]=D[Ee++];return Le}function M(w){var E=g(w);if(E)return E;throw new Error("Non-base"+m+" character")}return{encode:y,decodeUnsafe:g,decode:M}}var Un=$n,On=Un,Fn="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Kn=On(Fn),m0=Kn,Hn=ut.Buffer,Gn=function(f){function t(a){var m=f(a);return m0.encode(Hn.concat([a,m],a.length+4))}function n(a){var m=a.slice(0,-4),x=a.slice(-4),_=f(m);if(!(x[0]^_[0]|x[1]^_[1]|x[2]^_[2]|x[3]^_[3]))return m}function h(a){var m=m0.decodeUnsafe(a);if(m)return n(m)}function d(a){var m=m0.decode(a),x=n(m);if(!x)throw new Error("Invalid checksum");return x}return{encode:t,decode:d,decodeUnsafe:h}},j0=L0,Zn=Gn;function Wn(f){var t=j0("sha256").update(f).digest();return j0("sha256").update(t).digest()}var Jn=Zn(Wn),Fr="qpzry9x8gf2tvdw0s3jn54khce6mua7l",E0={};for(var Vr=0;Vr>25;return(f&33554431)<<5^-(t>>0&1)&996825010^-(t>>1&1)&642813549^-(t>>2&1)&513874426^-(t>>3&1)&1027748829^-(t>>4&1)&705979059}function kf(f){for(var t=1,n=0;n126)return"Invalid prefix ("+f+")";t=Zt(t)^h>>5}for(t=Zt(t),n=0;nn)throw new TypeError("Exceeds length limit");f=f.toLowerCase();var h=kf(f);if(typeof h=="string")throw new Error(h);for(var d=f+"1",a=0;a>5)throw new Error("Non 5-bit word");h=Zt(h)^m,d+=Fr.charAt(m)}for(a=0;a<6;++a)h=Zt(h);for(h^=1,a=0;a<6;++a){var x=h>>(5-a)*5&31;d+=Fr.charAt(x)}return d}function $f(f,t){if(t=t||90,f.length<8)return f+" too short";if(f.length>t)return"Exceeds length limit";var n=f.toLowerCase(),h=f.toUpperCase();if(f!==n&&f!==h)return"Mixed-case string "+f;f=n;var d=f.lastIndexOf("1");if(d===-1)return"No separator character for "+f;if(d===0)return"Missing prefix for "+f;var a=f.slice(0,d),m=f.slice(d+1);if(m.length<6)return"Data too short";var x=kf(a);if(typeof x=="string")return x;for(var _=[],A=0;A=m.length)&&_.push(g)}return x!==1?"Invalid checksum for "+f:{prefix:a,words:_}}function Qn(){var f=$f.apply(null,arguments);if(typeof f=="object")return f}function jn(f){var t=$f.apply(null,arguments);if(typeof t=="object")return t;throw new Error(t)}function n0(f,t,n,h){for(var d=0,a=0,m=(1<=n;)a-=n,x.push(d>>a&m);if(h)a>0&&x.push(d<=t)return"Excess padding";if(d<=n)throw RangeError(h)};var ar={},nh=ut.Buffer;function hh(f){if(f.length<8||f.length>72||f[0]!==48||f[1]!==f.length-2||f[2]!==2)return!1;var t=f[3];if(t===0||5+t>=f.length||f[4+t]!==2)return!1;var n=f[5+t];return!(n===0||6+t+n!==f.length||f[4]&128||t>1&&f[4]===0&&!(f[5]&128)||f[t+6]&128||n>1&&f[t+6]===0&&!(f[t+7]&128))}function sh(f){if(f.length<8)throw new Error("DER sequence length is too short");if(f.length>72)throw new Error("DER sequence length is too long");if(f[0]!==48)throw new Error("Expected DER sequence");if(f[1]!==f.length-2)throw new Error("DER sequence length is invalid");if(f[2]!==2)throw new Error("Expected DER integer");var t=f[3];if(t===0)throw new Error("R length is zero");if(5+t>=f.length)throw new Error("R length is too long");if(f[4+t]!==2)throw new Error("Expected DER integer (2)");var n=f[5+t];if(n===0)throw new Error("S length is zero");if(6+t+n!==f.length)throw new Error("S length is invalid");if(f[4]&128)throw new Error("R value is negative");if(t>1&&f[4]===0&&!(f[5]&128))throw new Error("R value excessively padded");if(f[t+6]&128)throw new Error("S value is negative");if(n>1&&f[t+6]===0&&!(f[t+7]&128))throw new Error("S value excessively padded");return{r:f.slice(4,4+t),s:f.slice(6+t)}}function dh(f,t){var n=f.length,h=t.length;if(n===0)throw new Error("R length is zero");if(h===0)throw new Error("S length is zero");if(n>33)throw new Error("R length is too long");if(h>33)throw new Error("S length is too long");if(f[0]&128)throw new Error("R value is negative");if(t[0]&128)throw new Error("S value is negative");if(n>1&&f[0]===0&&!(f[1]&128))throw new Error("R value excessively padded");if(h>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");var d=nh.allocUnsafe(6+n+h);return d[0]=48,d[1]=d.length-2,d[2]=2,d[3]=f.length,f.copy(d,4),d[4+n]=2,d[5+n]=t.length,t.copy(d,6+n),d}var oh={check:hh,decode:sh,encode:dh},We=ut.Buffer,Uf=oh,uh=We.from([48,129,211,2,1,1,4,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,129,133,48,129,130,2,1,1,48,44,6,7,42,134,72,206,61,1,1,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255,255,252,47,48,6,4,1,0,4,1,7,4,33,2,121,190,102,126,249,220,187,172,85,160,98,149,206,135,11,7,2,155,252,219,45,206,40,217,89,242,129,91,22,248,23,152,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65,2,1,1,161,36,3,34,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),ch=We.from([48,130,1,19,2,1,1,4,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,129,165,48,129,162,2,1,1,48,44,6,7,42,134,72,206,61,1,1,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255,255,252,47,48,6,4,1,0,4,1,7,4,65,4,121,190,102,126,249,220,187,172,85,160,98,149,206,135,11,7,2,155,252,219,45,206,40,217,89,242,129,91,22,248,23,152,72,58,218,119,38,163,196,101,93,164,251,252,14,17,8,168,253,23,180,72,166,133,84,25,156,71,208,143,251,16,212,184,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65,2,1,1,161,68,3,66,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);ar.privateKeyExport=function(f,t,n){var h=We.from(n?uh:ch);return f.copy(h,n?8:9),t.copy(h,n?181:214),h};ar.privateKeyImport=function(f){var t=f.length,n=0;if(!(t2)&&!(t1?f[n+h-2]<<8:0);if(n+=h,!(t32||t1&&t[h]===0&&!(t[h+1]&128);--n,++h);for(var d=We.concat([We.from([0]),f.s]),a=33,m=0;a>1&&d[m]===0&&!(d[m+1]&128);--a,++m);return Uf.encode(t.slice(h),d.slice(m))};ar.signatureImport=function(f){var t=We.alloc(32,0),n=We.alloc(32,0);try{var h=Uf.decode(f);if(h.r.length===33&&h.r[0]===0&&(h.r=h.r.slice(1)),h.r.length>32)throw new Error("R length is too long");if(h.s.length===33&&h.s[0]===0&&(h.s=h.s.slice(1)),h.s.length>32)throw new Error("S length is too long")}catch{return}return h.r.copy(t,32-h.r.length),h.s.copy(n,32-h.s.length),{r:t,s:n}};ar.signatureImportLax=function(f){var t=We.alloc(32,0),n=We.alloc(32,0),h=f.length,d=0;if(f[d++]===48){var a=f[d++];if(!(a&128&&(d+=a-128,d>h))&&f[d++]===2){var m=f[d++];if(m&128){if(a=m-128,d+a>h)return;for(;a>0&&f[d]===0;d+=1,a-=1);for(m=0;a>0;d+=1,a-=1)m=(m<<8)+f[d]}if(!(m>h-d)){var x=d;if(d+=m,f[d++]===2){var _=f[d++];if(_&128){if(a=_-128,d+a>h)return;for(;a>0&&f[d]===0;d+=1,a-=1);for(_=0;a>0;d+=1,a-=1)_=(_<<8)+f[d]}if(!(_>h-d)){var A=d;for(d+=_;m>0&&f[x]===0;m-=1,x+=1);if(!(m>32)){var y=f.slice(x,x+m);for(y.copy(t,32-y.length);_>0&&f[A]===0;_-=1,A+=1);if(!(_>32)){var g=f.slice(A,A+_);return g.copy(n,32-g.length),{r:t,s:n}}}}}}}}};const lh="compressed should be a boolean",vh="private key should be a Buffer",bh="private key length is invalid",ph="private key range is invalid",xh="tweak out of range or resulting private key is invalid",mh="tweak out of range",gh="couldn't export to DER format",_h="couldn't import from DER format",yh="public keys should be an Array",Mh="public keys Array should have at least 1 element",wh="public key should be a Buffer",Ah="public key length is invalid",Eh="the public key could not be parsed or is invalid",Ih="private was invalid, try again",Sh="tweak out of range or resulting public key is invalid",Lh="tweak out of range",Ph="the sum of the public keys is not valid",Bh="scalar was invalid (zero or overflow)",Rh="signature should be a Buffer",Nh="signature length is invalid",Th="couldn't parse signature",Ch="couldn't parse DER signature",Dh="couldn't serialize signature to DER format",zh="nonce generation function failed or private key is invalid",qh="couldn't recover public key from signature",Vh="message should be a Buffer",Yh="message length is invalid",kh="options should be an Object",$h="options.data should be a Buffer",Uh="options.data length is invalid",Oh="options.noncefn should be a Function",Fh="recovery should be a Number",Kh="recovery should have value between -1 and 4",Hh="tweak should be a Buffer",Gh="tweak length is invalid",Of={COMPRESSED_TYPE_INVALID:lh,EC_PRIVATE_KEY_TYPE_INVALID:vh,EC_PRIVATE_KEY_LENGTH_INVALID:bh,EC_PRIVATE_KEY_RANGE_INVALID:ph,EC_PRIVATE_KEY_TWEAK_ADD_FAIL:xh,EC_PRIVATE_KEY_TWEAK_MUL_FAIL:mh,EC_PRIVATE_KEY_EXPORT_DER_FAIL:gh,EC_PRIVATE_KEY_IMPORT_DER_FAIL:_h,EC_PUBLIC_KEYS_TYPE_INVALID:yh,EC_PUBLIC_KEYS_LENGTH_INVALID:Mh,EC_PUBLIC_KEY_TYPE_INVALID:wh,EC_PUBLIC_KEY_LENGTH_INVALID:Ah,EC_PUBLIC_KEY_PARSE_FAIL:Eh,EC_PUBLIC_KEY_CREATE_FAIL:Ih,EC_PUBLIC_KEY_TWEAK_ADD_FAIL:Sh,EC_PUBLIC_KEY_TWEAK_MUL_FAIL:Lh,EC_PUBLIC_KEY_COMBINE_FAIL:Ph,ECDH_FAIL:Bh,ECDSA_SIGNATURE_TYPE_INVALID:Rh,ECDSA_SIGNATURE_LENGTH_INVALID:Nh,ECDSA_SIGNATURE_PARSE_FAIL:Th,ECDSA_SIGNATURE_PARSE_DER_FAIL:Ch,ECDSA_SIGNATURE_SERIALIZE_DER_FAIL:Dh,ECDSA_SIGN_FAIL:zh,ECDSA_RECOVER_FAIL:qh,MSG32_TYPE_INVALID:Vh,MSG32_LENGTH_INVALID:Yh,OPTIONS_TYPE_INVALID:kh,OPTIONS_DATA_TYPE_INVALID:$h,OPTIONS_DATA_LENGTH_INVALID:Uh,OPTIONS_NONCEFN_TYPE_INVALID:Oh,RECOVERY_ID_TYPE_INVALID:Fh,RECOVERY_ID_VALUE_INVALID:Kh,TWEAK_TYPE_INVALID:Hh,TWEAK_LENGTH_INVALID:Gh};var C=Qe,Rr=ar,T=Of;function bt(f,t){return f===void 0?t:(C.isBoolean(f,T.COMPRESSED_TYPE_INVALID),f)}var Zh=function(f){return{privateKeyVerify:function(t){return C.isBuffer(t,T.EC_PRIVATE_KEY_TYPE_INVALID),t.length===32&&f.privateKeyVerify(t)},privateKeyExport:function(t,n){C.isBuffer(t,T.EC_PRIVATE_KEY_TYPE_INVALID),C.isBufferLength(t,32,T.EC_PRIVATE_KEY_LENGTH_INVALID),n=bt(n,!0);var h=f.privateKeyExport(t,n);return Rr.privateKeyExport(t,h,n)},privateKeyImport:function(t){if(C.isBuffer(t,T.EC_PRIVATE_KEY_TYPE_INVALID),t=Rr.privateKeyImport(t),t&&t.length===32&&f.privateKeyVerify(t))return t;throw new Error(T.EC_PRIVATE_KEY_IMPORT_DER_FAIL)},privateKeyNegate:function(t){return C.isBuffer(t,T.EC_PRIVATE_KEY_TYPE_INVALID),C.isBufferLength(t,32,T.EC_PRIVATE_KEY_LENGTH_INVALID),f.privateKeyNegate(t)},privateKeyModInverse:function(t){return C.isBuffer(t,T.EC_PRIVATE_KEY_TYPE_INVALID),C.isBufferLength(t,32,T.EC_PRIVATE_KEY_LENGTH_INVALID),f.privateKeyModInverse(t)},privateKeyTweakAdd:function(t,n){return C.isBuffer(t,T.EC_PRIVATE_KEY_TYPE_INVALID),C.isBufferLength(t,32,T.EC_PRIVATE_KEY_LENGTH_INVALID),C.isBuffer(n,T.TWEAK_TYPE_INVALID),C.isBufferLength(n,32,T.TWEAK_LENGTH_INVALID),f.privateKeyTweakAdd(t,n)},privateKeyTweakMul:function(t,n){return C.isBuffer(t,T.EC_PRIVATE_KEY_TYPE_INVALID),C.isBufferLength(t,32,T.EC_PRIVATE_KEY_LENGTH_INVALID),C.isBuffer(n,T.TWEAK_TYPE_INVALID),C.isBufferLength(n,32,T.TWEAK_LENGTH_INVALID),f.privateKeyTweakMul(t,n)},publicKeyCreate:function(t,n){return C.isBuffer(t,T.EC_PRIVATE_KEY_TYPE_INVALID),C.isBufferLength(t,32,T.EC_PRIVATE_KEY_LENGTH_INVALID),n=bt(n,!0),f.publicKeyCreate(t,n)},publicKeyConvert:function(t,n){return C.isBuffer(t,T.EC_PUBLIC_KEY_TYPE_INVALID),C.isBufferLength2(t,33,65,T.EC_PUBLIC_KEY_LENGTH_INVALID),n=bt(n,!0),f.publicKeyConvert(t,n)},publicKeyVerify:function(t){return C.isBuffer(t,T.EC_PUBLIC_KEY_TYPE_INVALID),f.publicKeyVerify(t)},publicKeyTweakAdd:function(t,n,h){return C.isBuffer(t,T.EC_PUBLIC_KEY_TYPE_INVALID),C.isBufferLength2(t,33,65,T.EC_PUBLIC_KEY_LENGTH_INVALID),C.isBuffer(n,T.TWEAK_TYPE_INVALID),C.isBufferLength(n,32,T.TWEAK_LENGTH_INVALID),h=bt(h,!0),f.publicKeyTweakAdd(t,n,h)},publicKeyTweakMul:function(t,n,h){return C.isBuffer(t,T.EC_PUBLIC_KEY_TYPE_INVALID),C.isBufferLength2(t,33,65,T.EC_PUBLIC_KEY_LENGTH_INVALID),C.isBuffer(n,T.TWEAK_TYPE_INVALID),C.isBufferLength(n,32,T.TWEAK_LENGTH_INVALID),h=bt(h,!0),f.publicKeyTweakMul(t,n,h)},publicKeyCombine:function(t,n){C.isArray(t,T.EC_PUBLIC_KEYS_TYPE_INVALID),C.isLengthGTZero(t,T.EC_PUBLIC_KEYS_LENGTH_INVALID);for(var h=0;h0?e:i},a.min=function(e,i){return e.cmp(i)<0?e:i},a.prototype._init=function(e,i,s){if(typeof e=="number")return this._initNumber(e,i,s);if(typeof e=="object")return this._initArray(e,i,s);i==="hex"&&(i=16),h(i===(i|0)&&i>=2&&i<=36),e=e.toString().replace(/\s+/g,"");var o=0;e[0]==="-"&&(o++,this.negative=1),o=0;o-=3)b=e[o]|e[o-1]<<8|e[o-2]<<16,this.words[l]|=b<>>26-p&67108863,p+=24,p>=26&&(p-=26,l++);else if(s==="le")for(o=0,l=0;o>>26-p&67108863,p+=24,p>=26&&(p-=26,l++);return this.strip()};function x(v,e){var i=v.charCodeAt(e);return i>=65&&i<=70?i-55:i>=97&&i<=102?i-87:i-48&15}function _(v,e,i){var s=x(v,i);return i-1>=e&&(s|=x(v,i-1)<<4),s}a.prototype._parseHex=function(e,i,s){this.length=Math.ceil((e.length-i)/6),this.words=new Array(this.length);for(var o=0;o=i;o-=2)p=_(e,i,o)<=18?(l-=18,b+=1,this.words[b]|=p>>>26):l+=8;else{var u=e.length-i;for(o=u%2===0?i+1:i;o=18?(l-=18,b+=1,this.words[b]|=p>>>26):l+=8}this.strip()};function A(v,e,i,s){for(var o=0,l=Math.min(v.length,i),b=e;b=49?o+=p-49+10:p>=17?o+=p-17+10:o+=p}return o}a.prototype._parseBase=function(e,i,s){this.words=[0],this.length=1;for(var o=0,l=1;l<=67108863;l*=i)o++;o--,l=l/i|0;for(var b=e.length-s,p=b%o,u=Math.min(b,b-p)+s,r=0,c=s;c1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},a.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},a.prototype.inspect=function(){return(this.red?""};var y=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],g=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],M=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];a.prototype.toString=function(e,i){e=e||10,i=i|0||1;var s;if(e===16||e==="hex"){s="";for(var o=0,l=0,b=0;b>>24-o&16777215,o+=2,o>=26&&(o-=26,b--),l!==0||b!==this.length-1?s=y[6-u.length]+u+s:s=u+s}for(l!==0&&(s=l.toString(16)+s);s.length%i!==0;)s="0"+s;return this.negative!==0&&(s="-"+s),s}if(e===(e|0)&&e>=2&&e<=36){var r=g[e],c=M[e];s="";var I=this.clone();for(I.negative=0;!I.isZero();){var S=I.modn(c).toString(e);I=I.idivn(c),I.isZero()?s=S+s:s=y[r-S.length]+S+s}for(this.isZero()&&(s="0"+s);s.length%i!==0;)s="0"+s;return this.negative!==0&&(s="-"+s),s}h(!1,"Base should be between 2 and 36")},a.prototype.toNumber=function(){var e=this.words[0];return this.length===2?e+=this.words[1]*67108864:this.length===3&&this.words[2]===1?e+=4503599627370496+this.words[1]*67108864:this.length>2&&h(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-e:e},a.prototype.toJSON=function(){return this.toString(16)},a.prototype.toBuffer=function(e,i){return h(typeof m<"u"),this.toArrayLike(m,e,i)},a.prototype.toArray=function(e,i){return this.toArrayLike(Array,e,i)},a.prototype.toArrayLike=function(e,i,s){var o=this.byteLength(),l=s||Math.max(1,o);h(o<=l,"byte array longer than desired length"),h(l>0,"Requested array length <= 0"),this.strip();var b=i==="le",p=new e(l),u,r,c=this.clone();if(b){for(r=0;!c.isZero();r++)u=c.andln(255),c.iushrn(8),p[r]=u;for(;r=4096&&(s+=13,i>>>=13),i>=64&&(s+=7,i>>>=7),i>=8&&(s+=4,i>>>=4),i>=2&&(s+=2,i>>>=2),s+i},a.prototype._zeroBits=function(e){if(e===0)return 26;var i=e,s=0;return i&8191||(s+=13,i>>>=13),i&127||(s+=7,i>>>=7),i&15||(s+=4,i>>>=4),i&3||(s+=2,i>>>=2),i&1||s++,s},a.prototype.bitLength=function(){var e=this.words[this.length-1],i=this._countBits(e);return(this.length-1)*26+i};function w(v){for(var e=new Array(v.bitLength()),i=0;i>>o}return e}a.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,i=0;ie.length?this.clone().ior(e):e.clone().ior(this)},a.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},a.prototype.iuand=function(e){var i;this.length>e.length?i=e:i=this;for(var s=0;se.length?this.clone().iand(e):e.clone().iand(this)},a.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},a.prototype.iuxor=function(e){var i,s;this.length>e.length?(i=this,s=e):(i=e,s=this);for(var o=0;oe.length?this.clone().ixor(e):e.clone().ixor(this)},a.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},a.prototype.inotn=function(e){h(typeof e=="number"&&e>=0);var i=Math.ceil(e/26)|0,s=e%26;this._expand(i),s>0&&i--;for(var o=0;o0&&(this.words[o]=~this.words[o]&67108863>>26-s),this.strip()},a.prototype.notn=function(e){return this.clone().inotn(e)},a.prototype.setn=function(e,i){h(typeof e=="number"&&e>=0);var s=e/26|0,o=e%26;return this._expand(s+1),i?this.words[s]=this.words[s]|1<e.length?(s=this,o=e):(s=e,o=this);for(var l=0,b=0;b>>26;for(;l!==0&&b>>26;if(this.length=s.length,l!==0)this.words[this.length]=l,this.length++;else if(s!==this)for(;be.length?this.clone().iadd(e):e.clone().iadd(this)},a.prototype.isub=function(e){if(e.negative!==0){e.negative=0;var i=this.iadd(e);return e.negative=1,i._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var s=this.cmp(e);if(s===0)return this.negative=0,this.length=1,this.words[0]=0,this;var o,l;s>0?(o=this,l=e):(o=e,l=this);for(var b=0,p=0;p>26,this.words[p]=i&67108863;for(;b!==0&&p>26,this.words[p]=i&67108863;if(b===0&&p>>26,I=u&67108863,S=Math.min(r,e.length-1),L=Math.max(0,r-v.length+1);L<=S;L++){var B=r-L|0;o=v.words[B]|0,l=e.words[L]|0,b=o*l+I,c+=b/67108864|0,I=b&67108863}i.words[r]=I|0,u=c|0}return u!==0?i.words[r]=u|0:i.length--,i.strip()}var P=function(e,i,s){var o=e.words,l=i.words,b=s.words,p=0,u,r,c,I=o[0]|0,S=I&8191,L=I>>>13,B=o[1]|0,z=B&8191,V=B>>>13,Ce=o[2]|0,Y=Ce&8191,$=Ce>>>13,nr=o[3]|0,U=nr&8191,O=nr>>>13,hr=o[4]|0,F=hr&8191,K=hr>>>13,sr=o[5]|0,H=sr&8191,G=sr>>>13,dr=o[6]|0,Z=dr&8191,W=dr>>>13,or=o[7]|0,J=or&8191,X=or>>>13,ur=o[8]|0,Q=ur&8191,j=ur>>>13,cr=o[9]|0,ee=cr&8191,te=cr>>>13,lr=l[0]|0,re=lr&8191,fe=lr>>>13,vr=l[1]|0,ie=vr&8191,ae=vr>>>13,br=l[2]|0,ne=br&8191,he=br>>>13,pr=l[3]|0,se=pr&8191,de=pr>>>13,xr=l[4]|0,oe=xr&8191,ue=xr>>>13,mr=l[5]|0,ce=mr&8191,le=mr>>>13,gr=l[6]|0,ve=gr&8191,be=gr>>>13,_r=l[7]|0,pe=_r&8191,xe=_r>>>13,yr=l[8]|0,me=yr&8191,ge=yr>>>13,Mr=l[9]|0,_e=Mr&8191,ye=Mr>>>13;s.negative=e.negative^i.negative,s.length=19,u=Math.imul(S,re),r=Math.imul(S,fe),r=r+Math.imul(L,re)|0,c=Math.imul(L,fe);var yt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(yt>>>26)|0,yt&=67108863,u=Math.imul(z,re),r=Math.imul(z,fe),r=r+Math.imul(V,re)|0,c=Math.imul(V,fe),u=u+Math.imul(S,ie)|0,r=r+Math.imul(S,ae)|0,r=r+Math.imul(L,ie)|0,c=c+Math.imul(L,ae)|0;var Mt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,u=Math.imul(Y,re),r=Math.imul(Y,fe),r=r+Math.imul($,re)|0,c=Math.imul($,fe),u=u+Math.imul(z,ie)|0,r=r+Math.imul(z,ae)|0,r=r+Math.imul(V,ie)|0,c=c+Math.imul(V,ae)|0,u=u+Math.imul(S,ne)|0,r=r+Math.imul(S,he)|0,r=r+Math.imul(L,ne)|0,c=c+Math.imul(L,he)|0;var wt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(wt>>>26)|0,wt&=67108863,u=Math.imul(U,re),r=Math.imul(U,fe),r=r+Math.imul(O,re)|0,c=Math.imul(O,fe),u=u+Math.imul(Y,ie)|0,r=r+Math.imul(Y,ae)|0,r=r+Math.imul($,ie)|0,c=c+Math.imul($,ae)|0,u=u+Math.imul(z,ne)|0,r=r+Math.imul(z,he)|0,r=r+Math.imul(V,ne)|0,c=c+Math.imul(V,he)|0,u=u+Math.imul(S,se)|0,r=r+Math.imul(S,de)|0,r=r+Math.imul(L,se)|0,c=c+Math.imul(L,de)|0;var At=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(At>>>26)|0,At&=67108863,u=Math.imul(F,re),r=Math.imul(F,fe),r=r+Math.imul(K,re)|0,c=Math.imul(K,fe),u=u+Math.imul(U,ie)|0,r=r+Math.imul(U,ae)|0,r=r+Math.imul(O,ie)|0,c=c+Math.imul(O,ae)|0,u=u+Math.imul(Y,ne)|0,r=r+Math.imul(Y,he)|0,r=r+Math.imul($,ne)|0,c=c+Math.imul($,he)|0,u=u+Math.imul(z,se)|0,r=r+Math.imul(z,de)|0,r=r+Math.imul(V,se)|0,c=c+Math.imul(V,de)|0,u=u+Math.imul(S,oe)|0,r=r+Math.imul(S,ue)|0,r=r+Math.imul(L,oe)|0,c=c+Math.imul(L,ue)|0;var Et=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Et>>>26)|0,Et&=67108863,u=Math.imul(H,re),r=Math.imul(H,fe),r=r+Math.imul(G,re)|0,c=Math.imul(G,fe),u=u+Math.imul(F,ie)|0,r=r+Math.imul(F,ae)|0,r=r+Math.imul(K,ie)|0,c=c+Math.imul(K,ae)|0,u=u+Math.imul(U,ne)|0,r=r+Math.imul(U,he)|0,r=r+Math.imul(O,ne)|0,c=c+Math.imul(O,he)|0,u=u+Math.imul(Y,se)|0,r=r+Math.imul(Y,de)|0,r=r+Math.imul($,se)|0,c=c+Math.imul($,de)|0,u=u+Math.imul(z,oe)|0,r=r+Math.imul(z,ue)|0,r=r+Math.imul(V,oe)|0,c=c+Math.imul(V,ue)|0,u=u+Math.imul(S,ce)|0,r=r+Math.imul(S,le)|0,r=r+Math.imul(L,ce)|0,c=c+Math.imul(L,le)|0;var It=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(It>>>26)|0,It&=67108863,u=Math.imul(Z,re),r=Math.imul(Z,fe),r=r+Math.imul(W,re)|0,c=Math.imul(W,fe),u=u+Math.imul(H,ie)|0,r=r+Math.imul(H,ae)|0,r=r+Math.imul(G,ie)|0,c=c+Math.imul(G,ae)|0,u=u+Math.imul(F,ne)|0,r=r+Math.imul(F,he)|0,r=r+Math.imul(K,ne)|0,c=c+Math.imul(K,he)|0,u=u+Math.imul(U,se)|0,r=r+Math.imul(U,de)|0,r=r+Math.imul(O,se)|0,c=c+Math.imul(O,de)|0,u=u+Math.imul(Y,oe)|0,r=r+Math.imul(Y,ue)|0,r=r+Math.imul($,oe)|0,c=c+Math.imul($,ue)|0,u=u+Math.imul(z,ce)|0,r=r+Math.imul(z,le)|0,r=r+Math.imul(V,ce)|0,c=c+Math.imul(V,le)|0,u=u+Math.imul(S,ve)|0,r=r+Math.imul(S,be)|0,r=r+Math.imul(L,ve)|0,c=c+Math.imul(L,be)|0;var St=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(St>>>26)|0,St&=67108863,u=Math.imul(J,re),r=Math.imul(J,fe),r=r+Math.imul(X,re)|0,c=Math.imul(X,fe),u=u+Math.imul(Z,ie)|0,r=r+Math.imul(Z,ae)|0,r=r+Math.imul(W,ie)|0,c=c+Math.imul(W,ae)|0,u=u+Math.imul(H,ne)|0,r=r+Math.imul(H,he)|0,r=r+Math.imul(G,ne)|0,c=c+Math.imul(G,he)|0,u=u+Math.imul(F,se)|0,r=r+Math.imul(F,de)|0,r=r+Math.imul(K,se)|0,c=c+Math.imul(K,de)|0,u=u+Math.imul(U,oe)|0,r=r+Math.imul(U,ue)|0,r=r+Math.imul(O,oe)|0,c=c+Math.imul(O,ue)|0,u=u+Math.imul(Y,ce)|0,r=r+Math.imul(Y,le)|0,r=r+Math.imul($,ce)|0,c=c+Math.imul($,le)|0,u=u+Math.imul(z,ve)|0,r=r+Math.imul(z,be)|0,r=r+Math.imul(V,ve)|0,c=c+Math.imul(V,be)|0,u=u+Math.imul(S,pe)|0,r=r+Math.imul(S,xe)|0,r=r+Math.imul(L,pe)|0,c=c+Math.imul(L,xe)|0;var Lt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,u=Math.imul(Q,re),r=Math.imul(Q,fe),r=r+Math.imul(j,re)|0,c=Math.imul(j,fe),u=u+Math.imul(J,ie)|0,r=r+Math.imul(J,ae)|0,r=r+Math.imul(X,ie)|0,c=c+Math.imul(X,ae)|0,u=u+Math.imul(Z,ne)|0,r=r+Math.imul(Z,he)|0,r=r+Math.imul(W,ne)|0,c=c+Math.imul(W,he)|0,u=u+Math.imul(H,se)|0,r=r+Math.imul(H,de)|0,r=r+Math.imul(G,se)|0,c=c+Math.imul(G,de)|0,u=u+Math.imul(F,oe)|0,r=r+Math.imul(F,ue)|0,r=r+Math.imul(K,oe)|0,c=c+Math.imul(K,ue)|0,u=u+Math.imul(U,ce)|0,r=r+Math.imul(U,le)|0,r=r+Math.imul(O,ce)|0,c=c+Math.imul(O,le)|0,u=u+Math.imul(Y,ve)|0,r=r+Math.imul(Y,be)|0,r=r+Math.imul($,ve)|0,c=c+Math.imul($,be)|0,u=u+Math.imul(z,pe)|0,r=r+Math.imul(z,xe)|0,r=r+Math.imul(V,pe)|0,c=c+Math.imul(V,xe)|0,u=u+Math.imul(S,me)|0,r=r+Math.imul(S,ge)|0,r=r+Math.imul(L,me)|0,c=c+Math.imul(L,ge)|0;var Pt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,u=Math.imul(ee,re),r=Math.imul(ee,fe),r=r+Math.imul(te,re)|0,c=Math.imul(te,fe),u=u+Math.imul(Q,ie)|0,r=r+Math.imul(Q,ae)|0,r=r+Math.imul(j,ie)|0,c=c+Math.imul(j,ae)|0,u=u+Math.imul(J,ne)|0,r=r+Math.imul(J,he)|0,r=r+Math.imul(X,ne)|0,c=c+Math.imul(X,he)|0,u=u+Math.imul(Z,se)|0,r=r+Math.imul(Z,de)|0,r=r+Math.imul(W,se)|0,c=c+Math.imul(W,de)|0,u=u+Math.imul(H,oe)|0,r=r+Math.imul(H,ue)|0,r=r+Math.imul(G,oe)|0,c=c+Math.imul(G,ue)|0,u=u+Math.imul(F,ce)|0,r=r+Math.imul(F,le)|0,r=r+Math.imul(K,ce)|0,c=c+Math.imul(K,le)|0,u=u+Math.imul(U,ve)|0,r=r+Math.imul(U,be)|0,r=r+Math.imul(O,ve)|0,c=c+Math.imul(O,be)|0,u=u+Math.imul(Y,pe)|0,r=r+Math.imul(Y,xe)|0,r=r+Math.imul($,pe)|0,c=c+Math.imul($,xe)|0,u=u+Math.imul(z,me)|0,r=r+Math.imul(z,ge)|0,r=r+Math.imul(V,me)|0,c=c+Math.imul(V,ge)|0,u=u+Math.imul(S,_e)|0,r=r+Math.imul(S,ye)|0,r=r+Math.imul(L,_e)|0,c=c+Math.imul(L,ye)|0;var Bt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,u=Math.imul(ee,ie),r=Math.imul(ee,ae),r=r+Math.imul(te,ie)|0,c=Math.imul(te,ae),u=u+Math.imul(Q,ne)|0,r=r+Math.imul(Q,he)|0,r=r+Math.imul(j,ne)|0,c=c+Math.imul(j,he)|0,u=u+Math.imul(J,se)|0,r=r+Math.imul(J,de)|0,r=r+Math.imul(X,se)|0,c=c+Math.imul(X,de)|0,u=u+Math.imul(Z,oe)|0,r=r+Math.imul(Z,ue)|0,r=r+Math.imul(W,oe)|0,c=c+Math.imul(W,ue)|0,u=u+Math.imul(H,ce)|0,r=r+Math.imul(H,le)|0,r=r+Math.imul(G,ce)|0,c=c+Math.imul(G,le)|0,u=u+Math.imul(F,ve)|0,r=r+Math.imul(F,be)|0,r=r+Math.imul(K,ve)|0,c=c+Math.imul(K,be)|0,u=u+Math.imul(U,pe)|0,r=r+Math.imul(U,xe)|0,r=r+Math.imul(O,pe)|0,c=c+Math.imul(O,xe)|0,u=u+Math.imul(Y,me)|0,r=r+Math.imul(Y,ge)|0,r=r+Math.imul($,me)|0,c=c+Math.imul($,ge)|0,u=u+Math.imul(z,_e)|0,r=r+Math.imul(z,ye)|0,r=r+Math.imul(V,_e)|0,c=c+Math.imul(V,ye)|0;var Rt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,u=Math.imul(ee,ne),r=Math.imul(ee,he),r=r+Math.imul(te,ne)|0,c=Math.imul(te,he),u=u+Math.imul(Q,se)|0,r=r+Math.imul(Q,de)|0,r=r+Math.imul(j,se)|0,c=c+Math.imul(j,de)|0,u=u+Math.imul(J,oe)|0,r=r+Math.imul(J,ue)|0,r=r+Math.imul(X,oe)|0,c=c+Math.imul(X,ue)|0,u=u+Math.imul(Z,ce)|0,r=r+Math.imul(Z,le)|0,r=r+Math.imul(W,ce)|0,c=c+Math.imul(W,le)|0,u=u+Math.imul(H,ve)|0,r=r+Math.imul(H,be)|0,r=r+Math.imul(G,ve)|0,c=c+Math.imul(G,be)|0,u=u+Math.imul(F,pe)|0,r=r+Math.imul(F,xe)|0,r=r+Math.imul(K,pe)|0,c=c+Math.imul(K,xe)|0,u=u+Math.imul(U,me)|0,r=r+Math.imul(U,ge)|0,r=r+Math.imul(O,me)|0,c=c+Math.imul(O,ge)|0,u=u+Math.imul(Y,_e)|0,r=r+Math.imul(Y,ye)|0,r=r+Math.imul($,_e)|0,c=c+Math.imul($,ye)|0;var Nt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,u=Math.imul(ee,se),r=Math.imul(ee,de),r=r+Math.imul(te,se)|0,c=Math.imul(te,de),u=u+Math.imul(Q,oe)|0,r=r+Math.imul(Q,ue)|0,r=r+Math.imul(j,oe)|0,c=c+Math.imul(j,ue)|0,u=u+Math.imul(J,ce)|0,r=r+Math.imul(J,le)|0,r=r+Math.imul(X,ce)|0,c=c+Math.imul(X,le)|0,u=u+Math.imul(Z,ve)|0,r=r+Math.imul(Z,be)|0,r=r+Math.imul(W,ve)|0,c=c+Math.imul(W,be)|0,u=u+Math.imul(H,pe)|0,r=r+Math.imul(H,xe)|0,r=r+Math.imul(G,pe)|0,c=c+Math.imul(G,xe)|0,u=u+Math.imul(F,me)|0,r=r+Math.imul(F,ge)|0,r=r+Math.imul(K,me)|0,c=c+Math.imul(K,ge)|0,u=u+Math.imul(U,_e)|0,r=r+Math.imul(U,ye)|0,r=r+Math.imul(O,_e)|0,c=c+Math.imul(O,ye)|0;var Tt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,u=Math.imul(ee,oe),r=Math.imul(ee,ue),r=r+Math.imul(te,oe)|0,c=Math.imul(te,ue),u=u+Math.imul(Q,ce)|0,r=r+Math.imul(Q,le)|0,r=r+Math.imul(j,ce)|0,c=c+Math.imul(j,le)|0,u=u+Math.imul(J,ve)|0,r=r+Math.imul(J,be)|0,r=r+Math.imul(X,ve)|0,c=c+Math.imul(X,be)|0,u=u+Math.imul(Z,pe)|0,r=r+Math.imul(Z,xe)|0,r=r+Math.imul(W,pe)|0,c=c+Math.imul(W,xe)|0,u=u+Math.imul(H,me)|0,r=r+Math.imul(H,ge)|0,r=r+Math.imul(G,me)|0,c=c+Math.imul(G,ge)|0,u=u+Math.imul(F,_e)|0,r=r+Math.imul(F,ye)|0,r=r+Math.imul(K,_e)|0,c=c+Math.imul(K,ye)|0;var Ct=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,u=Math.imul(ee,ce),r=Math.imul(ee,le),r=r+Math.imul(te,ce)|0,c=Math.imul(te,le),u=u+Math.imul(Q,ve)|0,r=r+Math.imul(Q,be)|0,r=r+Math.imul(j,ve)|0,c=c+Math.imul(j,be)|0,u=u+Math.imul(J,pe)|0,r=r+Math.imul(J,xe)|0,r=r+Math.imul(X,pe)|0,c=c+Math.imul(X,xe)|0,u=u+Math.imul(Z,me)|0,r=r+Math.imul(Z,ge)|0,r=r+Math.imul(W,me)|0,c=c+Math.imul(W,ge)|0,u=u+Math.imul(H,_e)|0,r=r+Math.imul(H,ye)|0,r=r+Math.imul(G,_e)|0,c=c+Math.imul(G,ye)|0;var Dt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Dt>>>26)|0,Dt&=67108863,u=Math.imul(ee,ve),r=Math.imul(ee,be),r=r+Math.imul(te,ve)|0,c=Math.imul(te,be),u=u+Math.imul(Q,pe)|0,r=r+Math.imul(Q,xe)|0,r=r+Math.imul(j,pe)|0,c=c+Math.imul(j,xe)|0,u=u+Math.imul(J,me)|0,r=r+Math.imul(J,ge)|0,r=r+Math.imul(X,me)|0,c=c+Math.imul(X,ge)|0,u=u+Math.imul(Z,_e)|0,r=r+Math.imul(Z,ye)|0,r=r+Math.imul(W,_e)|0,c=c+Math.imul(W,ye)|0;var zt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(zt>>>26)|0,zt&=67108863,u=Math.imul(ee,pe),r=Math.imul(ee,xe),r=r+Math.imul(te,pe)|0,c=Math.imul(te,xe),u=u+Math.imul(Q,me)|0,r=r+Math.imul(Q,ge)|0,r=r+Math.imul(j,me)|0,c=c+Math.imul(j,ge)|0,u=u+Math.imul(J,_e)|0,r=r+Math.imul(J,ye)|0,r=r+Math.imul(X,_e)|0,c=c+Math.imul(X,ye)|0;var qt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(qt>>>26)|0,qt&=67108863,u=Math.imul(ee,me),r=Math.imul(ee,ge),r=r+Math.imul(te,me)|0,c=Math.imul(te,ge),u=u+Math.imul(Q,_e)|0,r=r+Math.imul(Q,ye)|0,r=r+Math.imul(j,_e)|0,c=c+Math.imul(j,ye)|0;var Vt=(p+u|0)+((r&8191)<<13)|0;p=(c+(r>>>13)|0)+(Vt>>>26)|0,Vt&=67108863,u=Math.imul(ee,_e),r=Math.imul(ee,ye),r=r+Math.imul(te,_e)|0,c=Math.imul(te,ye);var Yt=(p+u|0)+((r&8191)<<13)|0;return p=(c+(r>>>13)|0)+(Yt>>>26)|0,Yt&=67108863,b[0]=yt,b[1]=Mt,b[2]=wt,b[3]=At,b[4]=Et,b[5]=It,b[6]=St,b[7]=Lt,b[8]=Pt,b[9]=Bt,b[10]=Rt,b[11]=Nt,b[12]=Tt,b[13]=Ct,b[14]=Dt,b[15]=zt,b[16]=qt,b[17]=Vt,b[18]=Yt,p!==0&&(b[19]=p,s.length++),s};Math.imul||(P=E);function N(v,e,i){i.negative=e.negative^v.negative,i.length=v.length+e.length;for(var s=0,o=0,l=0;l>>26)|0,o+=b>>>26,b&=67108863}i.words[l]=p,s=b,b=o}return s!==0?i.words[l]=s:i.length--,i.strip()}function R(v,e,i){var s=new D;return s.mulp(v,e,i)}a.prototype.mulTo=function(e,i){var s,o=this.length+e.length;return this.length===10&&e.length===10?s=P(this,e,i):o<63?s=E(this,e,i):o<1024?s=N(this,e,i):s=R(this,e,i),s};function D(v,e){this.x=v,this.y=e}D.prototype.makeRBT=function(e){for(var i=new Array(e),s=a.prototype._countBits(e)-1,o=0;o>=1;return o},D.prototype.permute=function(e,i,s,o,l,b){for(var p=0;p>>1)l++;return 1<>>13,s[2*b+1]=l&8191,l=l>>>13;for(b=2*i;b>=26,i+=o/67108864|0,i+=l>>>26,this.words[s]=l&67108863}return i!==0&&(this.words[s]=i,this.length++),this.length=e===0?1:this.length,this},a.prototype.muln=function(e){return this.clone().imuln(e)},a.prototype.sqr=function(){return this.mul(this)},a.prototype.isqr=function(){return this.imul(this.clone())},a.prototype.pow=function(e){var i=w(e);if(i.length===0)return new a(1);for(var s=this,o=0;o=0);var i=e%26,s=(e-i)/26,o=67108863>>>26-i<<26-i,l;if(i!==0){var b=0;for(l=0;l>>26-i}b&&(this.words[l]=b,this.length++)}if(s!==0){for(l=this.length-1;l>=0;l--)this.words[l+s]=this.words[l];for(l=0;l=0);var o;i?o=(i-i%26)/26:o=0;var l=e%26,b=Math.min((e-l)/26,this.length),p=67108863^67108863>>>l<b)for(this.length-=b,r=0;r=0&&(c!==0||r>=o);r--){var I=this.words[r]|0;this.words[r]=c<<26-l|I>>>l,c=I&p}return u&&c!==0&&(u.words[u.length++]=c),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},a.prototype.ishrn=function(e,i,s){return h(this.negative===0),this.iushrn(e,i,s)},a.prototype.shln=function(e){return this.clone().ishln(e)},a.prototype.ushln=function(e){return this.clone().iushln(e)},a.prototype.shrn=function(e){return this.clone().ishrn(e)},a.prototype.ushrn=function(e){return this.clone().iushrn(e)},a.prototype.testn=function(e){h(typeof e=="number"&&e>=0);var i=e%26,s=(e-i)/26,o=1<=0);var i=e%26,s=(e-i)/26;if(h(this.negative===0,"imaskn works only with positive numbers"),this.length<=s)return this;if(i!==0&&s++,this.length=Math.min(s,this.length),i!==0){var o=67108863^67108863>>>i<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},a.prototype.isubn=function(e){if(h(typeof e=="number"),h(e<67108864),e<0)return this.iaddn(-e);if(this.negative!==0)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(u/67108864|0),this.words[l+s]=b&67108863}for(;l>26,this.words[l+s]=b&67108863;if(p===0)return this.strip();for(h(p===-1),p=0,l=0;l>26,this.words[l]=b&67108863;return this.negative=1,this.strip()},a.prototype._wordDiv=function(e,i){var s=this.length-e.length,o=this.clone(),l=e,b=l.words[l.length-1]|0,p=this._countBits(b);s=26-p,s!==0&&(l=l.ushln(s),o.iushln(s),b=l.words[l.length-1]|0);var u=o.length-l.length,r;if(i!=="mod"){r=new a(null),r.length=u+1,r.words=new Array(r.length);for(var c=0;c=0;S--){var L=(o.words[l.length+S]|0)*67108864+(o.words[l.length+S-1]|0);for(L=Math.min(L/b|0,67108863),o._ishlnsubmul(l,L,S);o.negative!==0;)L--,o.negative=0,o._ishlnsubmul(l,1,S),o.isZero()||(o.negative^=1);r&&(r.words[S]=L)}return r&&r.strip(),o.strip(),i!=="div"&&s!==0&&o.iushrn(s),{div:r||null,mod:o}},a.prototype.divmod=function(e,i,s){if(h(!e.isZero()),this.isZero())return{div:new a(0),mod:new a(0)};var o,l,b;return this.negative!==0&&e.negative===0?(b=this.neg().divmod(e,i),i!=="mod"&&(o=b.div.neg()),i!=="div"&&(l=b.mod.neg(),s&&l.negative!==0&&l.iadd(e)),{div:o,mod:l}):this.negative===0&&e.negative!==0?(b=this.divmod(e.neg(),i),i!=="mod"&&(o=b.div.neg()),{div:o,mod:b.mod}):this.negative&e.negative?(b=this.neg().divmod(e.neg(),i),i!=="div"&&(l=b.mod.neg(),s&&l.negative!==0&&l.isub(e)),{div:b.div,mod:l}):e.length>this.length||this.cmp(e)<0?{div:new a(0),mod:this}:e.length===1?i==="div"?{div:this.divn(e.words[0]),mod:null}:i==="mod"?{div:null,mod:new a(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new a(this.modn(e.words[0]))}:this._wordDiv(e,i)},a.prototype.div=function(e){return this.divmod(e,"div",!1).div},a.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},a.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},a.prototype.divRound=function(e){var i=this.divmod(e);if(i.mod.isZero())return i.div;var s=i.div.negative!==0?i.mod.isub(e):i.mod,o=e.ushrn(1),l=e.andln(1),b=s.cmp(o);return b<0||l===1&&b===0?i.div:i.div.negative!==0?i.div.isubn(1):i.div.iaddn(1)},a.prototype.modn=function(e){h(e<=67108863);for(var i=(1<<26)%e,s=0,o=this.length-1;o>=0;o--)s=(i*s+(this.words[o]|0))%e;return s},a.prototype.idivn=function(e){h(e<=67108863);for(var i=0,s=this.length-1;s>=0;s--){var o=(this.words[s]|0)+i*67108864;this.words[s]=o/e|0,i=o%e}return this.strip()},a.prototype.divn=function(e){return this.clone().idivn(e)},a.prototype.egcd=function(e){h(e.negative===0),h(!e.isZero());var i=this,s=e.clone();i.negative!==0?i=i.umod(e):i=i.clone();for(var o=new a(1),l=new a(0),b=new a(0),p=new a(1),u=0;i.isEven()&&s.isEven();)i.iushrn(1),s.iushrn(1),++u;for(var r=s.clone(),c=i.clone();!i.isZero();){for(var I=0,S=1;!(i.words[0]&S)&&I<26;++I,S<<=1);if(I>0)for(i.iushrn(I);I-- >0;)(o.isOdd()||l.isOdd())&&(o.iadd(r),l.isub(c)),o.iushrn(1),l.iushrn(1);for(var L=0,B=1;!(s.words[0]&B)&&L<26;++L,B<<=1);if(L>0)for(s.iushrn(L);L-- >0;)(b.isOdd()||p.isOdd())&&(b.iadd(r),p.isub(c)),b.iushrn(1),p.iushrn(1);i.cmp(s)>=0?(i.isub(s),o.isub(b),l.isub(p)):(s.isub(i),b.isub(o),p.isub(l))}return{a:b,b:p,gcd:s.iushln(u)}},a.prototype._invmp=function(e){h(e.negative===0),h(!e.isZero());var i=this,s=e.clone();i.negative!==0?i=i.umod(e):i=i.clone();for(var o=new a(1),l=new a(0),b=s.clone();i.cmpn(1)>0&&s.cmpn(1)>0;){for(var p=0,u=1;!(i.words[0]&u)&&p<26;++p,u<<=1);if(p>0)for(i.iushrn(p);p-- >0;)o.isOdd()&&o.iadd(b),o.iushrn(1);for(var r=0,c=1;!(s.words[0]&c)&&r<26;++r,c<<=1);if(r>0)for(s.iushrn(r);r-- >0;)l.isOdd()&&l.iadd(b),l.iushrn(1);i.cmp(s)>=0?(i.isub(s),o.isub(l)):(s.isub(i),l.isub(o))}var I;return i.cmpn(1)===0?I=o:I=l,I.cmpn(0)<0&&I.iadd(e),I},a.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var i=this.clone(),s=e.clone();i.negative=0,s.negative=0;for(var o=0;i.isEven()&&s.isEven();o++)i.iushrn(1),s.iushrn(1);do{for(;i.isEven();)i.iushrn(1);for(;s.isEven();)s.iushrn(1);var l=i.cmp(s);if(l<0){var b=i;i=s,s=b}else if(l===0||s.cmpn(1)===0)break;i.isub(s)}while(!0);return s.iushln(o)},a.prototype.invm=function(e){return this.egcd(e).a.umod(e)},a.prototype.isEven=function(){return(this.words[0]&1)===0},a.prototype.isOdd=function(){return(this.words[0]&1)===1},a.prototype.andln=function(e){return this.words[0]&e},a.prototype.bincn=function(e){h(typeof e=="number");var i=e%26,s=(e-i)/26,o=1<>>26,p&=67108863,this.words[b]=p}return l!==0&&(this.words[b]=l,this.length++),this},a.prototype.isZero=function(){return this.length===1&&this.words[0]===0},a.prototype.cmpn=function(e){var i=e<0;if(this.negative!==0&&!i)return-1;if(this.negative===0&&i)return 1;this.strip();var s;if(this.length>1)s=1;else{i&&(e=-e),h(e<=67108863,"Number is too big");var o=this.words[0]|0;s=o===e?0:oe.length)return 1;if(this.length=0;s--){var o=this.words[s]|0,l=e.words[s]|0;if(o!==l){ol&&(i=1);break}}return i},a.prototype.gtn=function(e){return this.cmpn(e)===1},a.prototype.gt=function(e){return this.cmp(e)===1},a.prototype.gten=function(e){return this.cmpn(e)>=0},a.prototype.gte=function(e){return this.cmp(e)>=0},a.prototype.ltn=function(e){return this.cmpn(e)===-1},a.prototype.lt=function(e){return this.cmp(e)===-1},a.prototype.lten=function(e){return this.cmpn(e)<=0},a.prototype.lte=function(e){return this.cmp(e)<=0},a.prototype.eqn=function(e){return this.cmpn(e)===0},a.prototype.eq=function(e){return this.cmp(e)===0},a.red=function(e){return new q(e)},a.prototype.toRed=function(e){return h(!this.red,"Already a number in reduction context"),h(this.negative===0,"red works only with positives"),e.convertTo(this)._forceRed(e)},a.prototype.fromRed=function(){return h(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},a.prototype._forceRed=function(e){return this.red=e,this},a.prototype.forceRed=function(e){return h(!this.red,"Already a number in reduction context"),this._forceRed(e)},a.prototype.redAdd=function(e){return h(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},a.prototype.redIAdd=function(e){return h(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},a.prototype.redSub=function(e){return h(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},a.prototype.redISub=function(e){return h(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},a.prototype.redShl=function(e){return h(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},a.prototype.redMul=function(e){return h(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},a.prototype.redIMul=function(e){return h(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},a.prototype.redSqr=function(){return h(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},a.prototype.redISqr=function(){return h(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},a.prototype.redSqrt=function(){return h(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},a.prototype.redInvm=function(){return h(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},a.prototype.redNeg=function(){return h(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},a.prototype.redPow=function(e){return h(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var Me={k256:null,p224:null,p192:null,p25519:null};function k(v,e){this.name=v,this.p=new a(e,16),this.n=this.p.bitLength(),this.k=new a(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}k.prototype._tmp=function(){var e=new a(null);return e.words=new Array(Math.ceil(this.n/13)),e},k.prototype.ireduce=function(e){var i=e,s;do this.split(i,this.tmp),i=this.imulK(i),i=i.iadd(this.tmp),s=i.bitLength();while(s>this.n);var o=s0?i.isub(this.p):i.strip!==void 0?i.strip():i._strip(),i},k.prototype.split=function(e,i){e.iushrn(this.n,0,i)},k.prototype.imulK=function(e){return e.imul(this.k)};function Ae(){k.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}d(Ae,k),Ae.prototype.split=function(e,i){for(var s=4194303,o=Math.min(e.length,9),l=0;l>>22,b=p}b>>>=22,e.words[l-10]=b,b===0&&e.length>10?e.length-=10:e.length-=9},Ae.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var i=0,s=0;s>>=26,e.words[s]=l,i=o}return i!==0&&(e.words[e.length++]=i),e},a._prime=function(e){if(Me[e])return Me[e];var i;if(e==="k256")i=new Ae;else if(e==="p224")i=new Ie;else if(e==="p192")i=new Ee;else if(e==="p25519")i=new Le;else throw new Error("Unknown prime "+e);return Me[e]=i,i};function q(v){if(typeof v=="string"){var e=a._prime(v);this.m=e.p,this.prime=e}else h(v.gtn(1),"modulus must be greater than 1"),this.m=v,this.prime=null}q.prototype._verify1=function(e){h(e.negative===0,"red works only with positives"),h(e.red,"red works only with red numbers")},q.prototype._verify2=function(e,i){h((e.negative|i.negative)===0,"red works only with positives"),h(e.red&&e.red===i.red,"red works only with red numbers")},q.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},q.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},q.prototype.add=function(e,i){this._verify2(e,i);var s=e.add(i);return s.cmp(this.m)>=0&&s.isub(this.m),s._forceRed(this)},q.prototype.iadd=function(e,i){this._verify2(e,i);var s=e.iadd(i);return s.cmp(this.m)>=0&&s.isub(this.m),s},q.prototype.sub=function(e,i){this._verify2(e,i);var s=e.sub(i);return s.cmpn(0)<0&&s.iadd(this.m),s._forceRed(this)},q.prototype.isub=function(e,i){this._verify2(e,i);var s=e.isub(i);return s.cmpn(0)<0&&s.iadd(this.m),s},q.prototype.shl=function(e,i){return this._verify1(e),this.imod(e.ushln(i))},q.prototype.imul=function(e,i){return this._verify2(e,i),this.imod(e.imul(i))},q.prototype.mul=function(e,i){return this._verify2(e,i),this.imod(e.mul(i))},q.prototype.isqr=function(e){return this.imul(e,e.clone())},q.prototype.sqr=function(e){return this.mul(e,e)},q.prototype.sqrt=function(e){if(e.isZero())return e.clone();var i=this.m.andln(3);if(h(i%2===1),i===3){var s=this.m.add(new a(1)).iushrn(2);return this.pow(e,s)}for(var o=this.m.subn(1),l=0;!o.isZero()&&o.andln(1)===0;)l++,o.iushrn(1);h(!o.isZero());var b=new a(1).toRed(this),p=b.redNeg(),u=this.m.subn(1).iushrn(1),r=this.m.bitLength();for(r=new a(2*r*r).toRed(this);this.pow(r,u).cmp(p)!==0;)r.redIAdd(p);for(var c=this.pow(r,o),I=this.pow(e,o.addn(1).iushrn(1)),S=this.pow(e,o),L=l;S.cmp(b)!==0;){for(var B=S,z=0;B.cmp(b)!==0;z++)B=B.redSqr();h(z=0;l--){for(var c=i.words[l],I=r-1;I>=0;I--){var S=c>>I&1;if(b!==o[0]&&(b=this.sqr(b)),S===0&&p===0){u=0;continue}p<<=1,p|=S,u++,!(u!==s&&(l!==0||I!==0))&&(b=this.mul(b,o[p]),u=0,p=0)}r=26}return b},q.prototype.convertTo=function(e){var i=e.umod(this.m);return i===e?i.clone():i},q.prototype.convertFrom=function(e){var i=e.clone();return i.red=null,i},a.mont=function(e){return new Be(e)};function Be(v){q.call(this,v),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new a(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}d(Be,q),Be.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},Be.prototype.convertFrom=function(e){var i=this.imod(e.mul(this.rinv));return i.red=null,i},Be.prototype.imul=function(e,i){if(e.isZero()||i.isZero())return e.words[0]=0,e.length=1,e;var s=e.imul(i),o=s.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),l=s.isub(o).iushrn(this.shift),b=l;return l.cmp(this.m)>=0?b=l.isub(this.m):l.cmpn(0)<0&&(b=l.iadd(this.m)),b._forceRed(this)},Be.prototype.mul=function(e,i){if(e.isZero()||i.isZero())return new a(0)._forceRed(this);var s=e.mul(i),o=s.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),l=s.isub(o).iushrn(this.shift),b=l;return l.cmp(this.m)>=0?b=l.isub(this.m):l.cmpn(0)<0&&(b=l.iadd(this.m)),b._forceRed(this)},Be.prototype.invm=function(e){var i=this.imod(e._invmp(this.m).mul(this.r2));return i._forceRed(this)}})(f,af)})(z0);var Wh=z0.exports;(function(f){var t=ut.Buffer,n=L0,h=Wh,d=lf.ec,a=Of,m=new d("secp256k1"),x=m.curve;function _(g,M){var w=new h(M);if(w.cmp(x.p)>=0)return null;w=w.toRed(x.red);var E=w.redSqr().redIMul(w).redIAdd(x.b).redSqrt();g===3!==E.isOdd()&&(E=E.redNeg());const P=w.redSqr().redIMul(w);return E.redSqr().redISub(P.redIAdd(x.b)).isZero()?m.keyPair({pub:{x:w,y:E}}):null}function A(g,M,w){var E=new h(M),P=new h(w);if(E.cmp(x.p)>=0||P.cmp(x.p)>=0||(E=E.toRed(x.red),P=P.toRed(x.red),(g===6||g===7)&&P.isOdd()!==(g===7)))return null;var N=E.redSqr().redIMul(E);return P.redSqr().redISub(N.redIAdd(x.b)).isZero()?m.keyPair({pub:{x:E,y:P}}):null}function y(g){var M=g[0];switch(M){case 2:case 3:return g.length!==33?null:_(M,g.slice(1,33));case 4:case 6:case 7:return g.length!==65?null:A(M,g.slice(1,33),g.slice(33,65));default:return null}}f.privateKeyVerify=function(g){var M=new h(g);return M.cmp(x.n)<0&&!M.isZero()},f.privateKeyExport=function(g,M){var w=new h(g);if(w.cmp(x.n)>=0||w.isZero())throw new Error(a.EC_PRIVATE_KEY_EXPORT_DER_FAIL);return t.from(m.keyFromPrivate(g).getPublic(M,!0))},f.privateKeyNegate=function(g){var M=new h(g);return M.isZero()?t.alloc(32):x.n.sub(M).umod(x.n).toArrayLike(t,"be",32)},f.privateKeyModInverse=function(g){var M=new h(g);if(M.cmp(x.n)>=0||M.isZero())throw new Error(a.EC_PRIVATE_KEY_RANGE_INVALID);return M.invm(x.n).toArrayLike(t,"be",32)},f.privateKeyTweakAdd=function(g,M){var w=new h(M);if(w.cmp(x.n)>=0)throw new Error(a.EC_PRIVATE_KEY_TWEAK_ADD_FAIL);if(w.iadd(new h(g)),w.cmp(x.n)>=0&&w.isub(x.n),w.isZero())throw new Error(a.EC_PRIVATE_KEY_TWEAK_ADD_FAIL);return w.toArrayLike(t,"be",32)},f.privateKeyTweakMul=function(g,M){var w=new h(M);if(w.cmp(x.n)>=0||w.isZero())throw new Error(a.EC_PRIVATE_KEY_TWEAK_MUL_FAIL);return w.imul(new h(g)),w.cmp(x.n)&&(w=w.umod(x.n)),w.toArrayLike(t,"be",32)},f.publicKeyCreate=function(g,M){var w=new h(g);if(w.cmp(x.n)>=0||w.isZero())throw new Error(a.EC_PUBLIC_KEY_CREATE_FAIL);return t.from(m.keyFromPrivate(g).getPublic(M,!0))},f.publicKeyConvert=function(g,M){var w=y(g);if(w===null)throw new Error(a.EC_PUBLIC_KEY_PARSE_FAIL);return t.from(w.getPublic(M,!0))},f.publicKeyVerify=function(g){return y(g)!==null},f.publicKeyTweakAdd=function(g,M,w){var E=y(g);if(E===null)throw new Error(a.EC_PUBLIC_KEY_PARSE_FAIL);if(M=new h(M),M.cmp(x.n)>=0)throw new Error(a.EC_PUBLIC_KEY_TWEAK_ADD_FAIL);var P=x.g.mul(M).add(E.pub);if(P.isInfinity())throw new Error(a.EC_PUBLIC_KEY_TWEAK_ADD_FAIL);return t.from(P.encode(!0,w))},f.publicKeyTweakMul=function(g,M,w){var E=y(g);if(E===null)throw new Error(a.EC_PUBLIC_KEY_PARSE_FAIL);if(M=new h(M),M.cmp(x.n)>=0||M.isZero())throw new Error(a.EC_PUBLIC_KEY_TWEAK_MUL_FAIL);return t.from(E.pub.mul(M).encode(!0,w))},f.publicKeyCombine=function(g,M){for(var w=new Array(g.length),E=0;E=0||w.cmp(x.n)>=0)throw new Error(a.ECDSA_SIGNATURE_PARSE_FAIL);var E=t.from(g);return w.cmp(m.nh)===1&&x.n.sub(w).toArrayLike(t,"be",32).copy(E,32),E},f.signatureExport=function(g){var M=g.slice(0,32),w=g.slice(32,64);if(new h(M).cmp(x.n)>=0||new h(w).cmp(x.n)>=0)throw new Error(a.ECDSA_SIGNATURE_PARSE_FAIL);return{r:M,s:w}},f.signatureImport=function(g){var M=new h(g.r);M.cmp(x.n)>=0&&(M=new h(0));var w=new h(g.s);return w.cmp(x.n)>=0&&(w=new h(0)),t.concat([M.toArrayLike(t,"be",32),w.toArrayLike(t,"be",32)])},f.sign=function(g,M,w,E){if(typeof w=="function"){var P=w;w=function(D){var Me=P(g,M,null,E,D);if(!t.isBuffer(Me)||Me.length!==32)throw new Error(a.ECDSA_SIGN_FAIL);return new h(Me)}}var N=new h(M);if(N.cmp(x.n)>=0||N.isZero())throw new Error(a.ECDSA_SIGN_FAIL);var R=m.sign(g,M,{canonical:!0,k:w,pers:E});return{signature:t.concat([R.r.toArrayLike(t,"be",32),R.s.toArrayLike(t,"be",32)]),recovery:R.recoveryParam}},f.verify=function(g,M,w){var E={r:M.slice(0,32),s:M.slice(32,64)},P=new h(E.r),N=new h(E.s);if(P.cmp(x.n)>=0||N.cmp(x.n)>=0)throw new Error(a.ECDSA_SIGNATURE_PARSE_FAIL);if(N.cmp(m.nh)===1||P.isZero()||N.isZero())return!1;var R=y(w);if(R===null)throw new Error(a.EC_PUBLIC_KEY_PARSE_FAIL);return m.verify(g,E,{x:R.pub.x,y:R.pub.y})},f.recover=function(g,M,w,E){var P={r:M.slice(0,32),s:M.slice(32,64)},N=new h(P.r),R=new h(P.s);if(N.cmp(x.n)>=0||R.cmp(x.n)>=0)throw new Error(a.ECDSA_SIGNATURE_PARSE_FAIL);try{if(N.isZero()||R.isZero())throw new Error;var D=m.recoverPubKey(g,P,w);return t.from(D.encode(!0,E))}catch{throw new Error(a.ECDSA_RECOVER_FAIL)}},f.ecdh=function(g,M){var w=f.ecdhUnsafe(g,M,!0);return n("sha256").update(w).digest()},f.ecdhUnsafe=function(g,M,w){var E=y(g);if(E===null)throw new Error(a.EC_PUBLIC_KEY_PARSE_FAIL);var P=new h(M);if(P.cmp(x.n)>=0||P.isZero())throw new Error(a.ECDH_FAIL);return t.from(E.pub.mul(P).encode(!0,w))}})(Ff);var Jh=Zh(Ff);const _0=Jn,ef=ih,Yr=ah,Kf=L0,q0=Jh,tf=ii,xt={P2WPKH:"p2wpkh",P2SH_P2WPKH:"p2sh(p2wpkh)"};function I0(f){return Kf("sha256").update(f).digest()}function Xh(f){return I0(I0(f))}function Hf(f){return Kf("ripemd160").update(I0(f)).digest()}function Gf(f,t,n,h){return h!==void 0?(t+=8,h===xt.P2WPKH&&(t+=4)):n&&(t+=4),Buffer.concat([Buffer.alloc(1,t+27),f])}function Qh(f){if(f.length!==65)throw new Error("Invalid signature length");const t=f.readUInt8(0)-27;if(t>15||t<0)throw new Error("Invalid signature parameter");return{compressed:!!(t&12),segwitType:t&8?t&4?xt.P2WPKH:xt.P2SH_P2WPKH:null,recovery:t&3,signature:f.slice(1)}}function s0(f,t){t=t||`Bitcoin Signed Message: +`,Buffer.isBuffer(t)||(t=Buffer.from(t,"utf8")),Buffer.isBuffer(f)||(f=Buffer.from(f,"utf8"));const n=tf.encodingLength(f.length),h=Buffer.allocUnsafe(t.length+n+f.length);return t.copy(h,0),tf.encode(f.length,h,t.length),f.copy(h,t.length+n),Xh(h)}function Zf(f,t){typeof f=="object"&&t===void 0&&(t=f,f=void 0);let{segwitType:n,extraEntropy:h}=t||{};if(n&&(typeof n=="string"||n instanceof String)&&(n=n.toLowerCase()),n&&n!==xt.P2SH_P2WPKH&&n!==xt.P2WPKH)throw new Error('Unrecognized segwitType: use "'+xt.P2SH_P2WPKH+'" or "'+xt.P2WPKH+'"');return{messagePrefixArg:f,segwitType:n,extraEntropy:h}}function Wf(f){return f&&typeof f.sign=="function"}function jh(f,t,n,h,d){const{messagePrefixArg:a,segwitType:m,extraEntropy:x}=Zf(h,d),_=s0(f,a),A=Wf(t)?t.sign(_,x):q0.sign(_,t,{data:x});return Gf(A.signature,A.recovery,n,m)}function es(f,t,n,h,d){let a,m,x;return Promise.resolve().then(()=>{({messagePrefixArg:a,segwitType:m,extraEntropy:x}=Zf(h,d));const _=s0(f,a);return Wf(t)?t.sign(_,x):q0.sign(_,t,{data:x})}).then(_=>Gf(_.signature,_.recovery,n,m))}function rf(f){const t=Buffer.concat([Buffer.from("0014","hex"),f]);return Hf(t)}function ff(f){const t=ef.decode(f),n=ef.fromWords(t.words.slice(1));return Buffer.from(n)}function ts(f,t,n,h,d){Buffer.isBuffer(n)||(n=Buffer.from(n,"base64"));const a=Qh(n);if(d&&!a.compressed)throw new Error("checkSegwitAlways can only be used with a compressed pubkey signature flagbyte");const m=s0(f,h),x=q0.recover(m,a.signature,a.recovery,a.compressed),_=Hf(x);let A,y;if(a.segwitType)a.segwitType===xt.P2SH_P2WPKH?(A=rf(_),y=_0.decode(t).slice(1)):(A=_,y=ff(t));else if(d)try{return y=ff(t),Yr(_,y)}catch{const M=rf(_);return y=_0.decode(t).slice(1),Yr(_,y)||Yr(M,y)}else A=_,y=_0.decode(t).slice(1);return Yr(A,y)}var Jf={magicHash:s0,sign:jh,signAsync:es,verify:ts};const rs=Qf(Jf),as=ri({__proto__:null,default:rs},[Jf]);export{as as i}; diff --git a/dist/assets/index-Cr5N_0pd.js b/dist/assets/index-Cr5N_0pd.js new file mode 100644 index 0000000..567f492 --- /dev/null +++ b/dist/assets/index-Cr5N_0pd.js @@ -0,0 +1,8205 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/swaps-2zeCrlxq.js","assets/index-DUeQylCA.js","assets/send-Ncb2jADE.js","assets/ui-CTdGiFlJ.js","assets/email-OHUMhOV6.js","assets/index-CqL7mnh0.js","assets/index-COonna6N.js"])))=>i.map(i=>d[i]); +function ZAe(t,e){for(var n=0;nr[s]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var kr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Zi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Zy(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}),n}var Pse={exports:{}},G4={},kse={exports:{}},Hn={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var TS=Symbol.for("react.element"),YAe=Symbol.for("react.portal"),XAe=Symbol.for("react.fragment"),QAe=Symbol.for("react.strict_mode"),JAe=Symbol.for("react.profiler"),eIe=Symbol.for("react.provider"),tIe=Symbol.for("react.context"),nIe=Symbol.for("react.forward_ref"),rIe=Symbol.for("react.suspense"),sIe=Symbol.for("react.memo"),iIe=Symbol.for("react.lazy"),EG=Symbol.iterator;function oIe(t){return t===null||typeof t!="object"?null:(t=EG&&t[EG]||t["@@iterator"],typeof t=="function"?t:null)}var Rse={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ose=Object.assign,$se={};function U1(t,e,n){this.props=t,this.context=e,this.refs=$se,this.updater=n||Rse}U1.prototype.isReactComponent={};U1.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};U1.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Dse(){}Dse.prototype=U1.prototype;function qU(t,e,n){this.props=t,this.context=e,this.refs=$se,this.updater=n||Rse}var KU=qU.prototype=new Dse;KU.constructor=qU;Ose(KU,U1.prototype);KU.isPureReactComponent=!0;var CG=Array.isArray,Mse=Object.prototype.hasOwnProperty,GU={current:null},Lse={key:!0,ref:!0,__self:!0,__source:!0};function Bse(t,e,n){var r,s={},i=null,o=null;if(e!=null)for(r in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(i=""+e.key),e)Mse.call(e,r)&&!Lse.hasOwnProperty(r)&&(s[r]=e[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,re=L[Y];if(0>>1;Ys(ve,H))Ees(oe,ve)?(L[Y]=oe,L[Ee]=H,Y=Ee):(L[Y]=ve,L[fe]=H,Y=fe);else if(Ees(oe,H))L[Y]=oe,L[Ee]=H,Y=Ee;else break e}}return P}function s(L,P){var H=L.sortIndex-P.sortIndex;return H!==0?H:L.id-P.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;t.unstable_now=function(){return i.now()}}else{var o=Date,a=o.now();t.unstable_now=function(){return o.now()-a}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(L){for(var P=n(l);P!==null;){if(P.callback===null)r(l);else if(P.startTime<=L)r(l),P.sortIndex=P.expirationTime,e(c,P);else break;P=n(l)}}function A(L){if(y=!1,E(L),!m)if(n(c)!==null)m=!0,T(_);else{var P=n(l);P!==null&&U(A,P.startTime-L)}}function _(L,P){m=!1,y&&(y=!1,v(W),W=-1),p=!0;var H=f;try{for(E(P),d=n(c);d!==null&&(!(d.expirationTime>P)||L&&!R());){var Y=d.callback;if(typeof Y=="function"){d.callback=null,f=d.priorityLevel;var re=Y(d.expirationTime<=P);P=t.unstable_now(),typeof re=="function"?d.callback=re:d===n(c)&&r(c),E(P)}else r(c);d=n(c)}if(d!==null)var de=!0;else{var fe=n(l);fe!==null&&U(A,fe.startTime-P),de=!1}return de}finally{d=null,f=H,p=!1}}var k=!1,B=null,W=-1,S=5,$=-1;function R(){return!(t.unstable_now()-$L||125Y?(L.sortIndex=H,e(l,L),n(c)===null&&L===n(l)&&(y?(v(W),W=-1):y=!0,U(A,H-Y))):(L.sortIndex=re,e(c,L),m||p||(m=!0,T(_))),L},t.unstable_shouldYield=R,t.unstable_wrapCallback=function(L){var P=f;return function(){var H=f;f=P;try{return L.apply(this,arguments)}finally{f=H}}}})(Vse);Wse.exports=Vse;var yIe=Wse.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var wIe=I,Uc=yIe;function at(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),J9=Object.prototype.hasOwnProperty,bIe=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,SG={},AG={};function vIe(t){return J9.call(AG,t)?!0:J9.call(SG,t)?!1:bIe.test(t)?AG[t]=!0:(SG[t]=!0,!1)}function xIe(t,e,n,r){if(n!==null&&n.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function EIe(t,e,n,r){if(e===null||typeof e>"u"||xIe(t,e,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function la(t,e,n,r,s,i,o){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=t,this.type=e,this.sanitizeURL=i,this.removeEmptyString=o}var qi={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){qi[t]=new la(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];qi[e]=new la(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){qi[t]=new la(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){qi[t]=new la(t,2,!1,t,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(t){qi[t]=new la(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){qi[t]=new la(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){qi[t]=new la(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){qi[t]=new la(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){qi[t]=new la(t,5,!1,t.toLowerCase(),null,!1,!1)});var YU=/[\-:]([a-z])/g;function XU(t){return t[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(t){var e=t.replace(YU,XU);qi[e]=new la(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(YU,XU);qi[e]=new la(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(YU,XU);qi[e]=new la(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){qi[t]=new la(t,1,!1,t.toLowerCase(),null,!1,!1)});qi.xlinkHref=new la("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){qi[t]=new la(t,1,!1,t.toLowerCase(),null,!0,!0)});function QU(t,e,n,r){var s=qi.hasOwnProperty(e)?qi[e]:null;(s!==null?s.type!==0:r||!(2a||s[o]!==i[a]){var c=` +`+s[o].replace(" at new "," at ");return t.displayName&&c.includes("")&&(c=c.replace("",t.displayName)),c}while(1<=o&&0<=a);break}}}finally{fO=!1,Error.prepareStackTrace=n}return(t=t?t.displayName||t.name:"")?$2(t):""}function CIe(t){switch(t.tag){case 5:return $2(t.type);case 16:return $2("Lazy");case 13:return $2("Suspense");case 19:return $2("SuspenseList");case 0:case 2:case 15:return t=hO(t.type,!1),t;case 11:return t=hO(t.type.render,!1),t;case 1:return t=hO(t.type,!0),t;default:return""}}function rM(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case Ib:return"Fragment";case Ab:return"Portal";case eM:return"Profiler";case JU:return"StrictMode";case tM:return"Suspense";case nM:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case Kse:return(t.displayName||"Context")+".Consumer";case qse:return(t._context.displayName||"Context")+".Provider";case eF:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case tF:return e=t.displayName||null,e!==null?e:rM(t.type)||"Memo";case lg:e=t._payload,t=t._init;try{return rM(t(e))}catch{}}return null}function _Ie(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return rM(e);case 8:return e===JU?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function n0(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function Zse(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function SIe(t){var e=Zse(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),r=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return s.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function F5(t){t._valueTracker||(t._valueTracker=SIe(t))}function Yse(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=Zse(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function C6(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function sM(t,e){var n=e.checked;return vs({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??t._wrapperState.initialChecked})}function TG(t,e){var n=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;n=n0(e.value!=null?e.value:n),t._wrapperState={initialChecked:r,initialValue:n,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function Xse(t,e){e=e.checked,e!=null&&QU(t,"checked",e,!1)}function iM(t,e){Xse(t,e);var n=n0(e.value),r=e.type;if(n!=null)r==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+n):t.value!==""+n&&(t.value=""+n);else if(r==="submit"||r==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?oM(t,e.type,n):e.hasOwnProperty("defaultValue")&&oM(t,e.type,n0(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function NG(t,e,n){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var r=e.type;if(!(r!=="submit"&&r!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,n||e===t.value||(t.value=e),t.defaultValue=e}n=t.name,n!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,n!==""&&(t.name=n)}function oM(t,e,n){(e!=="number"||C6(t.ownerDocument)!==t)&&(n==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+n&&(t.defaultValue=""+n))}var D2=Array.isArray;function Xb(t,e,n,r){if(t=t.options,e){e={};for(var s=0;s"+e.valueOf().toString()+"",e=j5.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function qE(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var iE={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},AIe=["Webkit","ms","Moz","O"];Object.keys(iE).forEach(function(t){AIe.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),iE[e]=iE[t]})});function tie(t,e,n){return e==null||typeof e=="boolean"||e===""?"":n||typeof e!="number"||e===0||iE.hasOwnProperty(t)&&iE[t]?(""+e).trim():e+"px"}function nie(t,e){t=t.style;for(var n in e)if(e.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=tie(n,e[n],r);n==="float"&&(n="cssFloat"),r?t.setProperty(n,s):t[n]=s}}var IIe=vs({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function lM(t,e){if(e){if(IIe[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(at(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(at(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(at(61))}if(e.style!=null&&typeof e.style!="object")throw Error(at(62))}}function uM(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var dM=null;function nF(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var fM=null,Qb=null,Jb=null;function RG(t){if(t=kS(t)){if(typeof fM!="function")throw Error(at(280));var e=t.stateNode;e&&(e=J4(e),fM(t.stateNode,t.type,e))}}function rie(t){Qb?Jb?Jb.push(t):Jb=[t]:Qb=t}function sie(){if(Qb){var t=Qb,e=Jb;if(Jb=Qb=null,RG(t),e)for(t=0;t>>=0,t===0?32:31-(BIe(t)/UIe|0)|0}var z5=64,W5=4194304;function M2(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function I6(t,e){var n=t.pendingLanes;if(n===0)return 0;var r=0,s=t.suspendedLanes,i=t.pingedLanes,o=n&268435455;if(o!==0){var a=o&~s;a!==0?r=M2(a):(i&=o,i!==0&&(r=M2(i)))}else o=n&~s,o!==0?r=M2(o):i!==0&&(r=M2(i));if(r===0)return 0;if(e!==0&&e!==r&&!(e&s)&&(s=r&-r,i=e&-e,s>=i||s===16&&(i&4194240)!==0))return e;if(r&4&&(r|=n&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=r;0n;n++)e.push(t);return e}function NS(t,e,n){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-ju(e),t[e]=n}function WIe(t,e){var n=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var r=t.eventTimes;for(t=t.expirationTimes;0=aE),jG=" ",zG=!1;function _ie(t,e){switch(t){case"keyup":return y6e.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Sie(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Tb=!1;function b6e(t,e){switch(t){case"compositionend":return Sie(e);case"keypress":return e.which!==32?null:(zG=!0,jG);case"textInput":return t=e.data,t===jG&&zG?null:t;default:return null}}function v6e(t,e){if(Tb)return t==="compositionend"||!uF&&_ie(t,e)?(t=Eie(),_I=aF=Ag=null,Tb=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:n,offset:e-t};t=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=qG(n)}}function Nie(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?Nie(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Pie(){for(var t=window,e=C6();e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=C6(t.document)}return e}function dF(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function N6e(t){var e=Pie(),n=t.focusedElem,r=t.selectionRange;if(e!==n&&n&&n.ownerDocument&&Nie(n.ownerDocument.documentElement,n)){if(r!==null&&dF(n)){if(e=r.start,t=r.end,t===void 0&&(t=e),"selectionStart"in n)n.selectionStart=e,n.selectionEnd=Math.min(t,n.value.length);else if(t=(e=n.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!t.extend&&i>r&&(s=r,r=i,i=s),s=KG(n,i);var o=KG(n,r);s&&o&&(t.rangeCount!==1||t.anchorNode!==s.node||t.anchorOffset!==s.offset||t.focusNode!==o.node||t.focusOffset!==o.offset)&&(e=e.createRange(),e.setStart(s.node,s.offset),t.removeAllRanges(),i>r?(t.addRange(e),t.extend(o.node,o.offset)):(e.setEnd(o.node,o.offset),t.addRange(e)))}}for(e=[],t=n;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Nb=null,wM=null,lE=null,bM=!1;function GG(t,e,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;bM||Nb==null||Nb!==C6(r)||(r=Nb,"selectionStart"in r&&dF(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),lE&&QE(lE,r)||(lE=r,r=P6(wM,"onSelect"),0Rb||(t.current=SM[Rb],SM[Rb]=null,Rb--)}function es(t,e){Rb++,SM[Rb]=t.current,t.current=e}var r0={},Io=T0(r0),Ha=T0(!1),Jm=r0;function _v(t,e){var n=t.type.contextTypes;if(!n)return r0;var r=t.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=e[i];return r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=s),s}function qa(t){return t=t.childContextTypes,t!=null}function R6(){as(Ha),as(Io)}function tZ(t,e,n){if(Io.current!==r0)throw Error(at(168));es(Io,e),es(Ha,n)}function Uie(t,e,n){var r=t.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in e))throw Error(at(108,_Ie(t)||"Unknown",s));return vs({},n,r)}function O6(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||r0,Jm=Io.current,es(Io,t),es(Ha,Ha.current),!0}function nZ(t,e,n){var r=t.stateNode;if(!r)throw Error(at(169));n?(t=Uie(t,e,Jm),r.__reactInternalMemoizedMergedChildContext=t,as(Ha),as(Io),es(Io,t)):as(Ha),es(Ha,n)}var uh=null,eP=!1,IO=!1;function Fie(t){uh===null?uh=[t]:uh.push(t)}function j6e(t){eP=!0,Fie(t)}function N0(){if(!IO&&uh!==null){IO=!0;var t=0,e=Mr;try{var n=uh;for(Mr=1;t>=o,s-=o,mh=1<<32-ju(e)+s|n<W?(S=B,B=null):S=B.sibling;var $=f(v,B,E[W],A);if($===null){B===null&&(B=S);break}t&&B&&$.alternate===null&&e(v,B),x=i($,x,W),k===null?_=$:k.sibling=$,k=$,B=S}if(W===E.length)return n(v,B),hs&&sm(v,W),_;if(B===null){for(;WW?(S=B,B=null):S=B.sibling;var R=f(v,B,$.value,A);if(R===null){B===null&&(B=S);break}t&&B&&R.alternate===null&&e(v,B),x=i(R,x,W),k===null?_=R:k.sibling=R,k=R,B=S}if($.done)return n(v,B),hs&&sm(v,W),_;if(B===null){for(;!$.done;W++,$=E.next())$=d(v,$.value,A),$!==null&&(x=i($,x,W),k===null?_=$:k.sibling=$,k=$);return hs&&sm(v,W),_}for(B=r(v,B);!$.done;W++,$=E.next())$=p(B,v,W,$.value,A),$!==null&&(t&&$.alternate!==null&&B.delete($.key===null?W:$.key),x=i($,x,W),k===null?_=$:k.sibling=$,k=$);return t&&B.forEach(function(M){return e(v,M)}),hs&&sm(v,W),_}function b(v,x,E,A){if(typeof E=="object"&&E!==null&&E.type===Ib&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case U5:e:{for(var _=E.key,k=x;k!==null;){if(k.key===_){if(_=E.type,_===Ib){if(k.tag===7){n(v,k.sibling),x=s(k,E.props.children),x.return=v,v=x;break e}}else if(k.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===lg&&iZ(_)===k.type){n(v,k.sibling),x=s(k,E.props),x.ref=qx(v,k,E),x.return=v,v=x;break e}n(v,k);break}else e(v,k);k=k.sibling}E.type===Ib?(x=Um(E.props.children,v.mode,A,E.key),x.return=v,v=x):(A=RI(E.type,E.key,E.props,null,v.mode,A),A.ref=qx(v,x,E),A.return=v,v=A)}return o(v);case Ab:e:{for(k=E.key;x!==null;){if(x.key===k)if(x.tag===4&&x.stateNode.containerInfo===E.containerInfo&&x.stateNode.implementation===E.implementation){n(v,x.sibling),x=s(x,E.children||[]),x.return=v,v=x;break e}else{n(v,x);break}else e(v,x);x=x.sibling}x=DO(E,v.mode,A),x.return=v,v=x}return o(v);case lg:return k=E._init,b(v,x,k(E._payload),A)}if(D2(E))return m(v,x,E,A);if(jx(E))return y(v,x,E,A);Y5(v,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,x!==null&&x.tag===6?(n(v,x.sibling),x=s(x,E),x.return=v,v=x):(n(v,x),x=$O(E,v.mode,A),x.return=v,v=x),o(v)):n(v,x)}return b}var Av=Vie(!0),Hie=Vie(!1),M6=T0(null),L6=null,Db=null,gF=null;function mF(){gF=Db=L6=null}function yF(t){var e=M6.current;as(M6),t._currentValue=e}function TM(t,e,n){for(;t!==null;){var r=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),t===n)break;t=t.return}}function tv(t,e){L6=t,gF=Db=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Fa=!0),t.firstContext=null)}function Ul(t){var e=t._currentValue;if(gF!==t)if(t={context:t,memoizedValue:e,next:null},Db===null){if(L6===null)throw Error(at(308));Db=t,L6.dependencies={lanes:0,firstContext:t}}else Db=Db.next=t;return e}var gm=null;function wF(t){gm===null?gm=[t]:gm.push(t)}function qie(t,e,n,r){var s=e.interleaved;return s===null?(n.next=n,wF(e)):(n.next=s.next,s.next=n),e.interleaved=n,Bh(t,r)}function Bh(t,e){t.lanes|=e;var n=t.alternate;for(n!==null&&(n.lanes|=e),n=t,t=t.return;t!==null;)t.childLanes|=e,n=t.alternate,n!==null&&(n.childLanes|=e),n=t,t=t.return;return n.tag===3?n.stateNode:null}var ug=!1;function bF(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Kie(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function Sh(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function jg(t,e,n){var r=t.updateQueue;if(r===null)return null;if(r=r.shared,ar&2){var s=r.pending;return s===null?e.next=e:(e.next=s.next,s.next=e),r.pending=e,Bh(t,n)}return s=r.interleaved,s===null?(e.next=e,wF(r)):(e.next=s.next,s.next=e),r.interleaved=e,Bh(t,n)}function AI(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194240)!==0)){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,sF(t,n)}}function oZ(t,e){var n=t.updateQueue,r=t.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?s=i=e:i=i.next=e}else s=i=e;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}function B6(t,e,n,r){var s=t.updateQueue;ug=!1;var i=s.firstBaseUpdate,o=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var c=a,l=c.next;c.next=null,o===null?i=l:o.next=l,o=c;var u=t.alternate;u!==null&&(u=u.updateQueue,a=u.lastBaseUpdate,a!==o&&(a===null?u.firstBaseUpdate=l:a.next=l,u.lastBaseUpdate=c))}if(i!==null){var d=s.baseState;o=0,u=l=c=null,a=i;do{var f=a.lane,p=a.eventTime;if((r&f)===f){u!==null&&(u=u.next={eventTime:p,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var m=t,y=a;switch(f=e,p=n,y.tag){case 1:if(m=y.payload,typeof m=="function"){d=m.call(p,d,f);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=y.payload,f=typeof m=="function"?m.call(p,d,f):m,f==null)break e;d=vs({},d,f);break e;case 2:ug=!0}}a.callback!==null&&a.lane!==0&&(t.flags|=64,f=s.effects,f===null?s.effects=[a]:f.push(a))}else p={eventTime:p,lane:f,tag:a.tag,payload:a.payload,callback:a.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;f=a,a=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);if(u===null&&(c=d),s.baseState=c,s.firstBaseUpdate=l,s.lastBaseUpdate=u,e=s.shared.interleaved,e!==null){s=e;do o|=s.lane,s=s.next;while(s!==e)}else i===null&&(s.shared.lanes=0);ny|=o,t.lanes=o,t.memoizedState=d}}function aZ(t,e,n){if(t=e.effects,e.effects=null,t!==null)for(e=0;en?n:4,t(!0);var r=NO.transition;NO.transition={};try{t(!1),e()}finally{Mr=n,NO.transition=r}}function uoe(){return Fl().memoizedState}function H6e(t,e,n){var r=Wg(t);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},doe(t))foe(e,n);else if(n=qie(t,e,n,r),n!==null){var s=ea();zu(n,t,r,s),hoe(n,e,r)}}function q6e(t,e,n){var r=Wg(t),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(doe(t))foe(e,s);else{var i=t.alternate;if(t.lanes===0&&(i===null||i.lanes===0)&&(i=e.lastRenderedReducer,i!==null))try{var o=e.lastRenderedState,a=i(o,n);if(s.hasEagerState=!0,s.eagerState=a,Ju(a,o)){var c=e.interleaved;c===null?(s.next=s,wF(e)):(s.next=c.next,c.next=s),e.interleaved=s;return}}catch{}finally{}n=qie(t,e,s,r),n!==null&&(s=ea(),zu(n,t,r,s),hoe(n,e,r))}}function doe(t){var e=t.alternate;return t===ws||e!==null&&e===ws}function foe(t,e){uE=F6=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function hoe(t,e,n){if(n&4194240){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,sF(t,n)}}var j6={readContext:Ul,useCallback:ro,useContext:ro,useEffect:ro,useImperativeHandle:ro,useInsertionEffect:ro,useLayoutEffect:ro,useMemo:ro,useReducer:ro,useRef:ro,useState:ro,useDebugValue:ro,useDeferredValue:ro,useTransition:ro,useMutableSource:ro,useSyncExternalStore:ro,useId:ro,unstable_isNewReconciler:!1},K6e={readContext:Ul,useCallback:function(t,e){return Dd().memoizedState=[t,e===void 0?null:e],t},useContext:Ul,useEffect:lZ,useImperativeHandle:function(t,e,n){return n=n!=null?n.concat([t]):null,TI(4194308,4,ioe.bind(null,e,t),n)},useLayoutEffect:function(t,e){return TI(4194308,4,t,e)},useInsertionEffect:function(t,e){return TI(4,2,t,e)},useMemo:function(t,e){var n=Dd();return e=e===void 0?null:e,t=t(),n.memoizedState=[t,e],t},useReducer:function(t,e,n){var r=Dd();return e=n!==void 0?n(e):e,r.memoizedState=r.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},r.queue=t,t=t.dispatch=H6e.bind(null,ws,t),[r.memoizedState,t]},useRef:function(t){var e=Dd();return t={current:t},e.memoizedState=t},useState:cZ,useDebugValue:IF,useDeferredValue:function(t){return Dd().memoizedState=t},useTransition:function(){var t=cZ(!1),e=t[0];return t=V6e.bind(null,t[1]),Dd().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,n){var r=ws,s=Dd();if(hs){if(n===void 0)throw Error(at(407));n=n()}else{if(n=e(),bi===null)throw Error(at(349));ty&30||Xie(r,e,n)}s.memoizedState=n;var i={value:n,getSnapshot:e};return s.queue=i,lZ(Jie.bind(null,r,i,t),[t]),r.flags|=2048,oC(9,Qie.bind(null,r,i,n,e),void 0,null),n},useId:function(){var t=Dd(),e=bi.identifierPrefix;if(hs){var n=yh,r=mh;n=(r&~(1<<32-ju(r)-1)).toString(32)+n,e=":"+e+"R"+n,n=sC++,0<\/script>",t=t.removeChild(t.firstChild)):typeof r.is=="string"?t=o.createElement(n,{is:r.is}):(t=o.createElement(n),n==="select"&&(o=t,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):t=o.createElementNS(t,n),t[zd]=e,t[tC]=r,Coe(t,e,!1,!1),e.stateNode=t;e:{switch(o=uM(n,r),n){case"dialog":ss("cancel",t),ss("close",t),s=r;break;case"iframe":case"object":case"embed":ss("load",t),s=r;break;case"video":case"audio":for(s=0;sNv&&(e.flags|=128,r=!0,Kx(i,!1),e.lanes=4194304)}else{if(!r)if(t=U6(o),t!==null){if(e.flags|=128,r=!0,n=t.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),Kx(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!hs)return so(e),null}else 2*Os()-i.renderingStartTime>Nv&&n!==1073741824&&(e.flags|=128,r=!0,Kx(i,!1),e.lanes=4194304);i.isBackwards?(o.sibling=e.child,e.child=o):(n=i.last,n!==null?n.sibling=o:e.child=o,i.last=o)}return i.tail!==null?(e=i.tail,i.rendering=e,i.tail=e.sibling,i.renderingStartTime=Os(),e.sibling=null,n=ys.current,es(ys,r?n&1|2:n&1),e):(so(e),null);case 22:case 23:return OF(),r=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==r&&(e.flags|=8192),r&&e.mode&1?Ac&1073741824&&(so(e),e.subtreeFlags&6&&(e.flags|=8192)):so(e),null;case 24:return null;case 25:return null}throw Error(at(156,e.tag))}function tTe(t,e){switch(hF(e),e.tag){case 1:return qa(e.type)&&R6(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return Iv(),as(Ha),as(Io),EF(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return xF(e),null;case 13:if(as(ys),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(at(340));Sv()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return as(ys),null;case 4:return Iv(),null;case 10:return yF(e.type._context),null;case 22:case 23:return OF(),null;case 24:return null;default:return null}}var Q5=!1,_o=!1,nTe=typeof WeakSet=="function"?WeakSet:Set,Ot=null;function Mb(t,e){var n=t.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Cs(t,e,r)}else n.current=null}function LM(t,e,n){try{n()}catch(r){Cs(t,e,r)}}var vZ=!1;function rTe(t,e){if(vM=T6,t=Pie(),dF(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,a=-1,c=-1,l=0,u=0,d=t,f=null;t:for(;;){for(var p;d!==n||s!==0&&d.nodeType!==3||(a=o+s),d!==i||r!==0&&d.nodeType!==3||(c=o+r),d.nodeType===3&&(o+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===t)break t;if(f===n&&++l===s&&(a=o),f===i&&++u===r&&(c=o),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}n=a===-1||c===-1?null:{start:a,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(xM={focusedElem:t,selectionRange:n},T6=!1,Ot=e;Ot!==null;)if(e=Ot,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,Ot=t;else for(;Ot!==null;){e=Ot;try{var m=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var y=m.memoizedProps,b=m.memoizedState,v=e.stateNode,x=v.getSnapshotBeforeUpdate(e.elementType===e.type?y:Iu(e.type,y),b);v.__reactInternalSnapshotBeforeUpdate=x}break;case 3:var E=e.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(at(163))}}catch(A){Cs(e,e.return,A)}if(t=e.sibling,t!==null){t.return=e.return,Ot=t;break}Ot=e.return}return m=vZ,vZ=!1,m}function dE(t,e,n){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&t)===t){var i=s.destroy;s.destroy=void 0,i!==void 0&&LM(e,n,i)}s=s.next}while(s!==r)}}function rP(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var n=e=e.next;do{if((n.tag&t)===t){var r=n.create;n.destroy=r()}n=n.next}while(n!==e)}}function BM(t){var e=t.ref;if(e!==null){var n=t.stateNode;switch(t.tag){case 5:t=n;break;default:t=n}typeof e=="function"?e(t):e.current=t}}function Aoe(t){var e=t.alternate;e!==null&&(t.alternate=null,Aoe(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[zd],delete e[tC],delete e[_M],delete e[U6e],delete e[F6e])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function Ioe(t){return t.tag===5||t.tag===3||t.tag===4}function xZ(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Ioe(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function UM(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.nodeType===8?n.parentNode.insertBefore(t,e):n.insertBefore(t,e):(n.nodeType===8?(e=n.parentNode,e.insertBefore(t,n)):(e=n,e.appendChild(t)),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=k6));else if(r!==4&&(t=t.child,t!==null))for(UM(t,e,n),t=t.sibling;t!==null;)UM(t,e,n),t=t.sibling}function FM(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(r!==4&&(t=t.child,t!==null))for(FM(t,e,n),t=t.sibling;t!==null;)FM(t,e,n),t=t.sibling}var Di=null,ku=!1;function Dp(t,e,n){for(n=n.child;n!==null;)Toe(t,e,n),n=n.sibling}function Toe(t,e,n){if(Zd&&typeof Zd.onCommitFiberUnmount=="function")try{Zd.onCommitFiberUnmount(Z4,n)}catch{}switch(n.tag){case 5:_o||Mb(n,e);case 6:var r=Di,s=ku;Di=null,Dp(t,e,n),Di=r,ku=s,Di!==null&&(ku?(t=Di,n=n.stateNode,t.nodeType===8?t.parentNode.removeChild(n):t.removeChild(n)):Di.removeChild(n.stateNode));break;case 18:Di!==null&&(ku?(t=Di,n=n.stateNode,t.nodeType===8?AO(t.parentNode,n):t.nodeType===1&&AO(t,n),YE(t)):AO(Di,n.stateNode));break;case 4:r=Di,s=ku,Di=n.stateNode.containerInfo,ku=!0,Dp(t,e,n),Di=r,ku=s;break;case 0:case 11:case 14:case 15:if(!_o&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&LM(n,e,o),s=s.next}while(s!==r)}Dp(t,e,n);break;case 1:if(!_o&&(Mb(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){Cs(n,e,a)}Dp(t,e,n);break;case 21:Dp(t,e,n);break;case 22:n.mode&1?(_o=(r=_o)||n.memoizedState!==null,Dp(t,e,n),_o=r):Dp(t,e,n);break;default:Dp(t,e,n)}}function EZ(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var n=t.stateNode;n===null&&(n=t.stateNode=new nTe),e.forEach(function(r){var s=fTe.bind(null,t,r);n.has(r)||(n.add(r),r.then(s,s))})}}function fu(t,e){var n=e.deletions;if(n!==null)for(var r=0;rs&&(s=o),r&=~i}if(r=s,r=Os()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*iTe(r/1960))-r,10t?16:t,Ig===null)var r=!1;else{if(t=Ig,Ig=null,V6=0,ar&6)throw Error(at(331));var s=ar;for(ar|=4,Ot=t.current;Ot!==null;){var i=Ot,o=i.child;if(Ot.flags&16){var a=i.deletions;if(a!==null){for(var c=0;cOs()-kF?Bm(t,0):PF|=n),Ka(t,e)}function Moe(t,e){e===0&&(t.mode&1?(e=W5,W5<<=1,!(W5&130023424)&&(W5=4194304)):e=1);var n=ea();t=Bh(t,e),t!==null&&(NS(t,e,n),Ka(t,n))}function dTe(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),Moe(t,n)}function fTe(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,s=t.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=t.stateNode;break;default:throw Error(at(314))}r!==null&&r.delete(e),Moe(t,n)}var Loe;Loe=function(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps||Ha.current)Fa=!0;else{if(!(t.lanes&n)&&!(e.flags&128))return Fa=!1,J6e(t,e,n);Fa=!!(t.flags&131072)}else Fa=!1,hs&&e.flags&1048576&&jie(e,D6,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;NI(t,e),t=e.pendingProps;var s=_v(e,Io.current);tv(e,n),s=_F(null,e,r,t,s,n);var i=SF();return e.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,qa(r)?(i=!0,O6(e)):i=!1,e.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,bF(e),s.updater=nP,e.stateNode=s,s._reactInternals=e,PM(e,r,t,n),e=OM(null,e,r,!0,i,n)):(e.tag=0,hs&&i&&fF(e),qo(null,e,s,n),e=e.child),e;case 16:r=e.elementType;e:{switch(NI(t,e),t=e.pendingProps,s=r._init,r=s(r._payload),e.type=r,s=e.tag=pTe(r),t=Iu(r,t),s){case 0:e=RM(null,e,r,t,n);break e;case 1:e=yZ(null,e,r,t,n);break e;case 11:e=gZ(null,e,r,t,n);break e;case 14:e=mZ(null,e,r,Iu(r.type,t),n);break e}throw Error(at(306,r,""))}return e;case 0:return r=e.type,s=e.pendingProps,s=e.elementType===r?s:Iu(r,s),RM(t,e,r,s,n);case 1:return r=e.type,s=e.pendingProps,s=e.elementType===r?s:Iu(r,s),yZ(t,e,r,s,n);case 3:e:{if(voe(e),t===null)throw Error(at(387));r=e.pendingProps,i=e.memoizedState,s=i.element,Kie(t,e),B6(e,r,null,n);var o=e.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},e.updateQueue.baseState=i,e.memoizedState=i,e.flags&256){s=Tv(Error(at(423)),e),e=wZ(t,e,r,n,s);break e}else if(r!==s){s=Tv(Error(at(424)),e),e=wZ(t,e,r,n,s);break e}else for(Oc=Fg(e.stateNode.containerInfo.firstChild),Mc=e,hs=!0,Ru=null,n=Hie(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Sv(),r===s){e=Uh(t,e,n);break e}qo(t,e,r,n)}e=e.child}return e;case 5:return Gie(e),t===null&&IM(e),r=e.type,s=e.pendingProps,i=t!==null?t.memoizedProps:null,o=s.children,EM(r,s)?o=null:i!==null&&EM(r,i)&&(e.flags|=32),boe(t,e),qo(t,e,o,n),e.child;case 6:return t===null&&IM(e),null;case 13:return xoe(t,e,n);case 4:return vF(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=Av(e,null,r,n):qo(t,e,r,n),e.child;case 11:return r=e.type,s=e.pendingProps,s=e.elementType===r?s:Iu(r,s),gZ(t,e,r,s,n);case 7:return qo(t,e,e.pendingProps,n),e.child;case 8:return qo(t,e,e.pendingProps.children,n),e.child;case 12:return qo(t,e,e.pendingProps.children,n),e.child;case 10:e:{if(r=e.type._context,s=e.pendingProps,i=e.memoizedProps,o=s.value,es(M6,r._currentValue),r._currentValue=o,i!==null)if(Ju(i.value,o)){if(i.children===s.children&&!Ha.current){e=Uh(t,e,n);break e}}else for(i=e.child,i!==null&&(i.return=e);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var c=a.firstContext;c!==null;){if(c.context===r){if(i.tag===1){c=Sh(-1,n&-n),c.tag=2;var l=i.updateQueue;if(l!==null){l=l.shared;var u=l.pending;u===null?c.next=c:(c.next=u.next,u.next=c),l.pending=c}}i.lanes|=n,c=i.alternate,c!==null&&(c.lanes|=n),TM(i.return,n,e),a.lanes|=n;break}c=c.next}}else if(i.tag===10)o=i.type===e.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(at(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),TM(o,n,e),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===e){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}qo(t,e,s.children,n),e=e.child}return e;case 9:return s=e.type,r=e.pendingProps.children,tv(e,n),s=Ul(s),r=r(s),e.flags|=1,qo(t,e,r,n),e.child;case 14:return r=e.type,s=Iu(r,e.pendingProps),s=Iu(r.type,s),mZ(t,e,r,s,n);case 15:return yoe(t,e,e.type,e.pendingProps,n);case 17:return r=e.type,s=e.pendingProps,s=e.elementType===r?s:Iu(r,s),NI(t,e),e.tag=1,qa(r)?(t=!0,O6(e)):t=!1,tv(e,n),poe(e,r,s),PM(e,r,s,n),OM(null,e,r,!0,t,n);case 19:return Eoe(t,e,n);case 22:return woe(t,e,n)}throw Error(at(156,e.tag))};function Boe(t,e){return die(t,e)}function hTe(t,e,n,r){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Pl(t,e,n,r){return new hTe(t,e,n,r)}function DF(t){return t=t.prototype,!(!t||!t.isReactComponent)}function pTe(t){if(typeof t=="function")return DF(t)?1:0;if(t!=null){if(t=t.$$typeof,t===eF)return 11;if(t===tF)return 14}return 2}function Vg(t,e){var n=t.alternate;return n===null?(n=Pl(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&14680064,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n}function RI(t,e,n,r,s,i){var o=2;if(r=t,typeof t=="function")DF(t)&&(o=1);else if(typeof t=="string")o=5;else e:switch(t){case Ib:return Um(n.children,s,i,e);case JU:o=8,s|=8;break;case eM:return t=Pl(12,n,e,s|2),t.elementType=eM,t.lanes=i,t;case tM:return t=Pl(13,n,e,s),t.elementType=tM,t.lanes=i,t;case nM:return t=Pl(19,n,e,s),t.elementType=nM,t.lanes=i,t;case Gse:return iP(n,s,i,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case qse:o=10;break e;case Kse:o=9;break e;case eF:o=11;break e;case tF:o=14;break e;case lg:o=16,r=null;break e}throw Error(at(130,t==null?t:typeof t,""))}return e=Pl(o,n,e,s),e.elementType=t,e.type=r,e.lanes=i,e}function Um(t,e,n,r){return t=Pl(7,t,r,e),t.lanes=n,t}function iP(t,e,n,r){return t=Pl(22,t,r,e),t.elementType=Gse,t.lanes=n,t.stateNode={isHidden:!1},t}function $O(t,e,n){return t=Pl(6,t,null,e),t.lanes=n,t}function DO(t,e,n){return e=Pl(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function gTe(t,e,n,r,s){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=gO(0),this.expirationTimes=gO(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=gO(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function MF(t,e,n,r,s,i,o,a,c){return t=new gTe(t,e,n,a,c),e===1?(e=1,i===!0&&(e|=8)):e=0,i=Pl(3,null,null,e),t.current=i,i.stateNode=t,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},bF(i),t}function mTe(t,e,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(zoe)}catch(t){console.error(t)}}zoe(),zse.exports=Kc;var Qy=zse.exports;const Woe=Zi(Qy);var Voe,PZ=Qy;Voe=PZ.createRoot,PZ.hydrateRoot;const xTe=1,ETe=1e6;let MO=0;function CTe(){return MO=(MO+1)%Number.MAX_SAFE_INTEGER,MO.toString()}const LO=new Map,kZ=t=>{if(LO.has(t))return;const e=setTimeout(()=>{LO.delete(t),pE({type:"REMOVE_TOAST",toastId:t})},ETe);LO.set(t,e)},_Te=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,xTe)};case"UPDATE_TOAST":return{...t,toasts:t.toasts.map(n=>n.id===e.toast.id?{...n,...e.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=e;return n?kZ(n):t.toasts.forEach(r=>{kZ(r.id)}),{...t,toasts:t.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return e.toastId===void 0?{...t,toasts:[]}:{...t,toasts:t.toasts.filter(n=>n.id!==e.toastId)}}},OI=[];let $I={toasts:[]};function pE(t){$I=_Te($I,t),OI.forEach(e=>{e($I)})}function STe({...t}){const e=CTe(),n=s=>pE({type:"UPDATE_TOAST",toast:{...s,id:e}}),r=()=>pE({type:"DISMISS_TOAST",toastId:e});return pE({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:s=>{s||r()}}}),{id:e,dismiss:r,update:n}}function xf(){const[t,e]=I.useState($I);return I.useEffect(()=>(OI.push(e),()=>{const n=OI.indexOf(e);n>-1&&OI.splice(n,1)}),[t]),{...t,toast:STe,dismiss:n=>pE({type:"DISMISS_TOAST",toastId:n})}}function vt(t,e,{checkForDefaultPrevented:n=!0}={}){return function(s){if(t?.(s),n===!1||!s.defaultPrevented)return e?.(s)}}function ATe(t,e){typeof t=="function"?t(e):t!=null&&(t.current=e)}function uP(...t){return e=>t.forEach(n=>ATe(n,e))}function ir(...t){return I.useCallback(uP(...t),t)}function ITe(t,e=[]){let n=[];function r(i,o){const a=I.createContext(o),c=n.length;n=[...n,o];function l(d){const{scope:f,children:p,...m}=d,y=f?.[t][c]||a,b=I.useMemo(()=>m,Object.values(m));return w.jsx(y.Provider,{value:b,children:p})}function u(d,f){const p=f?.[t][c]||a,m=I.useContext(p);if(m)return m;if(o!==void 0)return o;throw new Error(`\`${d}\` must be used within \`${i}\``)}return l.displayName=i+"Provider",[l,u]}const s=()=>{const i=n.map(o=>I.createContext(o));return function(a){const c=a?.[t]||i;return I.useMemo(()=>({[`__scope${t}`]:{...a,[t]:c}}),[a,c])}};return s.scopeName=t,[r,TTe(s,...e)]}function TTe(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(i){const o=r.reduce((a,{useScope:c,scopeName:l})=>{const d=c(i)[`__scope${l}`];return{...a,...d}},{});return I.useMemo(()=>({[`__scope${e.scopeName}`]:o}),[o])}};return n.scopeName=e.scopeName,n}var Fh=I.forwardRef((t,e)=>{const{children:n,...r}=t,s=I.Children.toArray(n),i=s.find(NTe);if(i){const o=i.props.children,a=s.map(c=>c===i?I.Children.count(o)>1?I.Children.only(null):I.isValidElement(o)?o.props.children:null:c);return w.jsx(HM,{...r,ref:e,children:I.isValidElement(o)?I.cloneElement(o,void 0,a):null})}return w.jsx(HM,{...r,ref:e,children:n})});Fh.displayName="Slot";var HM=I.forwardRef((t,e)=>{const{children:n,...r}=t;if(I.isValidElement(n)){const s=kTe(n);return I.cloneElement(n,{...PTe(r,n.props),ref:e?uP(e,s):s})}return I.Children.count(n)>1?I.Children.only(null):null});HM.displayName="SlotClone";var FF=({children:t})=>w.jsx(w.Fragment,{children:t});function NTe(t){return I.isValidElement(t)&&t.type===FF}function PTe(t,e){const n={...e};for(const r in e){const s=t[r],i=e[r];/^on[A-Z]/.test(r)?s&&i?n[r]=(...a)=>{i(...a),s(...a)}:s&&(n[r]=s):r==="style"?n[r]={...s,...i}:r==="className"&&(n[r]=[s,i].filter(Boolean).join(" "))}return{...t,...n}}function kTe(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}function dP(t){const e=t+"CollectionProvider",[n,r]=ITe(e),[s,i]=n(e,{collectionRef:{current:null},itemMap:new Map}),o=p=>{const{scope:m,children:y}=p,b=qe.useRef(null),v=qe.useRef(new Map).current;return w.jsx(s,{scope:m,itemMap:v,collectionRef:b,children:y})};o.displayName=e;const a=t+"CollectionSlot",c=qe.forwardRef((p,m)=>{const{scope:y,children:b}=p,v=i(a,y),x=ir(m,v.collectionRef);return w.jsx(Fh,{ref:x,children:b})});c.displayName=a;const l=t+"CollectionItemSlot",u="data-radix-collection-item",d=qe.forwardRef((p,m)=>{const{scope:y,children:b,...v}=p,x=qe.useRef(null),E=ir(m,x),A=i(l,y);return qe.useEffect(()=>(A.itemMap.set(x,{ref:x,...v}),()=>void A.itemMap.delete(x))),w.jsx(Fh,{[u]:"",ref:E,children:b})});d.displayName=l;function f(p){const m=i(t+"CollectionConsumer",p);return qe.useCallback(()=>{const b=m.collectionRef.current;if(!b)return[];const v=Array.from(b.querySelectorAll(`[${u}]`));return Array.from(m.itemMap.values()).sort((A,_)=>v.indexOf(A.ref.current)-v.indexOf(_.ref.current))},[m.collectionRef,m.itemMap])}return[{Provider:o,Slot:c,ItemSlot:d},f,r]}function RTe(t,e){const n=I.createContext(e),r=i=>{const{children:o,...a}=i,c=I.useMemo(()=>a,Object.values(a));return w.jsx(n.Provider,{value:c,children:o})};r.displayName=t+"Provider";function s(i){const o=I.useContext(n);if(o)return o;if(e!==void 0)return e;throw new Error(`\`${i}\` must be used within \`${t}\``)}return[r,s]}function pp(t,e=[]){let n=[];function r(i,o){const a=I.createContext(o),c=n.length;n=[...n,o];const l=d=>{const{scope:f,children:p,...m}=d,y=f?.[t]?.[c]||a,b=I.useMemo(()=>m,Object.values(m));return w.jsx(y.Provider,{value:b,children:p})};l.displayName=i+"Provider";function u(d,f){const p=f?.[t]?.[c]||a,m=I.useContext(p);if(m)return m;if(o!==void 0)return o;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,u]}const s=()=>{const i=n.map(o=>I.createContext(o));return function(a){const c=a?.[t]||i;return I.useMemo(()=>({[`__scope${t}`]:{...a,[t]:c}}),[a,c])}};return s.scopeName=t,[r,OTe(s,...e)]}function OTe(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(i){const o=r.reduce((a,{useScope:c,scopeName:l})=>{const d=c(i)[`__scope${l}`];return{...a,...d}},{});return I.useMemo(()=>({[`__scope${e.scopeName}`]:o}),[o])}};return n.scopeName=e.scopeName,n}var $Te=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],gn=$Te.reduce((t,e)=>{const n=I.forwardRef((r,s)=>{const{asChild:i,...o}=r,a=i?Fh:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),w.jsx(a,{...o,ref:s})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});function jF(t,e){t&&Qy.flushSync(()=>t.dispatchEvent(e))}function To(t){const e=I.useRef(t);return I.useEffect(()=>{e.current=t}),I.useMemo(()=>(...n)=>e.current?.(...n),[])}function DTe(t,e=globalThis?.document){const n=To(t);I.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[n,e])}var MTe="DismissableLayer",qM="dismissableLayer.update",LTe="dismissableLayer.pointerDownOutside",BTe="dismissableLayer.focusOutside",RZ,Hoe=I.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),z1=I.forwardRef((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:i,onInteractOutside:o,onDismiss:a,...c}=t,l=I.useContext(Hoe),[u,d]=I.useState(null),f=u?.ownerDocument??globalThis?.document,[,p]=I.useState({}),m=ir(e,B=>d(B)),y=Array.from(l.layers),[b]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),v=y.indexOf(b),x=u?y.indexOf(u):-1,E=l.layersWithOutsidePointerEventsDisabled.size>0,A=x>=v,_=FTe(B=>{const W=B.target,S=[...l.branches].some($=>$.contains(W));!A||S||(s?.(B),o?.(B),B.defaultPrevented||a?.())},f),k=jTe(B=>{const W=B.target;[...l.branches].some($=>$.contains(W))||(i?.(B),o?.(B),B.defaultPrevented||a?.())},f);return DTe(B=>{x===l.layers.size-1&&(r?.(B),!B.defaultPrevented&&a&&(B.preventDefault(),a()))},f),I.useEffect(()=>{if(u)return n&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(RZ=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(u)),l.layers.add(u),OZ(),()=>{n&&l.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=RZ)}},[u,f,n,l]),I.useEffect(()=>()=>{u&&(l.layers.delete(u),l.layersWithOutsidePointerEventsDisabled.delete(u),OZ())},[u,l]),I.useEffect(()=>{const B=()=>p({});return document.addEventListener(qM,B),()=>document.removeEventListener(qM,B)},[]),w.jsx(gn.div,{...c,ref:m,style:{pointerEvents:E?A?"auto":"none":void 0,...t.style},onFocusCapture:vt(t.onFocusCapture,k.onFocusCapture),onBlurCapture:vt(t.onBlurCapture,k.onBlurCapture),onPointerDownCapture:vt(t.onPointerDownCapture,_.onPointerDownCapture)})});z1.displayName=MTe;var UTe="DismissableLayerBranch",qoe=I.forwardRef((t,e)=>{const n=I.useContext(Hoe),r=I.useRef(null),s=ir(e,r);return I.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),w.jsx(gn.div,{...t,ref:s})});qoe.displayName=UTe;function FTe(t,e=globalThis?.document){const n=To(t),r=I.useRef(!1),s=I.useRef(()=>{});return I.useEffect(()=>{const i=a=>{if(a.target&&!r.current){let c=function(){Koe(LTe,n,l,{discrete:!0})};const l={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",s.current),s.current=c,e.addEventListener("click",s.current,{once:!0})):c()}else e.removeEventListener("click",s.current);r.current=!1},o=window.setTimeout(()=>{e.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(o),e.removeEventListener("pointerdown",i),e.removeEventListener("click",s.current)}},[e,n]),{onPointerDownCapture:()=>r.current=!0}}function jTe(t,e=globalThis?.document){const n=To(t),r=I.useRef(!1);return I.useEffect(()=>{const s=i=>{i.target&&!r.current&&Koe(BTe,n,{originalEvent:i},{discrete:!1})};return e.addEventListener("focusin",s),()=>e.removeEventListener("focusin",s)},[e,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OZ(){const t=new CustomEvent(qM);document.dispatchEvent(t)}function Koe(t,e,n,{discrete:r}){const s=n.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&s.addEventListener(t,e,{once:!0}),r?jF(s,i):s.dispatchEvent(i)}var zTe=z1,WTe=qoe,No=globalThis?.document?I.useLayoutEffect:()=>{},VTe="Portal",OS=I.forwardRef((t,e)=>{const{container:n,...r}=t,[s,i]=I.useState(!1);No(()=>i(!0),[]);const o=n||s&&globalThis?.document?.body;return o?Woe.createPortal(w.jsx(gn.div,{...r,ref:e}),o):null});OS.displayName=VTe;function HTe(t,e){return I.useReducer((n,r)=>e[n][r]??n,t)}var ud=t=>{const{present:e,children:n}=t,r=qTe(e),s=typeof n=="function"?n({present:r.isPresent}):I.Children.only(n),i=ir(r.ref,KTe(s));return typeof n=="function"||r.isPresent?I.cloneElement(s,{ref:i}):null};ud.displayName="Presence";function qTe(t){const[e,n]=I.useState(),r=I.useRef({}),s=I.useRef(t),i=I.useRef("none"),o=t?"mounted":"unmounted",[a,c]=HTe(o,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return I.useEffect(()=>{const l=tA(r.current);i.current=a==="mounted"?l:"none"},[a]),No(()=>{const l=r.current,u=s.current;if(u!==t){const f=i.current,p=tA(l);t?c("MOUNT"):p==="none"||l?.display==="none"?c("UNMOUNT"):c(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),s.current=t}},[t,c]),No(()=>{if(e){let l;const u=e.ownerDocument.defaultView??window,d=p=>{const y=tA(r.current).includes(p.animationName);if(p.target===e&&y&&(c("ANIMATION_END"),!s.current)){const b=e.style.animationFillMode;e.style.animationFillMode="forwards",l=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=b)})}},f=p=>{p.target===e&&(i.current=tA(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(l),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else c("ANIMATION_END")},[e,c]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:I.useCallback(l=>{l&&(r.current=getComputedStyle(l)),n(l)},[])}}function tA(t){return t?.animationName||"none"}function KTe(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}function jh({prop:t,defaultProp:e,onChange:n=()=>{}}){const[r,s]=GTe({defaultProp:e,onChange:n}),i=t!==void 0,o=i?t:r,a=To(n),c=I.useCallback(l=>{if(i){const d=typeof l=="function"?l(t):l;d!==t&&a(d)}else s(l)},[i,t,s,a]);return[o,c]}function GTe({defaultProp:t,onChange:e}){const n=I.useState(t),[r]=n,s=I.useRef(r),i=To(e);return I.useEffect(()=>{s.current!==r&&(i(r),s.current=r)},[r,s,i]),n}var ZTe="VisuallyHidden",$S=I.forwardRef((t,e)=>w.jsx(gn.span,{...t,ref:e,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...t.style}}));$S.displayName=ZTe;var YTe=$S,zF="ToastProvider",[WF,XTe,QTe]=dP("Toast"),[Goe,ekt]=pp("Toast",[QTe]),[JTe,fP]=Goe(zF),Zoe=t=>{const{__scopeToast:e,label:n="Notification",duration:r=5e3,swipeDirection:s="right",swipeThreshold:i=50,children:o}=t,[a,c]=I.useState(null),[l,u]=I.useState(0),d=I.useRef(!1),f=I.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${zF}\`. Expected non-empty \`string\`.`),w.jsx(WF.Provider,{scope:e,children:w.jsx(JTe,{scope:e,label:n,duration:r,swipeDirection:s,swipeThreshold:i,toastCount:l,viewport:a,onViewportChange:c,onToastAdd:I.useCallback(()=>u(p=>p+1),[]),onToastRemove:I.useCallback(()=>u(p=>p-1),[]),isFocusedToastEscapeKeyDownRef:d,isClosePausedRef:f,children:o})})};Zoe.displayName=zF;var Yoe="ToastViewport",eNe=["F8"],KM="toast.viewportPause",GM="toast.viewportResume",Xoe=I.forwardRef((t,e)=>{const{__scopeToast:n,hotkey:r=eNe,label:s="Notifications ({hotkey})",...i}=t,o=fP(Yoe,n),a=XTe(n),c=I.useRef(null),l=I.useRef(null),u=I.useRef(null),d=I.useRef(null),f=ir(e,d,o.onViewportChange),p=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),m=o.toastCount>0;I.useEffect(()=>{const b=v=>{r.length!==0&&r.every(E=>v[E]||v.code===E)&&d.current?.focus()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[r]),I.useEffect(()=>{const b=c.current,v=d.current;if(m&&b&&v){const x=()=>{if(!o.isClosePausedRef.current){const k=new CustomEvent(KM);v.dispatchEvent(k),o.isClosePausedRef.current=!0}},E=()=>{if(o.isClosePausedRef.current){const k=new CustomEvent(GM);v.dispatchEvent(k),o.isClosePausedRef.current=!1}},A=k=>{!b.contains(k.relatedTarget)&&E()},_=()=>{b.contains(document.activeElement)||E()};return b.addEventListener("focusin",x),b.addEventListener("focusout",A),b.addEventListener("pointermove",x),b.addEventListener("pointerleave",_),window.addEventListener("blur",x),window.addEventListener("focus",E),()=>{b.removeEventListener("focusin",x),b.removeEventListener("focusout",A),b.removeEventListener("pointermove",x),b.removeEventListener("pointerleave",_),window.removeEventListener("blur",x),window.removeEventListener("focus",E)}}},[m,o.isClosePausedRef]);const y=I.useCallback(({tabbingDirection:b})=>{const x=a().map(E=>{const A=E.ref.current,_=[A,...hNe(A)];return b==="forwards"?_:_.reverse()});return(b==="forwards"?x.reverse():x).flat()},[a]);return I.useEffect(()=>{const b=d.current;if(b){const v=x=>{const E=x.altKey||x.ctrlKey||x.metaKey;if(x.key==="Tab"&&!E){const _=document.activeElement,k=x.shiftKey;if(x.target===b&&k){l.current?.focus();return}const S=y({tabbingDirection:k?"backwards":"forwards"}),$=S.findIndex(R=>R===_);BO(S.slice($+1))?x.preventDefault():k?l.current?.focus():u.current?.focus()}};return b.addEventListener("keydown",v),()=>b.removeEventListener("keydown",v)}},[a,y]),w.jsxs(WTe,{ref:c,role:"region","aria-label":s.replace("{hotkey}",p),tabIndex:-1,style:{pointerEvents:m?void 0:"none"},children:[m&&w.jsx(ZM,{ref:l,onFocusFromOutsideViewport:()=>{const b=y({tabbingDirection:"forwards"});BO(b)}}),w.jsx(WF.Slot,{scope:n,children:w.jsx(gn.ol,{tabIndex:-1,...i,ref:f})}),m&&w.jsx(ZM,{ref:u,onFocusFromOutsideViewport:()=>{const b=y({tabbingDirection:"backwards"});BO(b)}})]})});Xoe.displayName=Yoe;var Qoe="ToastFocusProxy",ZM=I.forwardRef((t,e)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...s}=t,i=fP(Qoe,n);return w.jsx($S,{"aria-hidden":!0,tabIndex:0,...s,ref:e,style:{position:"fixed"},onFocus:o=>{const a=o.relatedTarget;!i.viewport?.contains(a)&&r()}})});ZM.displayName=Qoe;var hP="Toast",tNe="toast.swipeStart",nNe="toast.swipeMove",rNe="toast.swipeCancel",sNe="toast.swipeEnd",Joe=I.forwardRef((t,e)=>{const{forceMount:n,open:r,defaultOpen:s,onOpenChange:i,...o}=t,[a=!0,c]=jh({prop:r,defaultProp:s,onChange:i});return w.jsx(ud,{present:n||a,children:w.jsx(aNe,{open:a,...o,ref:e,onClose:()=>c(!1),onPause:To(t.onPause),onResume:To(t.onResume),onSwipeStart:vt(t.onSwipeStart,l=>{l.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:vt(t.onSwipeMove,l=>{const{x:u,y:d}=l.detail.delta;l.currentTarget.setAttribute("data-swipe","move"),l.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),l.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${d}px`)}),onSwipeCancel:vt(t.onSwipeCancel,l=>{l.currentTarget.setAttribute("data-swipe","cancel"),l.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),l.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),l.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),l.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:vt(t.onSwipeEnd,l=>{const{x:u,y:d}=l.detail.delta;l.currentTarget.setAttribute("data-swipe","end"),l.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),l.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),l.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),l.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${d}px`),c(!1)})})})});Joe.displayName=hP;var[iNe,oNe]=Goe(hP,{onClose(){}}),aNe=I.forwardRef((t,e)=>{const{__scopeToast:n,type:r="foreground",duration:s,open:i,onClose:o,onEscapeKeyDown:a,onPause:c,onResume:l,onSwipeStart:u,onSwipeMove:d,onSwipeCancel:f,onSwipeEnd:p,...m}=t,y=fP(hP,n),[b,v]=I.useState(null),x=ir(e,z=>v(z)),E=I.useRef(null),A=I.useRef(null),_=s||y.duration,k=I.useRef(0),B=I.useRef(_),W=I.useRef(0),{onToastAdd:S,onToastRemove:$}=y,R=To(()=>{b?.contains(document.activeElement)&&y.viewport?.focus(),o()}),M=I.useCallback(z=>{!z||z===1/0||(window.clearTimeout(W.current),k.current=new Date().getTime(),W.current=window.setTimeout(R,z))},[R]);I.useEffect(()=>{const z=y.viewport;if(z){const N=()=>{M(B.current),l?.()},T=()=>{const U=new Date().getTime()-k.current;B.current=B.current-U,window.clearTimeout(W.current),c?.()};return z.addEventListener(KM,T),z.addEventListener(GM,N),()=>{z.removeEventListener(KM,T),z.removeEventListener(GM,N)}}},[y.viewport,_,c,l,M]),I.useEffect(()=>{i&&!y.isClosePausedRef.current&&M(_)},[i,_,y.isClosePausedRef,M]),I.useEffect(()=>(S(),()=>$()),[S,$]);const j=I.useMemo(()=>b?oae(b):null,[b]);return y.viewport?w.jsxs(w.Fragment,{children:[j&&w.jsx(cNe,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:j}),w.jsx(iNe,{scope:n,onClose:R,children:Qy.createPortal(w.jsx(WF.ItemSlot,{scope:n,children:w.jsx(zTe,{asChild:!0,onEscapeKeyDown:vt(a,()=>{y.isFocusedToastEscapeKeyDownRef.current||R(),y.isFocusedToastEscapeKeyDownRef.current=!1}),children:w.jsx(gn.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":y.swipeDirection,...m,ref:x,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:vt(t.onKeyDown,z=>{z.key==="Escape"&&(a?.(z.nativeEvent),z.nativeEvent.defaultPrevented||(y.isFocusedToastEscapeKeyDownRef.current=!0,R()))}),onPointerDown:vt(t.onPointerDown,z=>{z.button===0&&(E.current={x:z.clientX,y:z.clientY})}),onPointerMove:vt(t.onPointerMove,z=>{if(!E.current)return;const N=z.clientX-E.current.x,T=z.clientY-E.current.y,U=!!A.current,L=["left","right"].includes(y.swipeDirection),P=["left","up"].includes(y.swipeDirection)?Math.min:Math.max,H=L?P(0,N):0,Y=L?0:P(0,T),re=z.pointerType==="touch"?10:2,de={x:H,y:Y},fe={originalEvent:z,delta:de};U?(A.current=de,nA(nNe,d,fe,{discrete:!1})):$Z(de,y.swipeDirection,re)?(A.current=de,nA(tNe,u,fe,{discrete:!1}),z.target.setPointerCapture(z.pointerId)):(Math.abs(N)>re||Math.abs(T)>re)&&(E.current=null)}),onPointerUp:vt(t.onPointerUp,z=>{const N=A.current,T=z.target;if(T.hasPointerCapture(z.pointerId)&&T.releasePointerCapture(z.pointerId),A.current=null,E.current=null,N){const U=z.currentTarget,L={originalEvent:z,delta:N};$Z(N,y.swipeDirection,y.swipeThreshold)?nA(sNe,p,L,{discrete:!0}):nA(rNe,f,L,{discrete:!0}),U.addEventListener("click",P=>P.preventDefault(),{once:!0})}})})})}),y.viewport)})]}):null}),cNe=t=>{const{__scopeToast:e,children:n,...r}=t,s=fP(hP,e),[i,o]=I.useState(!1),[a,c]=I.useState(!1);return dNe(()=>o(!0)),I.useEffect(()=>{const l=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(l)},[]),a?null:w.jsx(OS,{asChild:!0,children:w.jsx($S,{...r,children:i&&w.jsxs(w.Fragment,{children:[s.label," ",n]})})})},lNe="ToastTitle",eae=I.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t;return w.jsx(gn.div,{...r,ref:e})});eae.displayName=lNe;var uNe="ToastDescription",tae=I.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t;return w.jsx(gn.div,{...r,ref:e})});tae.displayName=uNe;var nae="ToastAction",rae=I.forwardRef((t,e)=>{const{altText:n,...r}=t;return n.trim()?w.jsx(iae,{altText:n,asChild:!0,children:w.jsx(VF,{...r,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${nae}\`. Expected non-empty \`string\`.`),null)});rae.displayName=nae;var sae="ToastClose",VF=I.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t,s=oNe(sae,n);return w.jsx(iae,{asChild:!0,children:w.jsx(gn.button,{type:"button",...r,ref:e,onClick:vt(t.onClick,s.onClose)})})});VF.displayName=sae;var iae=I.forwardRef((t,e)=>{const{__scopeToast:n,altText:r,...s}=t;return w.jsx(gn.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...s,ref:e})});function oae(t){const e=[];return Array.from(t.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&e.push(r.textContent),fNe(r)){const s=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!s)if(i){const o=r.dataset.radixToastAnnounceAlt;o&&e.push(o)}else e.push(...oae(r))}}),e}function nA(t,e,n,{discrete:r}){const s=n.originalEvent.currentTarget,i=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:n});e&&s.addEventListener(t,e,{once:!0}),r?jF(s,i):s.dispatchEvent(i)}var $Z=(t,e,n=0)=>{const r=Math.abs(t.x),s=Math.abs(t.y),i=r>s;return e==="left"||e==="right"?i&&r>n:!i&&s>n};function dNe(t=()=>{}){const e=To(t);No(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[e])}function fNe(t){return t.nodeType===t.ELEMENT_NODE}function hNe(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function BO(t){const e=document.activeElement;return t.some(n=>n===e?!0:(n.focus(),document.activeElement!==e))}var pNe=Zoe,aae=Xoe,cae=Joe,lae=eae,uae=tae,dae=rae,fae=VF;function hae(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;etypeof t=="boolean"?`${t}`:t===0?"0":t,MZ=pae,pP=(t,e)=>n=>{var r;if(e?.variants==null)return MZ(t,n?.class,n?.className);const{variants:s,defaultVariants:i}=e,o=Object.keys(s).map(l=>{const u=n?.[l],d=i?.[l];if(u===null)return null;const f=DZ(u)||DZ(d);return s[l][f]}),a=n&&Object.entries(n).reduce((l,u)=>{let[d,f]=u;return f===void 0||(l[d]=f),l},{}),c=e==null||(r=e.compoundVariants)===null||r===void 0?void 0:r.reduce((l,u)=>{let{class:d,className:f,...p}=u;return Object.entries(p).every(m=>{let[y,b]=m;return Array.isArray(b)?b.includes({...i,...a}[y]):{...i,...a}[y]===b})?[...l,d,f]:l},[]);return MZ(t,o,c,n?.class,n?.className)};/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gNe=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),gae=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var mNe={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yNe=I.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:s="",children:i,iconNode:o,...a},c)=>I.createElement("svg",{ref:c,...mNe,width:e,height:e,stroke:t,strokeWidth:r?Number(n)*24/Number(e):n,className:gae("lucide",s),...a},[...o.map(([l,u])=>I.createElement(l,u)),...Array.isArray(i)?i:[i]]));/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Xt=(t,e)=>{const n=I.forwardRef(({className:r,...s},i)=>I.createElement(yNe,{ref:i,iconNode:e,className:gae(`lucide-${gNe(t)}`,r),...s}));return n.displayName=`${t}`,n};/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gP=Xt("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const DI=Xt("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mP=Xt("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mae=Xt("Bitcoin",[["path",{d:"M11.767 19.089c4.924.868 6.14-6.025 1.216-6.894m-1.216 6.894L5.86 18.047m5.908 1.042-.347 1.97m1.563-8.864c4.924.869 6.14-6.025 1.215-6.893m-1.215 6.893-3.94-.694m5.155-6.2L8.29 4.26m5.908 1.042.348-1.97M7.48 20.364l3.126-17.727",key:"yr8idg"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const wNe=Xt("BookmarkCheck",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Fm=Xt("Bookmark",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yae=Xt("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const wae=Xt("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bNe=Xt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vNe=Xt("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const YM=Xt("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const cC=Xt("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const xNe=Xt("CircleSlash",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ENe=Xt("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bae=Xt("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const CNe=Xt("Clipboard",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const W1=Xt("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vae=Xt("Coins",[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const LZ=Xt("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _Ne=Xt("Crown",[["path",{d:"M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z",key:"1vdc57"}],["path",{d:"M5 21h14",key:"11awu3"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const SNe=Xt("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ANe=Xt("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const K6=Xt("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const XM=Xt("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const INe=Xt("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const QM=Xt("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const xae=Xt("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const BZ=Xt("House",[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const TNe=Xt("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Xd=Xt("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const NNe=Xt("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const PNe=Xt("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const MI=Xt("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const s0=Xt("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Eae=Xt("PanelsTopLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const kNe=Xt("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const HF=Xt("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const RNe=Xt("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ONe=Xt("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const JM=Xt("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const UZ=Xt("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const zh=Xt("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const $Ne=Xt("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const DNe=Xt("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yP=Xt("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const lC=Xt("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const G6=Xt("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const FZ=Xt("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Cae=Xt("UserX",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gE=Xt("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const MNe=Xt("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const LNe=Xt("Wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const wP=Xt("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),qF="-",BNe=t=>{const e=FNe(t),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:o=>{const a=o.split(qF);return a[0]===""&&a.length!==1&&a.shift(),_ae(a,e)||UNe(o)},getConflictingClassGroupIds:(o,a)=>{const c=n[o]||[];return a&&r[o]?[...c,...r[o]]:c}}},_ae=(t,e)=>{if(t.length===0)return e.classGroupId;const n=t[0],r=e.nextPart.get(n),s=r?_ae(t.slice(1),r):void 0;if(s)return s;if(e.validators.length===0)return;const i=t.join(qF);return e.validators.find(({validator:o})=>o(i))?.classGroupId},jZ=/^\[(.+)\]$/,UNe=t=>{if(jZ.test(t)){const e=jZ.exec(t)[1],n=e?.substring(0,e.indexOf(":"));if(n)return"arbitrary.."+n}},FNe=t=>{const{theme:e,prefix:n}=t,r={nextPart:new Map,validators:[]};return zNe(Object.entries(t.classGroups),n).forEach(([i,o])=>{eL(o,r,i,e)}),r},eL=(t,e,n,r)=>{t.forEach(s=>{if(typeof s=="string"){const i=s===""?e:zZ(e,s);i.classGroupId=n;return}if(typeof s=="function"){if(jNe(s)){eL(s(r),e,n,r);return}e.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([i,o])=>{eL(o,zZ(e,i),n,r)})})},zZ=(t,e)=>{let n=t;return e.split(qF).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},jNe=t=>t.isThemeGetter,zNe=(t,e)=>e?t.map(([n,r])=>{const s=r.map(i=>typeof i=="string"?e+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,a])=>[e+o,a])):i);return[n,s]}):t,WNe=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,n=new Map,r=new Map;const s=(i,o)=>{n.set(i,o),e++,e>t&&(e=0,r=n,n=new Map)};return{get(i){let o=n.get(i);if(o!==void 0)return o;if((o=r.get(i))!==void 0)return s(i,o),o},set(i,o){n.has(i)?n.set(i,o):s(i,o)}}},Sae="!",VNe=t=>{const{separator:e,experimentalParseClassName:n}=t,r=e.length===1,s=e[0],i=e.length,o=a=>{const c=[];let l=0,u=0,d;for(let b=0;bu?d-u:void 0;return{modifiers:c,hasImportantModifier:p,baseClassName:m,maybePostfixModifierPosition:y}};return n?a=>n({className:a,parseClassName:o}):o},HNe=t=>{if(t.length<=1)return t;const e=[];let n=[];return t.forEach(r=>{r[0]==="["?(e.push(...n.sort(),r),n=[]):n.push(r)}),e.push(...n.sort()),e},qNe=t=>({cache:WNe(t.cacheSize),parseClassName:VNe(t),...BNe(t)}),KNe=/\s+/,GNe=(t,e)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=e,i=[],o=t.trim().split(KNe);let a="";for(let c=o.length-1;c>=0;c-=1){const l=o[c],{modifiers:u,hasImportantModifier:d,baseClassName:f,maybePostfixModifierPosition:p}=n(l);let m=!!p,y=r(m?f.substring(0,p):f);if(!y){if(!m){a=l+(a.length>0?" "+a:a);continue}if(y=r(f),!y){a=l+(a.length>0?" "+a:a);continue}m=!1}const b=HNe(u).join(":"),v=d?b+Sae:b,x=v+y;if(i.includes(x))continue;i.push(x);const E=s(y,m);for(let A=0;A0?" "+a:a)}return a};function ZNe(){let t=0,e,n,r="";for(;t{if(typeof t=="string")return t;let e,n="";for(let r=0;rd(u),t());return n=qNe(l),r=n.cache.get,s=n.cache.set,i=a,a(c)}function a(c){const l=r(c);if(l)return l;const u=GNe(c,n);return s(c,u),u}return function(){return i(ZNe.apply(null,arguments))}}const ns=t=>{const e=n=>n[t]||[];return e.isThemeGetter=!0,e},Iae=/^\[(?:([a-z-]+):)?(.+)\]$/i,XNe=/^\d+\/\d+$/,QNe=new Set(["px","full","screen"]),JNe=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,e4e=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,t4e=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,n4e=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,r4e=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,jf=t=>rv(t)||QNe.has(t)||XNe.test(t),Mp=t=>V1(t,"length",d4e),rv=t=>!!t&&!Number.isNaN(Number(t)),UO=t=>V1(t,"number",rv),Zx=t=>!!t&&Number.isInteger(Number(t)),s4e=t=>t.endsWith("%")&&rv(t.slice(0,-1)),On=t=>Iae.test(t),Lp=t=>JNe.test(t),i4e=new Set(["length","size","percentage"]),o4e=t=>V1(t,i4e,Tae),a4e=t=>V1(t,"position",Tae),c4e=new Set(["image","url"]),l4e=t=>V1(t,c4e,h4e),u4e=t=>V1(t,"",f4e),Yx=()=>!0,V1=(t,e,n)=>{const r=Iae.exec(t);return r?r[1]?typeof e=="string"?r[1]===e:e.has(r[1]):n(r[2]):!1},d4e=t=>e4e.test(t)&&!t4e.test(t),Tae=()=>!1,f4e=t=>n4e.test(t),h4e=t=>r4e.test(t),p4e=()=>{const t=ns("colors"),e=ns("spacing"),n=ns("blur"),r=ns("brightness"),s=ns("borderColor"),i=ns("borderRadius"),o=ns("borderSpacing"),a=ns("borderWidth"),c=ns("contrast"),l=ns("grayscale"),u=ns("hueRotate"),d=ns("invert"),f=ns("gap"),p=ns("gradientColorStops"),m=ns("gradientColorStopPositions"),y=ns("inset"),b=ns("margin"),v=ns("opacity"),x=ns("padding"),E=ns("saturate"),A=ns("scale"),_=ns("sepia"),k=ns("skew"),B=ns("space"),W=ns("translate"),S=()=>["auto","contain","none"],$=()=>["auto","hidden","clip","visible","scroll"],R=()=>["auto",On,e],M=()=>[On,e],j=()=>["",jf,Mp],z=()=>["auto",rv,On],N=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],T=()=>["solid","dashed","dotted","double","none"],U=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],L=()=>["start","end","center","between","around","evenly","stretch"],P=()=>["","0",On],H=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Y=()=>[rv,On];return{cacheSize:500,separator:":",theme:{colors:[Yx],spacing:[jf,Mp],blur:["none","",Lp,On],brightness:Y(),borderColor:[t],borderRadius:["none","","full",Lp,On],borderSpacing:M(),borderWidth:j(),contrast:Y(),grayscale:P(),hueRotate:Y(),invert:P(),gap:M(),gradientColorStops:[t],gradientColorStopPositions:[s4e,Mp],inset:R(),margin:R(),opacity:Y(),padding:M(),saturate:Y(),scale:Y(),sepia:P(),skew:Y(),space:M(),translate:M()},classGroups:{aspect:[{aspect:["auto","square","video",On]}],container:["container"],columns:[{columns:[Lp]}],"break-after":[{"break-after":H()}],"break-before":[{"break-before":H()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...N(),On]}],overflow:[{overflow:$()}],"overflow-x":[{"overflow-x":$()}],"overflow-y":[{"overflow-y":$()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[y]}],"inset-x":[{"inset-x":[y]}],"inset-y":[{"inset-y":[y]}],start:[{start:[y]}],end:[{end:[y]}],top:[{top:[y]}],right:[{right:[y]}],bottom:[{bottom:[y]}],left:[{left:[y]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Zx,On]}],basis:[{basis:R()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",On]}],grow:[{grow:P()}],shrink:[{shrink:P()}],order:[{order:["first","last","none",Zx,On]}],"grid-cols":[{"grid-cols":[Yx]}],"col-start-end":[{col:["auto",{span:["full",Zx,On]},On]}],"col-start":[{"col-start":z()}],"col-end":[{"col-end":z()}],"grid-rows":[{"grid-rows":[Yx]}],"row-start-end":[{row:["auto",{span:[Zx,On]},On]}],"row-start":[{"row-start":z()}],"row-end":[{"row-end":z()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",On]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",On]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...L()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...L(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...L(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[x]}],px:[{px:[x]}],py:[{py:[x]}],ps:[{ps:[x]}],pe:[{pe:[x]}],pt:[{pt:[x]}],pr:[{pr:[x]}],pb:[{pb:[x]}],pl:[{pl:[x]}],m:[{m:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"space-x":[{"space-x":[B]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[B]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",On,e]}],"min-w":[{"min-w":[On,e,"min","max","fit"]}],"max-w":[{"max-w":[On,e,"none","full","min","max","fit","prose",{screen:[Lp]},Lp]}],h:[{h:[On,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[On,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[On,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[On,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Lp,Mp]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",UO]}],"font-family":[{font:[Yx]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",On]}],"line-clamp":[{"line-clamp":["none",rv,UO]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",jf,On]}],"list-image":[{"list-image":["none",On]}],"list-style-type":[{list:["none","disc","decimal",On]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...T(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",jf,Mp]}],"underline-offset":[{"underline-offset":["auto",jf,On]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:M()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",On]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",On]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...N(),a4e]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",o4e]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},l4e]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[m]}],"gradient-via-pos":[{via:[m]}],"gradient-to-pos":[{to:[m]}],"gradient-from":[{from:[p]}],"gradient-via":[{via:[p]}],"gradient-to":[{to:[p]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[a]}],"border-w-x":[{"border-x":[a]}],"border-w-y":[{"border-y":[a]}],"border-w-s":[{"border-s":[a]}],"border-w-e":[{"border-e":[a]}],"border-w-t":[{"border-t":[a]}],"border-w-r":[{"border-r":[a]}],"border-w-b":[{"border-b":[a]}],"border-w-l":[{"border-l":[a]}],"border-opacity":[{"border-opacity":[v]}],"border-style":[{border:[...T(),"hidden"]}],"divide-x":[{"divide-x":[a]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[a]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[v]}],"divide-style":[{divide:T()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-s":[{"border-s":[s]}],"border-color-e":[{"border-e":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...T()]}],"outline-offset":[{"outline-offset":[jf,On]}],"outline-w":[{outline:[jf,Mp]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:j()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[jf,Mp]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Lp,u4e]}],"shadow-color":[{shadow:[Yx]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...U(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":U()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Lp,On]}],grayscale:[{grayscale:[l]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[d]}],saturate:[{saturate:[E]}],sepia:[{sepia:[_]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[l]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[d]}],"backdrop-opacity":[{"backdrop-opacity":[v]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[_]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",On]}],duration:[{duration:Y()}],ease:[{ease:["linear","in","out","in-out",On]}],delay:[{delay:Y()}],animate:[{animate:["none","spin","ping","pulse","bounce",On]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[A]}],"scale-x":[{"scale-x":[A]}],"scale-y":[{"scale-y":[A]}],rotate:[{rotate:[Zx,On]}],"translate-x":[{"translate-x":[W]}],"translate-y":[{"translate-y":[W]}],"skew-x":[{"skew-x":[k]}],"skew-y":[{"skew-y":[k]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",On]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",On]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":M()}],"scroll-mx":[{"scroll-mx":M()}],"scroll-my":[{"scroll-my":M()}],"scroll-ms":[{"scroll-ms":M()}],"scroll-me":[{"scroll-me":M()}],"scroll-mt":[{"scroll-mt":M()}],"scroll-mr":[{"scroll-mr":M()}],"scroll-mb":[{"scroll-mb":M()}],"scroll-ml":[{"scroll-ml":M()}],"scroll-p":[{"scroll-p":M()}],"scroll-px":[{"scroll-px":M()}],"scroll-py":[{"scroll-py":M()}],"scroll-ps":[{"scroll-ps":M()}],"scroll-pe":[{"scroll-pe":M()}],"scroll-pt":[{"scroll-pt":M()}],"scroll-pr":[{"scroll-pr":M()}],"scroll-pb":[{"scroll-pb":M()}],"scroll-pl":[{"scroll-pl":M()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",On]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[jf,Mp,UO]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},g4e=YNe(p4e);function Dt(...t){return g4e(pae(t))}function FO(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function jO(t){const e=new Uint8Array(t.length/2);for(let n=0;nw.jsx(aae,{ref:n,className:Dt("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",t),...e}));Nae.displayName=aae.displayName;const w4e=pP("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),Pae=I.forwardRef(({className:t,variant:e,...n},r)=>w.jsx(cae,{ref:r,className:Dt(w4e({variant:e}),t),...n}));Pae.displayName=cae.displayName;const b4e=I.forwardRef(({className:t,...e},n)=>w.jsx(dae,{ref:n,className:Dt("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",t),...e}));b4e.displayName=dae.displayName;const kae=I.forwardRef(({className:t,...e},n)=>w.jsx(fae,{ref:n,className:Dt("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",t),"toast-close":"",...e,children:w.jsx(wP,{className:"h-4 w-4"})}));kae.displayName=fae.displayName;const Rae=I.forwardRef(({className:t,...e},n)=>w.jsx(lae,{ref:n,className:Dt("text-sm font-semibold",t),...e}));Rae.displayName=lae.displayName;const Oae=I.forwardRef(({className:t,...e},n)=>w.jsx(uae,{ref:n,className:Dt("text-sm opacity-90",t),...e}));Oae.displayName=uae.displayName;function v4e(){const{toasts:t}=xf();return w.jsxs(y4e,{children:[t.map(function({id:e,title:n,description:r,action:s,...i}){return w.jsxs(Pae,{...i,children:[w.jsxs("div",{className:"grid gap-1",children:[n&&w.jsx(Rae,{children:n}),r&&w.jsx(Oae,{children:r})]}),s,w.jsx(kae,{})]},e)}),w.jsx(Nae,{})]})}var WZ=["light","dark"],x4e="(prefers-color-scheme: dark)",E4e=I.createContext(void 0),C4e={setTheme:t=>{},themes:[]},_4e=()=>{var t;return(t=I.useContext(E4e))!=null?t:C4e};I.memo(({forcedTheme:t,storageKey:e,attribute:n,enableSystem:r,enableColorScheme:s,defaultTheme:i,value:o,attrs:a,nonce:c})=>{let l=i==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${a.map(m=>`'${m}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,d=s?WZ.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",f=(m,y=!1,b=!0)=>{let v=o?o[m]:m,x=y?m+"|| ''":`'${v}'`,E="";return s&&b&&!y&&WZ.includes(m)&&(E+=`d.style.colorScheme = '${m}';`),n==="class"?y||v?E+=`c.add(${x})`:E+="null":v&&(E+=`d[s](n,${x})`),E},p=t?`!function(){${u}${f(t)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${e}');if('system'===e||(!e&&${l})){var t='${x4e}',m=window.matchMedia(t);if(m.media!==t||m.matches){${f("dark")}}else{${f("light")}}}else if(e){${o?`var x=${JSON.stringify(o)};`:""}${f(o?"x[e]":"e",!0)}}${l?"":"else{"+f(i,!1,!1)+"}"}${d}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${e}');if(e){${o?`var x=${JSON.stringify(o)};`:""}${f(o?"x[e]":"e",!0)}}else{${f(i,!1,!1)};}${d}}catch(t){}}();`;return I.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:p}})});var S4e=t=>{switch(t){case"success":return T4e;case"info":return P4e;case"warning":return N4e;case"error":return k4e;default:return null}},A4e=Array(12).fill(0),I4e=({visible:t})=>qe.createElement("div",{className:"sonner-loading-wrapper","data-visible":t},qe.createElement("div",{className:"sonner-spinner"},A4e.map((e,n)=>qe.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),T4e=qe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},qe.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),N4e=qe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},qe.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),P4e=qe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},qe.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),k4e=qe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},qe.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),R4e=()=>{let[t,e]=qe.useState(document.hidden);return qe.useEffect(()=>{let n=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),t},tL=1,O4e=class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let n=this.subscribers.indexOf(e);this.subscribers.splice(n,1)}),this.publish=e=>{this.subscribers.forEach(n=>n(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var n;let{message:r,...s}=e,i=typeof e?.id=="number"||((n=e.id)==null?void 0:n.length)>0?e.id:tL++,o=this.toasts.find(c=>c.id===i),a=e.dismissible===void 0?!0:e.dismissible;return o?this.toasts=this.toasts.map(c=>c.id===i?(this.publish({...c,...e,id:i,title:r}),{...c,...e,id:i,dismissible:a,title:r}):c):this.addToast({title:r,...s,dismissible:a,id:i}),i},this.dismiss=e=>(e||this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),this.subscribers.forEach(n=>n({id:e,dismiss:!0})),e),this.message=(e,n)=>this.create({...n,message:e}),this.error=(e,n)=>this.create({...n,message:e,type:"error"}),this.success=(e,n)=>this.create({...n,type:"success",message:e}),this.info=(e,n)=>this.create({...n,type:"info",message:e}),this.warning=(e,n)=>this.create({...n,type:"warning",message:e}),this.loading=(e,n)=>this.create({...n,type:"loading",message:e}),this.promise=(e,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:e,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));let s=e instanceof Promise?e:e(),i=r!==void 0;return s.then(async o=>{if(D4e(o)&&!o.ok){i=!1;let a=typeof n.error=="function"?await n.error(`HTTP error! status: ${o.status}`):n.error,c=typeof n.description=="function"?await n.description(`HTTP error! status: ${o.status}`):n.description;this.create({id:r,type:"error",message:a,description:c})}else if(n.success!==void 0){i=!1;let a=typeof n.success=="function"?await n.success(o):n.success,c=typeof n.description=="function"?await n.description(o):n.description;this.create({id:r,type:"success",message:a,description:c})}}).catch(async o=>{if(n.error!==void 0){i=!1;let a=typeof n.error=="function"?await n.error(o):n.error,c=typeof n.description=="function"?await n.description(o):n.description;this.create({id:r,type:"error",message:a,description:c})}}).finally(()=>{var o;i&&(this.dismiss(r),r=void 0),(o=n.finally)==null||o.call(n)}),r},this.custom=(e,n)=>{let r=n?.id||tL++;return this.create({jsx:e(r),id:r,...n}),r},this.subscribers=[],this.toasts=[]}},Sc=new O4e,$4e=(t,e)=>{let n=e?.id||tL++;return Sc.addToast({title:t,...e,id:n}),n},D4e=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",M4e=$4e,L4e=()=>Sc.toasts;Object.assign(M4e,{success:Sc.success,info:Sc.info,warning:Sc.warning,error:Sc.error,custom:Sc.custom,message:Sc.message,promise:Sc.promise,dismiss:Sc.dismiss,loading:Sc.loading},{getHistory:L4e});function B4e(t,{insertAt:e}={}){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",e==="top"&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=t:r.appendChild(document.createTextNode(t))}B4e(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999}:where([data-sonner-toaster][data-x-position="right"]){right:max(var(--offset),env(safe-area-inset-right))}:where([data-sonner-toaster][data-x-position="left"]){left:max(var(--offset),env(safe-area-inset-left))}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:max(var(--offset),env(safe-area-inset-top))}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:max(var(--offset),env(safe-area-inset-bottom))}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;background:var(--gray1);color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:0;right:0;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount, 0px));transition:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation:swipe-out .2s ease-out forwards}@keyframes swipe-out{0%{transform:translateY(calc(var(--lift) * var(--offset) + var(--swipe-amount)));opacity:1}to{transform:translateY(calc(var(--lift) * var(--offset) + var(--swipe-amount) + var(--lift) * -100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;--mobile-offset: 16px;right:var(--mobile-offset);left:var(--mobile-offset);width:100%}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset)}[data-sonner-toaster][data-y-position=bottom]{bottom:20px}[data-sonner-toaster][data-y-position=top]{top:20px}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset);right:var(--mobile-offset);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)} +`);function rA(t){return t.label!==void 0}var U4e=3,F4e="32px",j4e=4e3,z4e=356,W4e=14,V4e=20,H4e=200;function q4e(...t){return t.filter(Boolean).join(" ")}var K4e=t=>{var e,n,r,s,i,o,a,c,l,u;let{invert:d,toast:f,unstyled:p,interacting:m,setHeights:y,visibleToasts:b,heights:v,index:x,toasts:E,expanded:A,removeToast:_,defaultRichColors:k,closeButton:B,style:W,cancelButtonStyle:S,actionButtonStyle:$,className:R="",descriptionClassName:M="",duration:j,position:z,gap:N,loadingIcon:T,expandByDefault:U,classNames:L,icons:P,closeButtonAriaLabel:H="Close toast",pauseWhenPageIsHidden:Y,cn:re}=t,[de,fe]=qe.useState(!1),[ve,Ee]=qe.useState(!1),[oe,Oe]=qe.useState(!1),[je,V]=qe.useState(!1),[we,Ae]=qe.useState(0),[Ie,ge]=qe.useState(0),Me=qe.useRef(null),be=qe.useRef(null),pe=x===0,J=x+1<=b,ie=f.type,ae=f.dismissible!==!1,Pe=f.className||"",$e=f.descriptionClassName||"",Re=qe.useMemo(()=>v.findIndex(bt=>bt.toastId===f.id)||0,[v,f.id]),ut=qe.useMemo(()=>{var bt;return(bt=f.closeButton)!=null?bt:B},[f.closeButton,B]),Je=qe.useMemo(()=>f.duration||j||j4e,[f.duration,j]),ft=qe.useRef(0),Z=qe.useRef(0),O=qe.useRef(0),F=qe.useRef(null),[ne,he]=z.split("-"),Te=qe.useMemo(()=>v.reduce((bt,Gn,Zn)=>Zn>=Re?bt:bt+Gn.height,0),[v,Re]),Fe=R4e(),Bt=f.invert||d,vn=ie==="loading";Z.current=qe.useMemo(()=>Re*N+Te,[Re,Te]),qe.useEffect(()=>{fe(!0)},[]),qe.useLayoutEffect(()=>{if(!de)return;let bt=be.current,Gn=bt.style.height;bt.style.height="auto";let Zn=bt.getBoundingClientRect().height;bt.style.height=Gn,ge(Zn),y(Ls=>Ls.find(Is=>Is.toastId===f.id)?Ls.map(Is=>Is.toastId===f.id?{...Is,height:Zn}:Is):[{toastId:f.id,height:Zn,position:f.position},...Ls])},[de,f.title,f.description,y,f.id]);let Kt=qe.useCallback(()=>{Ee(!0),Ae(Z.current),y(bt=>bt.filter(Gn=>Gn.toastId!==f.id)),setTimeout(()=>{_(f)},H4e)},[f,_,y,Z]);qe.useEffect(()=>{if(f.promise&&ie==="loading"||f.duration===1/0||f.type==="loading")return;let bt,Gn=Je;return A||m||Y&&Fe?(()=>{if(O.current{var Zn;(Zn=f.onAutoClose)==null||Zn.call(f,f),Kt()},Gn)),()=>clearTimeout(bt)},[A,m,U,f,Je,Kt,f.promise,ie,Y,Fe]),qe.useEffect(()=>{let bt=be.current;if(bt){let Gn=bt.getBoundingClientRect().height;return ge(Gn),y(Zn=>[{toastId:f.id,height:Gn,position:f.position},...Zn]),()=>y(Zn=>Zn.filter(Ls=>Ls.toastId!==f.id))}},[y,f.id]),qe.useEffect(()=>{f.delete&&Kt()},[Kt,f.delete]);function Dn(){return P!=null&&P.loading?qe.createElement("div",{className:"sonner-loader","data-visible":ie==="loading"},P.loading):T?qe.createElement("div",{className:"sonner-loader","data-visible":ie==="loading"},T):qe.createElement(I4e,{visible:ie==="loading"})}return qe.createElement("li",{"aria-live":f.important?"assertive":"polite","aria-atomic":"true",role:"status",tabIndex:0,ref:be,className:re(R,Pe,L?.toast,(e=f?.classNames)==null?void 0:e.toast,L?.default,L?.[ie],(n=f?.classNames)==null?void 0:n[ie]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:k,"data-styled":!(f.jsx||f.unstyled||p),"data-mounted":de,"data-promise":!!f.promise,"data-removed":ve,"data-visible":J,"data-y-position":ne,"data-x-position":he,"data-index":x,"data-front":pe,"data-swiping":oe,"data-dismissible":ae,"data-type":ie,"data-invert":Bt,"data-swipe-out":je,"data-expanded":!!(A||U&&de),style:{"--index":x,"--toasts-before":x,"--z-index":E.length-x,"--offset":`${ve?we:Z.current}px`,"--initial-height":U?"auto":`${Ie}px`,...W,...f.style},onPointerDown:bt=>{vn||!ae||(Me.current=new Date,Ae(Z.current),bt.target.setPointerCapture(bt.pointerId),bt.target.tagName!=="BUTTON"&&(Oe(!0),F.current={x:bt.clientX,y:bt.clientY}))},onPointerUp:()=>{var bt,Gn,Zn,Ls;if(je||!ae)return;F.current=null;let Is=Number(((bt=be.current)==null?void 0:bt.style.getPropertyValue("--swipe-amount").replace("px",""))||0),ha=new Date().getTime()-((Gn=Me.current)==null?void 0:Gn.getTime()),iu=Math.abs(Is)/ha;if(Math.abs(Is)>=V4e||iu>.11){Ae(Z.current),(Zn=f.onDismiss)==null||Zn.call(f,f),Kt(),V(!0);return}(Ls=be.current)==null||Ls.style.setProperty("--swipe-amount","0px"),Oe(!1)},onPointerMove:bt=>{var Gn;if(!F.current||!ae)return;let Zn=bt.clientY-F.current.y,Ls=bt.clientX-F.current.x,Is=(ne==="top"?Math.min:Math.max)(0,Zn),ha=bt.pointerType==="touch"?10:2;Math.abs(Is)>ha?(Gn=be.current)==null||Gn.style.setProperty("--swipe-amount",`${Zn}px`):Math.abs(Ls)>ha&&(F.current=null)}},ut&&!f.jsx?qe.createElement("button",{"aria-label":H,"data-disabled":vn,"data-close-button":!0,onClick:vn||!ae?()=>{}:()=>{var bt;Kt(),(bt=f.onDismiss)==null||bt.call(f,f)},className:re(L?.closeButton,(s=f?.classNames)==null?void 0:s.closeButton)},qe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},qe.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),qe.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"}))):null,f.jsx||qe.isValidElement(f.title)?f.jsx||f.title:qe.createElement(qe.Fragment,null,ie||f.icon||f.promise?qe.createElement("div",{"data-icon":"",className:re(L?.icon,(i=f?.classNames)==null?void 0:i.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||Dn():null,f.type!=="loading"?f.icon||P?.[ie]||S4e(ie):null):null,qe.createElement("div",{"data-content":"",className:re(L?.content,(o=f?.classNames)==null?void 0:o.content)},qe.createElement("div",{"data-title":"",className:re(L?.title,(a=f?.classNames)==null?void 0:a.title)},f.title),f.description?qe.createElement("div",{"data-description":"",className:re(M,$e,L?.description,(c=f?.classNames)==null?void 0:c.description)},f.description):null),qe.isValidElement(f.cancel)?f.cancel:f.cancel&&rA(f.cancel)?qe.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||S,onClick:bt=>{var Gn,Zn;rA(f.cancel)&&ae&&((Zn=(Gn=f.cancel).onClick)==null||Zn.call(Gn,bt),Kt())},className:re(L?.cancelButton,(l=f?.classNames)==null?void 0:l.cancelButton)},f.cancel.label):null,qe.isValidElement(f.action)?f.action:f.action&&rA(f.action)?qe.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||$,onClick:bt=>{var Gn,Zn;rA(f.action)&&(bt.defaultPrevented||((Zn=(Gn=f.action).onClick)==null||Zn.call(Gn,bt),Kt()))},className:re(L?.actionButton,(u=f?.classNames)==null?void 0:u.actionButton)},f.action.label):null))};function VZ(){if(typeof window>"u"||typeof document>"u")return"ltr";let t=document.documentElement.getAttribute("dir");return t==="auto"||!t?window.getComputedStyle(document.documentElement).direction:t}var G4e=t=>{let{invert:e,position:n="bottom-right",hotkey:r=["altKey","KeyT"],expand:s,closeButton:i,className:o,offset:a,theme:c="light",richColors:l,duration:u,style:d,visibleToasts:f=U4e,toastOptions:p,dir:m=VZ(),gap:y=W4e,loadingIcon:b,icons:v,containerAriaLabel:x="Notifications",pauseWhenPageIsHidden:E,cn:A=q4e}=t,[_,k]=qe.useState([]),B=qe.useMemo(()=>Array.from(new Set([n].concat(_.filter(Y=>Y.position).map(Y=>Y.position)))),[_,n]),[W,S]=qe.useState([]),[$,R]=qe.useState(!1),[M,j]=qe.useState(!1),[z,N]=qe.useState(c!=="system"?c:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),T=qe.useRef(null),U=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),L=qe.useRef(null),P=qe.useRef(!1),H=qe.useCallback(Y=>{var re;(re=_.find(de=>de.id===Y.id))!=null&&re.delete||Sc.dismiss(Y.id),k(de=>de.filter(({id:fe})=>fe!==Y.id))},[_]);return qe.useEffect(()=>Sc.subscribe(Y=>{if(Y.dismiss){k(re=>re.map(de=>de.id===Y.id?{...de,delete:!0}:de));return}setTimeout(()=>{Woe.flushSync(()=>{k(re=>{let de=re.findIndex(fe=>fe.id===Y.id);return de!==-1?[...re.slice(0,de),{...re[de],...Y},...re.slice(de+1)]:[Y,...re]})})})}),[]),qe.useEffect(()=>{if(c!=="system"){N(c);return}c==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?N("dark"):N("light")),typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",({matches:Y})=>{N(Y?"dark":"light")})},[c]),qe.useEffect(()=>{_.length<=1&&R(!1)},[_]),qe.useEffect(()=>{let Y=re=>{var de,fe;r.every(ve=>re[ve]||re.code===ve)&&(R(!0),(de=T.current)==null||de.focus()),re.code==="Escape"&&(document.activeElement===T.current||(fe=T.current)!=null&&fe.contains(document.activeElement))&&R(!1)};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[r]),qe.useEffect(()=>{if(T.current)return()=>{L.current&&(L.current.focus({preventScroll:!0}),L.current=null,P.current=!1)}},[T.current]),_.length?qe.createElement("section",{"aria-label":`${x} ${U}`,tabIndex:-1},B.map((Y,re)=>{var de;let[fe,ve]=Y.split("-");return qe.createElement("ol",{key:Y,dir:m==="auto"?VZ():m,tabIndex:-1,ref:T,className:o,"data-sonner-toaster":!0,"data-theme":z,"data-y-position":fe,"data-x-position":ve,style:{"--front-toast-height":`${((de=W[0])==null?void 0:de.height)||0}px`,"--offset":typeof a=="number"?`${a}px`:a||F4e,"--width":`${z4e}px`,"--gap":`${y}px`,...d},onBlur:Ee=>{P.current&&!Ee.currentTarget.contains(Ee.relatedTarget)&&(P.current=!1,L.current&&(L.current.focus({preventScroll:!0}),L.current=null))},onFocus:Ee=>{Ee.target instanceof HTMLElement&&Ee.target.dataset.dismissible==="false"||P.current||(P.current=!0,L.current=Ee.relatedTarget)},onMouseEnter:()=>R(!0),onMouseMove:()=>R(!0),onMouseLeave:()=>{M||R(!1)},onPointerDown:Ee=>{Ee.target instanceof HTMLElement&&Ee.target.dataset.dismissible==="false"||j(!0)},onPointerUp:()=>j(!1)},_.filter(Ee=>!Ee.position&&re===0||Ee.position===Y).map((Ee,oe)=>{var Oe,je;return qe.createElement(K4e,{key:Ee.id,icons:v,index:oe,toast:Ee,defaultRichColors:l,duration:(Oe=p?.duration)!=null?Oe:u,className:p?.className,descriptionClassName:p?.descriptionClassName,invert:e,visibleToasts:f,closeButton:(je=p?.closeButton)!=null?je:i,interacting:M,position:Y,style:p?.style,unstyled:p?.unstyled,classNames:p?.classNames,cancelButtonStyle:p?.cancelButtonStyle,actionButtonStyle:p?.actionButtonStyle,removeToast:H,toasts:_.filter(V=>V.position==Ee.position),heights:W.filter(V=>V.position==Ee.position),setHeights:S,expandByDefault:s,gap:y,loadingIcon:b,expanded:$,pauseWhenPageIsHidden:E,cn:A})}))})):null};const Z4e=({...t})=>{const{theme:e="system"}=_4e();return w.jsx(G4e,{theme:e,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...t})};var Y4e=Fse.useId||(()=>{}),X4e=0;function Wu(t){const[e,n]=I.useState(Y4e());return No(()=>{n(r=>r??String(X4e++))},[t]),e?`radix-${e}`:""}const Q4e=["top","right","bottom","left"],i0=Math.min,Pc=Math.max,Z6=Math.round,sA=Math.floor,o0=t=>({x:t,y:t}),J4e={left:"right",right:"left",bottom:"top",top:"bottom"},ePe={start:"end",end:"start"};function nL(t,e,n){return Pc(t,i0(e,n))}function Wh(t,e){return typeof t=="function"?t(e):t}function Vh(t){return t.split("-")[0]}function H1(t){return t.split("-")[1]}function KF(t){return t==="x"?"y":"x"}function GF(t){return t==="y"?"height":"width"}function a0(t){return["top","bottom"].includes(Vh(t))?"y":"x"}function ZF(t){return KF(a0(t))}function tPe(t,e,n){n===void 0&&(n=!1);const r=H1(t),s=ZF(t),i=GF(s);let o=s==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[i]>e.floating[i]&&(o=Y6(o)),[o,Y6(o)]}function nPe(t){const e=Y6(t);return[rL(t),e,rL(e)]}function rL(t){return t.replace(/start|end/g,e=>ePe[e])}function rPe(t,e,n){const r=["left","right"],s=["right","left"],i=["top","bottom"],o=["bottom","top"];switch(t){case"top":case"bottom":return n?e?s:r:e?r:s;case"left":case"right":return e?i:o;default:return[]}}function sPe(t,e,n,r){const s=H1(t);let i=rPe(Vh(t),n==="start",r);return s&&(i=i.map(o=>o+"-"+s),e&&(i=i.concat(i.map(rL)))),i}function Y6(t){return t.replace(/left|right|bottom|top/g,e=>J4e[e])}function iPe(t){return{top:0,right:0,bottom:0,left:0,...t}}function $ae(t){return typeof t!="number"?iPe(t):{top:t,right:t,bottom:t,left:t}}function X6(t){const{x:e,y:n,width:r,height:s}=t;return{width:r,height:s,top:n,left:e,right:e+r,bottom:n+s,x:e,y:n}}function HZ(t,e,n){let{reference:r,floating:s}=t;const i=a0(e),o=ZF(e),a=GF(o),c=Vh(e),l=i==="y",u=r.x+r.width/2-s.width/2,d=r.y+r.height/2-s.height/2,f=r[a]/2-s[a]/2;let p;switch(c){case"top":p={x:u,y:r.y-s.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:d};break;case"left":p={x:r.x-s.width,y:d};break;default:p={x:r.x,y:r.y}}switch(H1(e)){case"start":p[o]-=f*(n&&l?-1:1);break;case"end":p[o]+=f*(n&&l?-1:1);break}return p}const oPe=async(t,e,n)=>{const{placement:r="bottom",strategy:s="absolute",middleware:i=[],platform:o}=n,a=i.filter(Boolean),c=await(o.isRTL==null?void 0:o.isRTL(e));let l=await o.getElementRects({reference:t,floating:e,strategy:s}),{x:u,y:d}=HZ(l,r,c),f=r,p={},m=0;for(let y=0;y({name:"arrow",options:t,async fn(e){const{x:n,y:r,placement:s,rects:i,platform:o,elements:a,middlewareData:c}=e,{element:l,padding:u=0}=Wh(t,e)||{};if(l==null)return{};const d=$ae(u),f={x:n,y:r},p=ZF(s),m=GF(p),y=await o.getDimensions(l),b=p==="y",v=b?"top":"left",x=b?"bottom":"right",E=b?"clientHeight":"clientWidth",A=i.reference[m]+i.reference[p]-f[p]-i.floating[m],_=f[p]-i.reference[p],k=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l));let B=k?k[E]:0;(!B||!await(o.isElement==null?void 0:o.isElement(k)))&&(B=a.floating[E]||i.floating[m]);const W=A/2-_/2,S=B/2-y[m]/2-1,$=i0(d[v],S),R=i0(d[x],S),M=$,j=B-y[m]-R,z=B/2-y[m]/2+W,N=nL(M,z,j),T=!c.arrow&&H1(s)!=null&&z!==N&&i.reference[m]/2-(zz<=0)){var R,M;const z=(((R=i.flip)==null?void 0:R.index)||0)+1,N=B[z];if(N)return{data:{index:z,overflows:$},reset:{placement:N}};let T=(M=$.filter(U=>U.overflows[0]<=0).sort((U,L)=>U.overflows[1]-L.overflows[1])[0])==null?void 0:M.placement;if(!T)switch(p){case"bestFit":{var j;const U=(j=$.filter(L=>{if(k){const P=a0(L.placement);return P===x||P==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(P=>P>0).reduce((P,H)=>P+H,0)]).sort((L,P)=>L[1]-P[1])[0])==null?void 0:j[0];U&&(T=U);break}case"initialPlacement":T=a;break}if(s!==T)return{reset:{placement:T}}}return{}}}};function qZ(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function KZ(t){return Q4e.some(e=>t[e]>=0)}const lPe=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n}=e,{strategy:r="referenceHidden",...s}=Wh(t,e);switch(r){case"referenceHidden":{const i=await uC(e,{...s,elementContext:"reference"}),o=qZ(i,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:KZ(o)}}}case"escaped":{const i=await uC(e,{...s,altBoundary:!0}),o=qZ(i,n.floating);return{data:{escapedOffsets:o,escaped:KZ(o)}}}default:return{}}}}};async function uPe(t,e){const{placement:n,platform:r,elements:s}=t,i=await(r.isRTL==null?void 0:r.isRTL(s.floating)),o=Vh(n),a=H1(n),c=a0(n)==="y",l=["left","top"].includes(o)?-1:1,u=i&&c?-1:1,d=Wh(e,t);let{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}const dPe=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;const{x:s,y:i,placement:o,middlewareData:a}=e,c=await uPe(e,t);return o===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:s+c.x,y:i+c.y,data:{...c,placement:o}}}}},fPe=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:s}=e,{mainAxis:i=!0,crossAxis:o=!1,limiter:a={fn:b=>{let{x:v,y:x}=b;return{x:v,y:x}}},...c}=Wh(t,e),l={x:n,y:r},u=await uC(e,c),d=a0(Vh(s)),f=KF(d);let p=l[f],m=l[d];if(i){const b=f==="y"?"top":"left",v=f==="y"?"bottom":"right",x=p+u[b],E=p-u[v];p=nL(x,p,E)}if(o){const b=d==="y"?"top":"left",v=d==="y"?"bottom":"right",x=m+u[b],E=m-u[v];m=nL(x,m,E)}const y=a.fn({...e,[f]:p,[d]:m});return{...y,data:{x:y.x-n,y:y.y-r,enabled:{[f]:i,[d]:o}}}}}},hPe=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:n,y:r,placement:s,rects:i,middlewareData:o}=e,{offset:a=0,mainAxis:c=!0,crossAxis:l=!0}=Wh(t,e),u={x:n,y:r},d=a0(s),f=KF(d);let p=u[f],m=u[d];const y=Wh(a,e),b=typeof y=="number"?{mainAxis:y,crossAxis:0}:{mainAxis:0,crossAxis:0,...y};if(c){const E=f==="y"?"height":"width",A=i.reference[f]-i.floating[E]+b.mainAxis,_=i.reference[f]+i.reference[E]-b.mainAxis;p_&&(p=_)}if(l){var v,x;const E=f==="y"?"width":"height",A=["top","left"].includes(Vh(s)),_=i.reference[d]-i.floating[E]+(A&&((v=o.offset)==null?void 0:v[d])||0)+(A?0:b.crossAxis),k=i.reference[d]+i.reference[E]+(A?0:((x=o.offset)==null?void 0:x[d])||0)-(A?b.crossAxis:0);m<_?m=_:m>k&&(m=k)}return{[f]:p,[d]:m}}}},pPe=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,r;const{placement:s,rects:i,platform:o,elements:a}=e,{apply:c=()=>{},...l}=Wh(t,e),u=await uC(e,l),d=Vh(s),f=H1(s),p=a0(s)==="y",{width:m,height:y}=i.floating;let b,v;d==="top"||d==="bottom"?(b=d,v=f===(await(o.isRTL==null?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(v=d,b=f==="end"?"top":"bottom");const x=y-u.top-u.bottom,E=m-u.left-u.right,A=i0(y-u[b],x),_=i0(m-u[v],E),k=!e.middlewareData.shift;let B=A,W=_;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(W=E),(r=e.middlewareData.shift)!=null&&r.enabled.y&&(B=x),k&&!f){const $=Pc(u.left,0),R=Pc(u.right,0),M=Pc(u.top,0),j=Pc(u.bottom,0);p?W=m-2*($!==0||R!==0?$+R:Pc(u.left,u.right)):B=y-2*(M!==0||j!==0?M+j:Pc(u.top,u.bottom))}await c({...e,availableWidth:W,availableHeight:B});const S=await o.getDimensions(a.floating);return m!==S.width||y!==S.height?{reset:{rects:!0}}:{}}}};function bP(){return typeof window<"u"}function q1(t){return Dae(t)?(t.nodeName||"").toLowerCase():"#document"}function Lc(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Ef(t){var e;return(e=(Dae(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Dae(t){return bP()?t instanceof Node||t instanceof Lc(t).Node:!1}function ed(t){return bP()?t instanceof Element||t instanceof Lc(t).Element:!1}function af(t){return bP()?t instanceof HTMLElement||t instanceof Lc(t).HTMLElement:!1}function GZ(t){return!bP()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof Lc(t).ShadowRoot}function DS(t){const{overflow:e,overflowX:n,overflowY:r,display:s}=td(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!["inline","contents"].includes(s)}function gPe(t){return["table","td","th"].includes(q1(t))}function vP(t){return[":popover-open",":modal"].some(e=>{try{return t.matches(e)}catch{return!1}})}function YF(t){const e=XF(),n=ed(t)?td(t):t;return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function mPe(t){let e=c0(t);for(;af(e)&&!Pv(e);){if(YF(e))return e;if(vP(e))return null;e=c0(e)}return null}function XF(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Pv(t){return["html","body","#document"].includes(q1(t))}function td(t){return Lc(t).getComputedStyle(t)}function xP(t){return ed(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function c0(t){if(q1(t)==="html")return t;const e=t.assignedSlot||t.parentNode||GZ(t)&&t.host||Ef(t);return GZ(e)?e.host:e}function Mae(t){const e=c0(t);return Pv(e)?t.ownerDocument?t.ownerDocument.body:t.body:af(e)&&DS(e)?e:Mae(e)}function dC(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);const s=Mae(t),i=s===((r=t.ownerDocument)==null?void 0:r.body),o=Lc(s);if(i){const a=sL(o);return e.concat(o,o.visualViewport||[],DS(s)?s:[],a&&n?dC(a):[])}return e.concat(s,dC(s,[],n))}function sL(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Lae(t){const e=td(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const s=af(t),i=s?t.offsetWidth:n,o=s?t.offsetHeight:r,a=Z6(n)!==i||Z6(r)!==o;return a&&(n=i,r=o),{width:n,height:r,$:a}}function QF(t){return ed(t)?t:t.contextElement}function sv(t){const e=QF(t);if(!af(e))return o0(1);const n=e.getBoundingClientRect(),{width:r,height:s,$:i}=Lae(e);let o=(i?Z6(n.width):n.width)/r,a=(i?Z6(n.height):n.height)/s;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const yPe=o0(0);function Bae(t){const e=Lc(t);return!XF()||!e.visualViewport?yPe:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function wPe(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==Lc(t)?!1:e}function sy(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const s=t.getBoundingClientRect(),i=QF(t);let o=o0(1);e&&(r?ed(r)&&(o=sv(r)):o=sv(t));const a=wPe(i,n,r)?Bae(i):o0(0);let c=(s.left+a.x)/o.x,l=(s.top+a.y)/o.y,u=s.width/o.x,d=s.height/o.y;if(i){const f=Lc(i),p=r&&ed(r)?Lc(r):r;let m=f,y=sL(m);for(;y&&r&&p!==m;){const b=sv(y),v=y.getBoundingClientRect(),x=td(y),E=v.left+(y.clientLeft+parseFloat(x.paddingLeft))*b.x,A=v.top+(y.clientTop+parseFloat(x.paddingTop))*b.y;c*=b.x,l*=b.y,u*=b.x,d*=b.y,c+=E,l+=A,m=Lc(y),y=sL(m)}}return X6({width:u,height:d,x:c,y:l})}function bPe(t){let{elements:e,rect:n,offsetParent:r,strategy:s}=t;const i=s==="fixed",o=Ef(r),a=e?vP(e.floating):!1;if(r===o||a&&i)return n;let c={scrollLeft:0,scrollTop:0},l=o0(1);const u=o0(0),d=af(r);if((d||!d&&!i)&&((q1(r)!=="body"||DS(o))&&(c=xP(r)),af(r))){const f=sy(r);l=sv(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x,y:n.y*l.y-c.scrollTop*l.y+u.y}}function vPe(t){return Array.from(t.getClientRects())}function iL(t,e){const n=xP(t).scrollLeft;return e?e.left+n:sy(Ef(t)).left+n}function xPe(t){const e=Ef(t),n=xP(t),r=t.ownerDocument.body,s=Pc(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),i=Pc(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+iL(t);const a=-n.scrollTop;return td(r).direction==="rtl"&&(o+=Pc(e.clientWidth,r.clientWidth)-s),{width:s,height:i,x:o,y:a}}function EPe(t,e){const n=Lc(t),r=Ef(t),s=n.visualViewport;let i=r.clientWidth,o=r.clientHeight,a=0,c=0;if(s){i=s.width,o=s.height;const l=XF();(!l||l&&e==="fixed")&&(a=s.offsetLeft,c=s.offsetTop)}return{width:i,height:o,x:a,y:c}}function CPe(t,e){const n=sy(t,!0,e==="fixed"),r=n.top+t.clientTop,s=n.left+t.clientLeft,i=af(t)?sv(t):o0(1),o=t.clientWidth*i.x,a=t.clientHeight*i.y,c=s*i.x,l=r*i.y;return{width:o,height:a,x:c,y:l}}function ZZ(t,e,n){let r;if(e==="viewport")r=EPe(t,n);else if(e==="document")r=xPe(Ef(t));else if(ed(e))r=CPe(e,n);else{const s=Bae(t);r={...e,x:e.x-s.x,y:e.y-s.y}}return X6(r)}function Uae(t,e){const n=c0(t);return n===e||!ed(n)||Pv(n)?!1:td(n).position==="fixed"||Uae(n,e)}function _Pe(t,e){const n=e.get(t);if(n)return n;let r=dC(t,[],!1).filter(a=>ed(a)&&q1(a)!=="body"),s=null;const i=td(t).position==="fixed";let o=i?c0(t):t;for(;ed(o)&&!Pv(o);){const a=td(o),c=YF(o);!c&&a.position==="fixed"&&(s=null),(i?!c&&!s:!c&&a.position==="static"&&!!s&&["absolute","fixed"].includes(s.position)||DS(o)&&!c&&Uae(t,o))?r=r.filter(u=>u!==o):s=a,o=c0(o)}return e.set(t,r),r}function SPe(t){let{element:e,boundary:n,rootBoundary:r,strategy:s}=t;const o=[...n==="clippingAncestors"?vP(e)?[]:_Pe(e,this._c):[].concat(n),r],a=o[0],c=o.reduce((l,u)=>{const d=ZZ(e,u,s);return l.top=Pc(d.top,l.top),l.right=i0(d.right,l.right),l.bottom=i0(d.bottom,l.bottom),l.left=Pc(d.left,l.left),l},ZZ(e,a,s));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function APe(t){const{width:e,height:n}=Lae(t);return{width:e,height:n}}function IPe(t,e,n){const r=af(e),s=Ef(e),i=n==="fixed",o=sy(t,!0,i,e);let a={scrollLeft:0,scrollTop:0};const c=o0(0);if(r||!r&&!i)if((q1(e)!=="body"||DS(s))&&(a=xP(e)),r){const p=sy(e,!0,i,e);c.x=p.x+e.clientLeft,c.y=p.y+e.clientTop}else s&&(c.x=iL(s));let l=0,u=0;if(s&&!r&&!i){const p=s.getBoundingClientRect();u=p.top+a.scrollTop,l=p.left+a.scrollLeft-iL(s,p)}const d=o.left+a.scrollLeft-c.x-l,f=o.top+a.scrollTop-c.y-u;return{x:d,y:f,width:o.width,height:o.height}}function zO(t){return td(t).position==="static"}function YZ(t,e){if(!af(t)||td(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return Ef(t)===n&&(n=n.ownerDocument.body),n}function Fae(t,e){const n=Lc(t);if(vP(t))return n;if(!af(t)){let s=c0(t);for(;s&&!Pv(s);){if(ed(s)&&!zO(s))return s;s=c0(s)}return n}let r=YZ(t,e);for(;r&&gPe(r)&&zO(r);)r=YZ(r,e);return r&&Pv(r)&&zO(r)&&!YF(r)?n:r||mPe(t)||n}const TPe=async function(t){const e=this.getOffsetParent||Fae,n=this.getDimensions,r=await n(t.floating);return{reference:IPe(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function NPe(t){return td(t).direction==="rtl"}const PPe={convertOffsetParentRelativeRectToViewportRelativeRect:bPe,getDocumentElement:Ef,getClippingRect:SPe,getOffsetParent:Fae,getElementRects:TPe,getClientRects:vPe,getDimensions:APe,getScale:sv,isElement:ed,isRTL:NPe};function kPe(t,e){let n=null,r;const s=Ef(t);function i(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function o(a,c){a===void 0&&(a=!1),c===void 0&&(c=1),i();const{left:l,top:u,width:d,height:f}=t.getBoundingClientRect();if(a||e(),!d||!f)return;const p=sA(u),m=sA(s.clientWidth-(l+d)),y=sA(s.clientHeight-(u+f)),b=sA(l),x={rootMargin:-p+"px "+-m+"px "+-y+"px "+-b+"px",threshold:Pc(0,i0(1,c))||1};let E=!0;function A(_){const k=_[0].intersectionRatio;if(k!==c){if(!E)return o();k?o(!1,k):r=setTimeout(()=>{o(!1,1e-7)},1e3)}E=!1}try{n=new IntersectionObserver(A,{...x,root:s.ownerDocument})}catch{n=new IntersectionObserver(A,x)}n.observe(t)}return o(!0),i}function RPe(t,e,n,r){r===void 0&&(r={});const{ancestorScroll:s=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,l=QF(t),u=s||i?[...l?dC(l):[],...dC(e)]:[];u.forEach(v=>{s&&v.addEventListener("scroll",n,{passive:!0}),i&&v.addEventListener("resize",n)});const d=l&&a?kPe(l,n):null;let f=-1,p=null;o&&(p=new ResizeObserver(v=>{let[x]=v;x&&x.target===l&&p&&(p.unobserve(e),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var E;(E=p)==null||E.observe(e)})),n()}),l&&!c&&p.observe(l),p.observe(e));let m,y=c?sy(t):null;c&&b();function b(){const v=sy(t);y&&(v.x!==y.x||v.y!==y.y||v.width!==y.width||v.height!==y.height)&&n(),y=v,m=requestAnimationFrame(b)}return n(),()=>{var v;u.forEach(x=>{s&&x.removeEventListener("scroll",n),i&&x.removeEventListener("resize",n)}),d?.(),(v=p)==null||v.disconnect(),p=null,c&&cancelAnimationFrame(m)}}const OPe=dPe,$Pe=fPe,DPe=cPe,MPe=pPe,LPe=lPe,XZ=aPe,BPe=hPe,UPe=(t,e,n)=>{const r=new Map,s={platform:PPe,...n},i={...s.platform,_c:r};return oPe(t,e,{...s,platform:i})};var LI=typeof document<"u"?I.useLayoutEffect:I.useEffect;function Q6(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let n,r,s;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(n=t.length,n!==e.length)return!1;for(r=n;r--!==0;)if(!Q6(t[r],e[r]))return!1;return!0}if(s=Object.keys(t),n=s.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(e,s[r]))return!1;for(r=n;r--!==0;){const i=s[r];if(!(i==="_owner"&&t.$$typeof)&&!Q6(t[i],e[i]))return!1}return!0}return t!==t&&e!==e}function jae(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function QZ(t,e){const n=jae(t);return Math.round(e*n)/n}function WO(t){const e=I.useRef(t);return LI(()=>{e.current=t}),e}function FPe(t){t===void 0&&(t={});const{placement:e="bottom",strategy:n="absolute",middleware:r=[],platform:s,elements:{reference:i,floating:o}={},transform:a=!0,whileElementsMounted:c,open:l}=t,[u,d]=I.useState({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[f,p]=I.useState(r);Q6(f,r)||p(r);const[m,y]=I.useState(null),[b,v]=I.useState(null),x=I.useCallback(L=>{L!==k.current&&(k.current=L,y(L))},[]),E=I.useCallback(L=>{L!==B.current&&(B.current=L,v(L))},[]),A=i||m,_=o||b,k=I.useRef(null),B=I.useRef(null),W=I.useRef(u),S=c!=null,$=WO(c),R=WO(s),M=WO(l),j=I.useCallback(()=>{if(!k.current||!B.current)return;const L={placement:e,strategy:n,middleware:f};R.current&&(L.platform=R.current),UPe(k.current,B.current,L).then(P=>{const H={...P,isPositioned:M.current!==!1};z.current&&!Q6(W.current,H)&&(W.current=H,Qy.flushSync(()=>{d(H)}))})},[f,e,n,R,M]);LI(()=>{l===!1&&W.current.isPositioned&&(W.current.isPositioned=!1,d(L=>({...L,isPositioned:!1})))},[l]);const z=I.useRef(!1);LI(()=>(z.current=!0,()=>{z.current=!1}),[]),LI(()=>{if(A&&(k.current=A),_&&(B.current=_),A&&_){if($.current)return $.current(A,_,j);j()}},[A,_,j,$,S]);const N=I.useMemo(()=>({reference:k,floating:B,setReference:x,setFloating:E}),[x,E]),T=I.useMemo(()=>({reference:A,floating:_}),[A,_]),U=I.useMemo(()=>{const L={position:n,left:0,top:0};if(!T.floating)return L;const P=QZ(T.floating,u.x),H=QZ(T.floating,u.y);return a?{...L,transform:"translate("+P+"px, "+H+"px)",...jae(T.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:P,top:H}},[n,a,T.floating,u.x,u.y]);return I.useMemo(()=>({...u,update:j,refs:N,elements:T,floatingStyles:U}),[u,j,N,T,U])}const jPe=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){const{element:r,padding:s}=typeof t=="function"?t(n):t;return r&&e(r)?r.current!=null?XZ({element:r.current,padding:s}).fn(n):{}:r?XZ({element:r,padding:s}).fn(n):{}}}},zPe=(t,e)=>({...OPe(t),options:[t,e]}),WPe=(t,e)=>({...$Pe(t),options:[t,e]}),VPe=(t,e)=>({...BPe(t),options:[t,e]}),HPe=(t,e)=>({...DPe(t),options:[t,e]}),qPe=(t,e)=>({...MPe(t),options:[t,e]}),KPe=(t,e)=>({...LPe(t),options:[t,e]}),GPe=(t,e)=>({...jPe(t),options:[t,e]});var ZPe="Arrow",zae=I.forwardRef((t,e)=>{const{children:n,width:r=10,height:s=5,...i}=t;return w.jsx(gn.svg,{...i,ref:e,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:w.jsx("polygon",{points:"0,0 30,0 15,10"})})});zae.displayName=ZPe;var YPe=zae;function XPe(t,e=[]){let n=[];function r(i,o){const a=I.createContext(o),c=n.length;n=[...n,o];function l(d){const{scope:f,children:p,...m}=d,y=f?.[t][c]||a,b=I.useMemo(()=>m,Object.values(m));return w.jsx(y.Provider,{value:b,children:p})}function u(d,f){const p=f?.[t][c]||a,m=I.useContext(p);if(m)return m;if(o!==void 0)return o;throw new Error(`\`${d}\` must be used within \`${i}\``)}return l.displayName=i+"Provider",[l,u]}const s=()=>{const i=n.map(o=>I.createContext(o));return function(a){const c=a?.[t]||i;return I.useMemo(()=>({[`__scope${t}`]:{...a,[t]:c}}),[a,c])}};return s.scopeName=t,[r,QPe(s,...e)]}function QPe(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(i){const o=r.reduce((a,{useScope:c,scopeName:l})=>{const d=c(i)[`__scope${l}`];return{...a,...d}},{});return I.useMemo(()=>({[`__scope${e.scopeName}`]:o}),[o])}};return n.scopeName=e.scopeName,n}function Wae(t){const[e,n]=I.useState(void 0);return No(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const i=s[0];let o,a;if("borderBoxSize"in i){const c=i.borderBoxSize,l=Array.isArray(c)?c[0]:c;o=l.inlineSize,a=l.blockSize}else o=t.offsetWidth,a=t.offsetHeight;n({width:o,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}var JF="Popper",[Vae,K1]=XPe(JF),[JPe,Hae]=Vae(JF),qae=t=>{const{__scopePopper:e,children:n}=t,[r,s]=I.useState(null);return w.jsx(JPe,{scope:e,anchor:r,onAnchorChange:s,children:n})};qae.displayName=JF;var Kae="PopperAnchor",Gae=I.forwardRef((t,e)=>{const{__scopePopper:n,virtualRef:r,...s}=t,i=Hae(Kae,n),o=I.useRef(null),a=ir(e,o);return I.useEffect(()=>{i.onAnchorChange(r?.current||o.current)}),r?null:w.jsx(gn.div,{...s,ref:a})});Gae.displayName=Kae;var ej="PopperContent",[eke,tke]=Vae(ej),Zae=I.forwardRef((t,e)=>{const{__scopePopper:n,side:r="bottom",sideOffset:s=0,align:i="center",alignOffset:o=0,arrowPadding:a=0,avoidCollisions:c=!0,collisionBoundary:l=[],collisionPadding:u=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:m,...y}=t,b=Hae(ej,n),[v,x]=I.useState(null),E=ir(e,oe=>x(oe)),[A,_]=I.useState(null),k=Wae(A),B=k?.width??0,W=k?.height??0,S=r+(i!=="center"?"-"+i:""),$=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},R=Array.isArray(l)?l:[l],M=R.length>0,j={padding:$,boundary:R.filter(rke),altBoundary:M},{refs:z,floatingStyles:N,placement:T,isPositioned:U,middlewareData:L}=FPe({strategy:"fixed",placement:S,whileElementsMounted:(...oe)=>RPe(...oe,{animationFrame:p==="always"}),elements:{reference:b.anchor},middleware:[zPe({mainAxis:s+W,alignmentAxis:o}),c&&WPe({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?VPe():void 0,...j}),c&&HPe({...j}),qPe({...j,apply:({elements:oe,rects:Oe,availableWidth:je,availableHeight:V})=>{const{width:we,height:Ae}=Oe.reference,Ie=oe.floating.style;Ie.setProperty("--radix-popper-available-width",`${je}px`),Ie.setProperty("--radix-popper-available-height",`${V}px`),Ie.setProperty("--radix-popper-anchor-width",`${we}px`),Ie.setProperty("--radix-popper-anchor-height",`${Ae}px`)}}),A&&GPe({element:A,padding:a}),ske({arrowWidth:B,arrowHeight:W}),f&&KPe({strategy:"referenceHidden",...j})]}),[P,H]=Qae(T),Y=To(m);No(()=>{U&&Y?.()},[U,Y]);const re=L.arrow?.x,de=L.arrow?.y,fe=L.arrow?.centerOffset!==0,[ve,Ee]=I.useState();return No(()=>{v&&Ee(window.getComputedStyle(v).zIndex)},[v]),w.jsx("div",{ref:z.setFloating,"data-radix-popper-content-wrapper":"",style:{...N,transform:U?N.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ve,"--radix-popper-transform-origin":[L.transformOrigin?.x,L.transformOrigin?.y].join(" "),...L.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:w.jsx(eke,{scope:n,placedSide:P,onArrowChange:_,arrowX:re,arrowY:de,shouldHideArrow:fe,children:w.jsx(gn.div,{"data-side":P,"data-align":H,...y,ref:E,style:{...y.style,animation:U?void 0:"none"}})})})});Zae.displayName=ej;var Yae="PopperArrow",nke={top:"bottom",right:"left",bottom:"top",left:"right"},Xae=I.forwardRef(function(e,n){const{__scopePopper:r,...s}=e,i=tke(Yae,r),o=nke[i.placedSide];return w.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[o]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:w.jsx(YPe,{...s,ref:n,style:{...s.style,display:"block"}})})});Xae.displayName=Yae;function rke(t){return t!==null}var ske=t=>({name:"transformOrigin",options:t,fn(e){const{placement:n,rects:r,middlewareData:s}=e,o=s.arrow?.centerOffset!==0,a=o?0:t.arrowWidth,c=o?0:t.arrowHeight,[l,u]=Qae(n),d={start:"0%",center:"50%",end:"100%"}[u],f=(s.arrow?.x??0)+a/2,p=(s.arrow?.y??0)+c/2;let m="",y="";return l==="bottom"?(m=o?d:`${f}px`,y=`${-c}px`):l==="top"?(m=o?d:`${f}px`,y=`${r.floating.height+c}px`):l==="right"?(m=`${-c}px`,y=o?d:`${p}px`):l==="left"&&(m=`${r.floating.width+c}px`,y=o?d:`${p}px`),{data:{x:m,y}}}});function Qae(t){const[e,n="center"]=t.split("-");return[e,n]}var tj=qae,nj=Gae,rj=Zae,sj=Xae,[EP,nkt]=pp("Tooltip",[K1]),CP=K1(),Jae="TooltipProvider",ike=700,oL="tooltip.open",[oke,ij]=EP(Jae),ece=t=>{const{__scopeTooltip:e,delayDuration:n=ike,skipDelayDuration:r=300,disableHoverableContent:s=!1,children:i}=t,[o,a]=I.useState(!0),c=I.useRef(!1),l=I.useRef(0);return I.useEffect(()=>{const u=l.current;return()=>window.clearTimeout(u)},[]),w.jsx(oke,{scope:e,isOpenDelayed:o,delayDuration:n,onOpen:I.useCallback(()=>{window.clearTimeout(l.current),a(!1)},[]),onClose:I.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>a(!0),r)},[r]),isPointerInTransitRef:c,onPointerInTransitChange:I.useCallback(u=>{c.current=u},[]),disableHoverableContent:s,children:i})};ece.displayName=Jae;var _P="Tooltip",[ake,SP]=EP(_P),tce=t=>{const{__scopeTooltip:e,children:n,open:r,defaultOpen:s=!1,onOpenChange:i,disableHoverableContent:o,delayDuration:a}=t,c=ij(_P,t.__scopeTooltip),l=CP(e),[u,d]=I.useState(null),f=Wu(),p=I.useRef(0),m=o??c.disableHoverableContent,y=a??c.delayDuration,b=I.useRef(!1),[v=!1,x]=jh({prop:r,defaultProp:s,onChange:B=>{B?(c.onOpen(),document.dispatchEvent(new CustomEvent(oL))):c.onClose(),i?.(B)}}),E=I.useMemo(()=>v?b.current?"delayed-open":"instant-open":"closed",[v]),A=I.useCallback(()=>{window.clearTimeout(p.current),p.current=0,b.current=!1,x(!0)},[x]),_=I.useCallback(()=>{window.clearTimeout(p.current),p.current=0,x(!1)},[x]),k=I.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{b.current=!0,x(!0),p.current=0},y)},[y,x]);return I.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),w.jsx(tj,{...l,children:w.jsx(ake,{scope:e,contentId:f,open:v,stateAttribute:E,trigger:u,onTriggerChange:d,onTriggerEnter:I.useCallback(()=>{c.isOpenDelayed?k():A()},[c.isOpenDelayed,k,A]),onTriggerLeave:I.useCallback(()=>{m?_():(window.clearTimeout(p.current),p.current=0)},[_,m]),onOpen:A,onClose:_,disableHoverableContent:m,children:n})})};tce.displayName=_P;var aL="TooltipTrigger",nce=I.forwardRef((t,e)=>{const{__scopeTooltip:n,...r}=t,s=SP(aL,n),i=ij(aL,n),o=CP(n),a=I.useRef(null),c=ir(e,a,s.onTriggerChange),l=I.useRef(!1),u=I.useRef(!1),d=I.useCallback(()=>l.current=!1,[]);return I.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),w.jsx(nj,{asChild:!0,...o,children:w.jsx(gn.button,{"aria-describedby":s.open?s.contentId:void 0,"data-state":s.stateAttribute,...r,ref:c,onPointerMove:vt(t.onPointerMove,f=>{f.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(s.onTriggerEnter(),u.current=!0)}),onPointerLeave:vt(t.onPointerLeave,()=>{s.onTriggerLeave(),u.current=!1}),onPointerDown:vt(t.onPointerDown,()=>{l.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:vt(t.onFocus,()=>{l.current||s.onOpen()}),onBlur:vt(t.onBlur,s.onClose),onClick:vt(t.onClick,s.onClose)})})});nce.displayName=aL;var cke="TooltipPortal",[rkt,lke]=EP(cke,{forceMount:void 0}),kv="TooltipContent",rce=I.forwardRef((t,e)=>{const n=lke(kv,t.__scopeTooltip),{forceMount:r=n.forceMount,side:s="top",...i}=t,o=SP(kv,t.__scopeTooltip);return w.jsx(ud,{present:r||o.open,children:o.disableHoverableContent?w.jsx(sce,{side:s,...i,ref:e}):w.jsx(uke,{side:s,...i,ref:e})})}),uke=I.forwardRef((t,e)=>{const n=SP(kv,t.__scopeTooltip),r=ij(kv,t.__scopeTooltip),s=I.useRef(null),i=ir(e,s),[o,a]=I.useState(null),{trigger:c,onClose:l}=n,u=s.current,{onPointerInTransitChange:d}=r,f=I.useCallback(()=>{a(null),d(!1)},[d]),p=I.useCallback((m,y)=>{const b=m.currentTarget,v={x:m.clientX,y:m.clientY},x=pke(v,b.getBoundingClientRect()),E=gke(v,x),A=mke(y.getBoundingClientRect()),_=wke([...E,...A]);a(_),d(!0)},[d]);return I.useEffect(()=>()=>f(),[f]),I.useEffect(()=>{if(c&&u){const m=b=>p(b,u),y=b=>p(b,c);return c.addEventListener("pointerleave",m),u.addEventListener("pointerleave",y),()=>{c.removeEventListener("pointerleave",m),u.removeEventListener("pointerleave",y)}}},[c,u,p,f]),I.useEffect(()=>{if(o){const m=y=>{const b=y.target,v={x:y.clientX,y:y.clientY},x=c?.contains(b)||u?.contains(b),E=!yke(v,o);x?f():E&&(f(),l())};return document.addEventListener("pointermove",m),()=>document.removeEventListener("pointermove",m)}},[c,u,o,l,f]),w.jsx(sce,{...t,ref:i})}),[dke,fke]=EP(_P,{isInside:!1}),sce=I.forwardRef((t,e)=>{const{__scopeTooltip:n,children:r,"aria-label":s,onEscapeKeyDown:i,onPointerDownOutside:o,...a}=t,c=SP(kv,n),l=CP(n),{onClose:u}=c;return I.useEffect(()=>(document.addEventListener(oL,u),()=>document.removeEventListener(oL,u)),[u]),I.useEffect(()=>{if(c.trigger){const d=f=>{f.target?.contains(c.trigger)&&u()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[c.trigger,u]),w.jsx(z1,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:o,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:w.jsxs(rj,{"data-state":c.stateAttribute,...l,...a,ref:e,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[w.jsx(FF,{children:r}),w.jsx(dke,{scope:n,isInside:!0,children:w.jsx(YTe,{id:c.contentId,role:"tooltip",children:s||r})})]})})});rce.displayName=kv;var ice="TooltipArrow",hke=I.forwardRef((t,e)=>{const{__scopeTooltip:n,...r}=t,s=CP(n);return fke(ice,n).isInside?null:w.jsx(sj,{...s,...r,ref:e})});hke.displayName=ice;function pke(t,e){const n=Math.abs(e.top-t.y),r=Math.abs(e.bottom-t.y),s=Math.abs(e.right-t.x),i=Math.abs(e.left-t.x);switch(Math.min(n,r,s,i)){case i:return"left";case s:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function gke(t,e,n=5){const r=[];switch(e){case"top":r.push({x:t.x-n,y:t.y+n},{x:t.x+n,y:t.y+n});break;case"bottom":r.push({x:t.x-n,y:t.y-n},{x:t.x+n,y:t.y-n});break;case"left":r.push({x:t.x+n,y:t.y-n},{x:t.x+n,y:t.y+n});break;case"right":r.push({x:t.x-n,y:t.y-n},{x:t.x-n,y:t.y+n});break}return r}function mke(t){const{top:e,right:n,bottom:r,left:s}=t;return[{x:s,y:e},{x:n,y:e},{x:n,y:r},{x:s,y:r}]}function yke(t,e){const{x:n,y:r}=t;let s=!1;for(let i=0,o=e.length-1;ir!=u>r&&n<(l-a)*(r-c)/(u-c)+a&&(s=!s)}return s}function wke(t){const e=t.slice();return e.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),bke(e)}function bke(t){if(t.length<=1)return t.slice();const e=[];for(let r=0;r=2;){const i=e[e.length-1],o=e[e.length-2];if((i.x-o.x)*(s.y-o.y)>=(i.y-o.y)*(s.x-o.x))e.pop();else break}e.push(s)}e.pop();const n=[];for(let r=t.length-1;r>=0;r--){const s=t[r];for(;n.length>=2;){const i=n[n.length-1],o=n[n.length-2];if((i.x-o.x)*(s.y-o.y)>=(i.y-o.y)*(s.x-o.x))n.pop();else break}n.push(s)}return n.pop(),e.length===1&&n.length===1&&e[0].x===n[0].x&&e[0].y===n[0].y?e:e.concat(n)}var vke=ece,xke=tce,Eke=nce,oce=rce;const ace=vke,jm=xke,zm=Eke,Hg=I.forwardRef(({className:t,sideOffset:e=4,...n},r)=>w.jsx(oce,{ref:r,sideOffset:e,className:Dt("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...n}));Hg.displayName=oce.displayName;var AP=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},IP=typeof window>"u"||"Deno"in globalThis;function Tu(){}function Cke(t,e){return typeof t=="function"?t(e):t}function _ke(t){return typeof t=="number"&&t>=0&&t!==1/0}function Ske(t,e){return Math.max(t+(e||0)-Date.now(),0)}function cL(t,e){return typeof t=="function"?t(e):t}function Ake(t,e){return typeof t=="function"?t(e):t}function JZ(t,e){const{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=t;if(o){if(r){if(e.queryHash!==oj(o,e.options))return!1}else if(!hC(e.queryKey,o))return!1}if(n!=="all"){const c=e.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&e.isStale()!==a||s&&s!==e.state.fetchStatus||i&&!i(e))}function eY(t,e){const{exact:n,status:r,predicate:s,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(n){if(fC(e.options.mutationKey)!==fC(i))return!1}else if(!hC(e.options.mutationKey,i))return!1}return!(r&&e.state.status!==r||s&&!s(e))}function oj(t,e){return(e?.queryKeyHashFn||fC)(t)}function fC(t){return JSON.stringify(t,(e,n)=>lL(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function hC(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>hC(t[n],e[n])):!1}function cce(t,e){if(t===e)return t;const n=tY(t)&&tY(e);if(n||lL(t)&&lL(e)){const r=n?t:Object.keys(t),s=r.length,i=n?e:Object.keys(e),o=i.length,a=n?[]:{},c=new Set(r);let l=0;for(let u=0;u{setTimeout(e,t)})}function Tke(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?cce(t,e):e}function Nke(t,e,n=0){const r=[...t,e];return n&&r.length>n?r.slice(1):r}function Pke(t,e,n=0){const r=[e,...t];return n&&r.length>n?r.slice(0,-1):r}var aj=Symbol();function lce(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===aj?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}var kke=class extends AP{#e;#t;#n;constructor(){super(),this.#n=t=>{if(!IP&&window.addEventListener){const e=()=>t();return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#n=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},uce=new kke,Rke=class extends AP{#e=!0;#t;#n;constructor(){super(),this.#n=t=>{if(!IP&&window.addEventListener){const e=()=>t(!0),n=()=>t(!1);return window.addEventListener("online",e,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#n=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(n=>{n(t)}))}isOnline(){return this.#e}},J6=new Rke;function Oke(){let t,e;const n=new Promise((s,i)=>{t=s,e=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),t(s)},n.reject=s=>{r({status:"rejected",reason:s}),e(s)},n}function $ke(t){return Math.min(1e3*2**t,3e4)}function dce(t){return(t??"online")==="online"?J6.isOnline():!0}var fce=class extends Error{constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function VO(t){return t instanceof fce}function hce(t){let e=!1,n=0,r=!1,s;const i=Oke(),o=y=>{r||(f(new fce(y)),t.abort?.())},a=()=>{e=!0},c=()=>{e=!1},l=()=>uce.isFocused()&&(t.networkMode==="always"||J6.isOnline())&&t.canRun(),u=()=>dce(t.networkMode)&&t.canRun(),d=y=>{r||(r=!0,t.onSuccess?.(y),s?.(),i.resolve(y))},f=y=>{r||(r=!0,t.onError?.(y),s?.(),i.reject(y))},p=()=>new Promise(y=>{s=b=>{(r||l())&&y(b)},t.onPause?.()}).then(()=>{s=void 0,r||t.onContinue?.()}),m=()=>{if(r)return;let y;const b=n===0?t.initialPromise:void 0;try{y=b??t.fn()}catch(v){y=Promise.reject(v)}Promise.resolve(y).then(d).catch(v=>{if(r)return;const x=t.retry??(IP?0:3),E=t.retryDelay??$ke,A=typeof E=="function"?E(n,v):E,_=x===!0||typeof x=="number"&&nl()?void 0:p()).then(()=>{e?f(v):m()})})};return{promise:i,cancel:o,continue:()=>(s?.(),i),cancelRetry:a,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var Dke=t=>setTimeout(t,0);function Mke(){let t=[],e=0,n=a=>{a()},r=a=>{a()},s=Dke;const i=a=>{e?t.push(a):s(()=>{n(a)})},o=()=>{const a=t;t=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;e++;try{c=a()}finally{e--,e||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var Go=Mke(),pce=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),_ke(this.gcTime)&&(this.#e=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(IP?1/0:5*60*1e3))}clearGcTimeout(){this.#e&&(clearTimeout(this.#e),this.#e=void 0)}},Lke=class extends pce{#e;#t;#n;#s;#i;#a;#o;constructor(t){super(),this.#o=!1,this.#a=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#s=t.client,this.#n=this.#s.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#e=Uke(this.options),this.state=t.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#i?.promise}setOptions(t){this.options={...this.#a,...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(t,e){const n=Tke(this.state.data,t,this.options);return this.#r({data:n,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),n}setState(t,e){this.#r({type:"setState",state:t,setStateOptions:e})}cancel(t){const e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(Tu).catch(Tu):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(t=>Ake(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===aj||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>cL(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Ske(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#i&&(this.#o?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#r({type:"invalidate"})}fetch(t,e){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){const c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,r=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},s=()=>{const c=lce(this.options,e),u=(()=>{const d={client:this.#s,queryKey:this.queryKey,meta:this.meta};return r(d),d})();return this.#o=!1,this.options.persister?this.options.persister(c,u,this):c(u)},o=(()=>{const c={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#s,state:this.state,fetchFn:s};return r(c),c})();this.options.behavior?.onFetch(o,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#r({type:"fetch",meta:o.fetchOptions?.meta});const a=c=>{VO(c)&&c.silent||this.#r({type:"error",error:c}),VO(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#i=hce({initialPromise:e?.initialPromise,fn:o.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,l)=>{this.#r({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#r({type:"pause"})},onContinue:()=>{this.#r({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}),this.#i.start()}#r(t){const e=n=>{switch(t.type){case"failed":return{...n,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Bke(n.data,this.options),fetchMeta:t.meta??null};case"success":return this.#t=void 0,{...n,data:t.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const r=t.error;return VO(r)&&r.revert&&this.#t?{...this.#t,fetchStatus:"idle"}:{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}};this.state=e(this.state),Go.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:t})})}};function Bke(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:dce(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Uke(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,r=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Fke=class extends AP{constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,n){const r=e.queryKey,s=e.queryHash??oj(r,e);let i=this.get(s);return i||(i=new Lke({client:t,queryKey:r,queryHash:s,options:t.defaultQueryOptions(e),state:n,defaultOptions:t.getQueryDefaults(r)}),this.add(i)),i}add(t){this.#e.has(t.queryHash)||(this.#e.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const e=this.#e.get(t.queryHash);e&&(t.destroy(),e===t&&this.#e.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Go.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#e.get(t)}getAll(){return[...this.#e.values()]}find(t){const e={exact:!0,...t};return this.getAll().find(n=>JZ(e,n))}findAll(t={}){const e=this.getAll();return Object.keys(t).length>0?e.filter(n=>JZ(t,n)):e}notify(t){Go.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){Go.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Go.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},jke=class extends pce{#e;#t;#n;constructor(t){super(),this.mutationId=t.mutationId,this.#t=t.mutationCache,this.#e=[],this.state=t.state||zke(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#e.includes(t)||(this.#e.push(t),this.clearGcTimeout(),this.#t.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#e=this.#e.filter(e=>e!==t),this.scheduleGc(),this.#t.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#t.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(t){const e=()=>{this.#s({type:"continue"})};this.#n=hce({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(s,i)=>{this.#s({type:"failed",failureCount:s,error:i})},onPause:()=>{this.#s({type:"pause"})},onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#t.canRun(this)});const n=this.state.status==="pending",r=!this.#n.canStart();try{if(n)e();else{this.#s({type:"pending",variables:t,isPaused:r}),await this.#t.config.onMutate?.(t,this);const i=await this.options.onMutate?.(t);i!==this.state.context&&this.#s({type:"pending",context:i,variables:t,isPaused:r})}const s=await this.#n.start();return await this.#t.config.onSuccess?.(s,t,this.state.context,this),await this.options.onSuccess?.(s,t,this.state.context),await this.#t.config.onSettled?.(s,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(s,null,t,this.state.context),this.#s({type:"success",data:s}),s}catch(s){try{throw await this.#t.config.onError?.(s,t,this.state.context,this),await this.options.onError?.(s,t,this.state.context),await this.#t.config.onSettled?.(void 0,s,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,s,t,this.state.context),s}finally{this.#s({type:"error",error:s})}}finally{this.#t.runNext(this)}}#s(t){const e=n=>{switch(t.type){case"failed":return{...n,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...n,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:t.error,failureCount:n.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=e(this.state),Go.batch(()=>{this.#e.forEach(n=>{n.onMutationUpdate(t)}),this.#t.notify({mutation:this,type:"updated",action:t})})}};function zke(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Wke=class extends AP{constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(t,e,n){const r=new jke({mutationCache:this,mutationId:++this.#n,options:t.defaultMutationOptions(e),state:n});return this.add(r),r}add(t){this.#e.add(t);const e=iA(t);if(typeof e=="string"){const n=this.#t.get(e);n?n.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){const e=iA(t);if(typeof e=="string"){const n=this.#t.get(e);if(n)if(n.length>1){const r=n.indexOf(t);r!==-1&&n.splice(r,1)}else n[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){const e=iA(t);if(typeof e=="string"){const r=this.#t.get(e)?.find(s=>s.state.status==="pending");return!r||r===t}else return!0}runNext(t){const e=iA(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Go.batch(()=>{this.#e.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(t){const e={exact:!0,...t};return this.getAll().find(n=>eY(e,n))}findAll(t={}){return this.getAll().filter(e=>eY(t,e))}notify(t){Go.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){const t=this.getAll().filter(e=>e.state.isPaused);return Go.batch(()=>Promise.all(t.map(e=>e.continue().catch(Tu))))}};function iA(t){return t.options.scope?.id}function rY(t){return{onFetch:(e,n)=>{const r=e.options,s=e.fetchOptions?.meta?.fetchMore?.direction,i=e.state.data?.pages||[],o=e.state.data?.pageParams||[];let a={pages:[],pageParams:[]},c=0;const l=async()=>{let u=!1;const d=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>(e.signal.aborted?u=!0:e.signal.addEventListener("abort",()=>{u=!0}),e.signal)})},f=lce(e.options,e.fetchOptions),p=async(m,y,b)=>{if(u)return Promise.reject();if(y==null&&m.pages.length)return Promise.resolve(m);const x=(()=>{const k={client:e.client,queryKey:e.queryKey,pageParam:y,direction:b?"backward":"forward",meta:e.options.meta};return d(k),k})(),E=await f(x),{maxPages:A}=e.options,_=b?Pke:Nke;return{pages:_(m.pages,E,A),pageParams:_(m.pageParams,y,A)}};if(s&&i.length){const m=s==="backward",y=m?Vke:sY,b={pages:i,pageParams:o},v=y(r,b);a=await p(b,v,m)}else{const m=t??i.length;do{const y=c===0?o[0]??r.initialPageParam:sY(r,a);if(c>0&&y==null)break;a=await p(a,y),c++}while(ce.options.persister?.(l,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n):e.fetchFn=l}}}function sY(t,{pages:e,pageParams:n}){const r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,n[r],n):void 0}function Vke(t,{pages:e,pageParams:n}){return e.length>0?t.getPreviousPageParam?.(e[0],e,n[0],n):void 0}var Hke=class{#e;#t;#n;#s;#i;#a;#o;#r;constructor(t={}){this.#e=t.queryCache||new Fke,this.#t=t.mutationCache||new Wke,this.#n=t.defaultOptions||{},this.#s=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=uce.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#r=J6.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#r?.(),this.#r=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){const e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),n=this.#e.build(this,e),r=n.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(cL(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:n})=>{const r=n.data;return[e,r]})}setQueryData(t,e,n){const r=this.defaultQueryOptions({queryKey:t}),i=this.#e.get(r.queryHash)?.state.data,o=Cke(e,i);if(o!==void 0)return this.#e.build(this,r).setData(o,{...n,manual:!0})}setQueriesData(t,e,n){return Go.batch(()=>this.#e.findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,n)]))}getQueryState(t){const e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){const e=this.#e;Go.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){const n=this.#e;return Go.batch(()=>(n.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const n={revert:!0,...e},r=Go.batch(()=>this.#e.findAll(t).map(s=>s.cancel(n)));return Promise.all(r).then(Tu).catch(Tu)}invalidateQueries(t,e={}){return Go.batch(()=>(this.#e.findAll(t).forEach(n=>{n.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){const n={...e,cancelRefetch:e.cancelRefetch??!0},r=Go.batch(()=>this.#e.findAll(t).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Tu)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Tu)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=this.#e.build(this,e);return n.isStaleByTime(cL(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(Tu).catch(Tu)}fetchInfiniteQuery(t){return t.behavior=rY(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(Tu).catch(Tu)}ensureInfiniteQueryData(t){return t.behavior=rY(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return J6.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(t){this.#n=t}setQueryDefaults(t,e){this.#s.set(fC(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...this.#s.values()],n={};return e.forEach(r=>{hC(t,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(t,e){this.#i.set(fC(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...this.#i.values()],n={};return e.forEach(r=>{hC(t,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;const e={...this.#n.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=oj(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===aj&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#n.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},qke=I.createContext(void 0),Kke=({client:t,children:e})=>(I.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),w.jsx(qke.Provider,{value:t,children:e}));/** + * @remix-run/router v1.20.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function pC(){return pC=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function gce(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function Zke(){return Math.random().toString(36).substr(2,8)}function oY(t,e){return{usr:t.state,key:t.key,idx:e}}function uL(t,e,n,r){return n===void 0&&(n=null),pC({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?G1(e):e,{state:n,key:e&&e.key||r||Zke()})}function eT(t){let{pathname:e="/",search:n="",hash:r=""}=t;return n&&n!=="?"&&(e+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(e+=r.charAt(0)==="#"?r:"#"+r),e}function G1(t){let e={};if(t){let n=t.indexOf("#");n>=0&&(e.hash=t.substr(n),t=t.substr(0,n));let r=t.indexOf("?");r>=0&&(e.search=t.substr(r),t=t.substr(0,r)),t&&(e.pathname=t)}return e}function Yke(t,e,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:i=!1}=r,o=s.history,a=Tg.Pop,c=null,l=u();l==null&&(l=0,o.replaceState(pC({},o.state,{idx:l}),""));function u(){return(o.state||{idx:null}).idx}function d(){a=Tg.Pop;let b=u(),v=b==null?null:b-l;l=b,c&&c({action:a,location:y.location,delta:v})}function f(b,v){a=Tg.Push;let x=uL(y.location,b,v);l=u()+1;let E=oY(x,l),A=y.createHref(x);try{o.pushState(E,"",A)}catch(_){if(_ instanceof DOMException&&_.name==="DataCloneError")throw _;s.location.assign(A)}i&&c&&c({action:a,location:y.location,delta:1})}function p(b,v){a=Tg.Replace;let x=uL(y.location,b,v);l=u();let E=oY(x,l),A=y.createHref(x);o.replaceState(E,"",A),i&&c&&c({action:a,location:y.location,delta:0})}function m(b){let v=s.location.origin!=="null"?s.location.origin:s.location.href,x=typeof b=="string"?b:eT(b);return x=x.replace(/ $/,"%20"),Ks(v,"No window.location.(origin|href) available to create URL for href: "+x),new URL(x,v)}let y={get action(){return a},get location(){return t(s,o)},listen(b){if(c)throw new Error("A history only accepts one active listener");return s.addEventListener(iY,d),c=b,()=>{s.removeEventListener(iY,d),c=null}},createHref(b){return e(s,b)},createURL:m,encodeLocation(b){let v=m(b);return{pathname:v.pathname,search:v.search,hash:v.hash}},push:f,replace:p,go(b){return o.go(b)}};return y}var aY;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(aY||(aY={}));function Xke(t,e,n){return n===void 0&&(n="/"),Qke(t,e,n,!1)}function Qke(t,e,n,r){let s=typeof e=="string"?G1(e):e,i=cj(s.pathname||"/",n);if(i==null)return null;let o=mce(t);Jke(o);let a=null;for(let c=0;a==null&&c{let c={relativePath:a===void 0?i.path||"":a,caseSensitive:i.caseSensitive===!0,childrenIndex:o,route:i};c.relativePath.startsWith("/")&&(Ks(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let l=qg([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(Ks(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+l+'".')),mce(i.children,e,u,l)),!(i.path==null&&!i.index)&&e.push({path:l,score:o8e(l,i.index),routesMeta:u})};return t.forEach((i,o)=>{var a;if(i.path===""||!((a=i.path)!=null&&a.includes("?")))s(i,o);else for(let c of yce(i.path))s(i,o,c)}),e}function yce(t){let e=t.split("/");if(e.length===0)return[];let[n,...r]=e,s=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return s?[i,""]:[i];let o=yce(r.join("/")),a=[];return a.push(...o.map(c=>c===""?i:[i,c].join("/"))),s&&a.push(...o),a.map(c=>t.startsWith("/")&&c===""?"/":c)}function Jke(t){t.sort((e,n)=>e.score!==n.score?n.score-e.score:a8e(e.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const e8e=/^:[\w-]+$/,t8e=3,n8e=2,r8e=1,s8e=10,i8e=-2,cY=t=>t==="*";function o8e(t,e){let n=t.split("/"),r=n.length;return n.some(cY)&&(r+=i8e),e&&(r+=n8e),n.filter(s=>!cY(s)).reduce((s,i)=>s+(e8e.test(i)?t8e:i===""?r8e:s8e),r)}function a8e(t,e){return t.length===e.length&&t.slice(0,-1).every((r,s)=>r===e[s])?t[t.length-1]-e[e.length-1]:0}function c8e(t,e,n){let{routesMeta:r}=t,s={},i="/",o=[];for(let a=0;a{let{paramName:f,isOptional:p}=u;if(f==="*"){let y=a[d]||"";o=i.slice(0,i.length-y.length).replace(/(.)\/+$/,"$1")}const m=a[d];return p&&!m?l[f]=void 0:l[f]=(m||"").replace(/%2F/g,"/"),l},{}),pathname:i,pathnameBase:o,pattern:t}}function l8e(t,e,n){e===void 0&&(e=!1),n===void 0&&(n=!0),gce(t==="*"||!t.endsWith("*")||t.endsWith("/*"),'Route path "'+t+'" will be treated as if it were '+('"'+t.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+t.replace(/\*$/,"/*")+'".'));let r=[],s="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,a,c)=>(r.push({paramName:a,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return t.endsWith("*")?(r.push({paramName:"*"}),s+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":t!==""&&t!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,e?void 0:"i"),r]}function u8e(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return gce(!1,'The URL path "'+t+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),t}}function cj(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let n=e.endsWith("/")?e.length-1:e.length,r=t.charAt(n);return r&&r!=="/"?null:t.slice(n)||"/"}function d8e(t,e){e===void 0&&(e="/");let{pathname:n,search:r="",hash:s=""}=typeof t=="string"?G1(t):t;return{pathname:n?n.startsWith("/")?n:f8e(n,e):e,search:g8e(r),hash:m8e(s)}}function f8e(t,e){let n=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function HO(t,e,n,r){return"Cannot include a '"+t+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function h8e(t){return t.filter((e,n)=>n===0||e.route.path&&e.route.path.length>0)}function wce(t,e){let n=h8e(t);return e?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function bce(t,e,n,r){r===void 0&&(r=!1);let s;typeof t=="string"?s=G1(t):(s=pC({},t),Ks(!s.pathname||!s.pathname.includes("?"),HO("?","pathname","search",s)),Ks(!s.pathname||!s.pathname.includes("#"),HO("#","pathname","hash",s)),Ks(!s.search||!s.search.includes("#"),HO("#","search","hash",s)));let i=t===""||s.pathname==="",o=i?"/":s.pathname,a;if(o==null)a=n;else{let d=e.length-1;if(!r&&o.startsWith("..")){let f=o.split("/");for(;f[0]==="..";)f.shift(),d-=1;s.pathname=f.join("/")}a=d>=0?e[d]:"/"}let c=d8e(s,a),l=o&&o!=="/"&&o.endsWith("/"),u=(i||o===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(l||u)&&(c.pathname+="/"),c}const qg=t=>t.join("/").replace(/\/\/+/g,"/"),p8e=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),g8e=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,m8e=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function y8e(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const vce=["post","put","patch","delete"];new Set(vce);const w8e=["get",...vce];new Set(w8e);/** + * React Router v6.27.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function gC(){return gC=Object.assign?Object.assign.bind():function(t){for(var e=1;e{a.current=!0}),I.useCallback(function(l,u){if(u===void 0&&(u={}),!a.current)return;if(typeof l=="number"){r.go(l);return}let d=bce(l,JSON.parse(o),i,u.relative==="path");t==null&&e!=="/"&&(d.pathname=d.pathname==="/"?e:qg([e,d.pathname])),(u.replace?r.replace:r.push)(d,u.state,u)},[e,r,o,i,t])}function Cce(){let{matches:t}=I.useContext(P0),e=t[t.length-1];return e?e.params:{}}function _ce(t,e){let{relative:n}=e===void 0?{}:e,{future:r}=I.useContext(Jy),{matches:s}=I.useContext(P0),{pathname:i}=Z1(),o=JSON.stringify(wce(s,r.v7_relativeSplatPath));return I.useMemo(()=>bce(t,JSON.parse(o),i,n==="path"),[t,o,i,n])}function E8e(t,e){return C8e(t,e)}function C8e(t,e,n,r){MS()||Ks(!1);let{navigator:s}=I.useContext(Jy),{matches:i}=I.useContext(P0),o=i[i.length-1],a=o?o.params:{};o&&o.pathname;let c=o?o.pathnameBase:"/";o&&o.route;let l=Z1(),u;if(e){var d;let b=typeof e=="string"?G1(e):e;c==="/"||(d=b.pathname)!=null&&d.startsWith(c)||Ks(!1),u=b}else u=l;let f=u.pathname||"/",p=f;if(c!=="/"){let b=c.replace(/^\//,"").split("/");p="/"+f.replace(/^\//,"").split("/").slice(b.length).join("/")}let m=Xke(t,{pathname:p}),y=T8e(m&&m.map(b=>Object.assign({},b,{params:Object.assign({},a,b.params),pathname:qg([c,s.encodeLocation?s.encodeLocation(b.pathname).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?c:qg([c,s.encodeLocation?s.encodeLocation(b.pathnameBase).pathname:b.pathnameBase])})),i,n,r);return e&&y?I.createElement(TP.Provider,{value:{location:gC({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:Tg.Pop}},y):y}function _8e(){let t=R8e(),e=y8e(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return I.createElement(I.Fragment,null,I.createElement("h2",null,"Unexpected Application Error!"),I.createElement("h3",{style:{fontStyle:"italic"}},e),n?I.createElement("pre",{style:s},n):null,null)}const S8e=I.createElement(_8e,null);class A8e extends I.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,n){return n.location!==e.location||n.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:n.error,location:n.location,revalidation:e.revalidation||n.revalidation}}componentDidCatch(e,n){console.error("React Router caught the following error during render",e,n)}render(){return this.state.error!==void 0?I.createElement(P0.Provider,{value:this.props.routeContext},I.createElement(xce.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function I8e(t){let{routeContext:e,match:n,children:r}=t,s=I.useContext(lj);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),I.createElement(P0.Provider,{value:e},r)}function T8e(t,e,n,r){var s;if(e===void 0&&(e=[]),n===void 0&&(n=null),r===void 0&&(r=null),t==null){var i;if(!n)return null;if(n.errors)t=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&e.length===0&&!n.initialized&&n.matches.length>0)t=n.matches;else return null}let o=t,a=(s=n)==null?void 0:s.errors;if(a!=null){let u=o.findIndex(d=>d.route.id&&a?.[d.route.id]!==void 0);u>=0||Ks(!1),o=o.slice(0,Math.min(o.length,u+1))}let c=!1,l=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?o=o.slice(0,l+1):o=[o[0]];break}}}return o.reduceRight((u,d,f)=>{let p,m=!1,y=null,b=null;n&&(p=a&&d.route.id?a[d.route.id]:void 0,y=d.route.errorElement||S8e,c&&(l<0&&f===0?(m=!0,b=null):l===f&&(m=!0,b=d.route.hydrateFallbackElement||null)));let v=e.concat(o.slice(0,f+1)),x=()=>{let E;return p?E=y:m?E=b:d.route.Component?E=I.createElement(d.route.Component,null):d.route.element?E=d.route.element:E=u,I.createElement(I8e,{match:d,routeContext:{outlet:u,matches:v,isDataRoute:n!=null},children:E})};return n&&(d.route.ErrorBoundary||d.route.errorElement||f===0)?I.createElement(A8e,{location:n.location,revalidation:n.revalidation,component:y,error:p,children:x(),routeContext:{outlet:null,matches:v,isDataRoute:!0}}):x()},null)}var Sce=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(Sce||{}),tT=function(t){return t.UseBlocker="useBlocker",t.UseLoaderData="useLoaderData",t.UseActionData="useActionData",t.UseRouteError="useRouteError",t.UseNavigation="useNavigation",t.UseRouteLoaderData="useRouteLoaderData",t.UseMatches="useMatches",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t.UseRouteId="useRouteId",t}(tT||{});function N8e(t){let e=I.useContext(lj);return e||Ks(!1),e}function P8e(t){let e=I.useContext(b8e);return e||Ks(!1),e}function k8e(t){let e=I.useContext(P0);return e||Ks(!1),e}function Ace(t){let e=k8e(),n=e.matches[e.matches.length-1];return n.route.id||Ks(!1),n.route.id}function R8e(){var t;let e=I.useContext(xce),n=P8e(tT.UseRouteError),r=Ace(tT.UseRouteError);return e!==void 0?e:(t=n.errors)==null?void 0:t[r]}function O8e(){let{router:t}=N8e(Sce.UseNavigateStable),e=Ace(tT.UseNavigateStable),n=I.useRef(!1);return Ece(()=>{n.current=!0}),I.useCallback(function(s,i){i===void 0&&(i={}),n.current&&(typeof s=="number"?t.navigate(s):t.navigate(s,gC({fromRouteId:e},i)))},[t,e])}function ag(t){Ks(!1)}function $8e(t){let{basename:e="/",children:n=null,location:r,navigationType:s=Tg.Pop,navigator:i,static:o=!1,future:a}=t;MS()&&Ks(!1);let c=e.replace(/^\/*/,"/"),l=I.useMemo(()=>({basename:c,navigator:i,static:o,future:gC({v7_relativeSplatPath:!1},a)}),[c,a,i,o]);typeof r=="string"&&(r=G1(r));let{pathname:u="/",search:d="",hash:f="",state:p=null,key:m="default"}=r,y=I.useMemo(()=>{let b=cj(u,c);return b==null?null:{location:{pathname:b,search:d,hash:f,state:p,key:m},navigationType:s}},[c,u,d,f,p,m,s]);return y==null?null:I.createElement(Jy.Provider,{value:l},I.createElement(TP.Provider,{children:n,value:y}))}function D8e(t){let{children:e,location:n}=t;return E8e(dL(e),n)}new Promise(()=>{});function dL(t,e){e===void 0&&(e=[]);let n=[];return I.Children.forEach(t,(r,s)=>{if(!I.isValidElement(r))return;let i=[...e,s];if(r.type===I.Fragment){n.push.apply(n,dL(r.props.children,i));return}r.type!==ag&&Ks(!1),!r.props.index||!r.props.children||Ks(!1);let o={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(o.children=dL(r.props.children,i)),n.push(o)}),n}/** + * React Router DOM v6.27.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function fL(){return fL=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&(n[s]=t[s]);return n}function L8e(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function B8e(t,e){return t.button===0&&(!e||e==="_self")&&!L8e(t)}const U8e=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],F8e="6";try{window.__reactRouterVersion=F8e}catch{}const j8e="startTransition",uY=Fse[j8e];function z8e(t){let{basename:e,children:n,future:r,window:s}=t,i=I.useRef();i.current==null&&(i.current=Gke({window:s,v5Compat:!0}));let o=i.current,[a,c]=I.useState({action:o.action,location:o.location}),{v7_startTransition:l}=r||{},u=I.useCallback(d=>{l&&uY?uY(()=>c(d)):c(d)},[c,l]);return I.useLayoutEffect(()=>o.listen(u),[o,u]),I.createElement($8e,{basename:e,children:n,location:a.location,navigationType:a.action,navigator:o,future:r})}const W8e=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",V8e=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,ks=I.forwardRef(function(e,n){let{onClick:r,relative:s,reloadDocument:i,replace:o,state:a,target:c,to:l,preventScrollReset:u,viewTransition:d}=e,f=M8e(e,U8e),{basename:p}=I.useContext(Jy),m,y=!1;if(typeof l=="string"&&V8e.test(l)&&(m=l,W8e))try{let E=new URL(window.location.href),A=l.startsWith("//")?new URL(E.protocol+l):new URL(l),_=cj(A.pathname,p);A.origin===E.origin&&_!=null?l=_+A.search+A.hash:y=!0}catch{}let b=v8e(l,{relative:s}),v=H8e(l,{replace:o,state:a,target:c,preventScrollReset:u,relative:s,viewTransition:d});function x(E){r&&r(E),E.defaultPrevented||v(E)}return I.createElement("a",fL({},f,{href:m||b,onClick:y||i?r:x,ref:n,target:c}))});var dY;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(dY||(dY={}));var fY;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(fY||(fY={}));function H8e(t,e){let{target:n,replace:r,state:s,preventScrollReset:i,relative:o,viewTransition:a}=e===void 0?{}:e,c=NP(),l=Z1(),u=_ce(t,{relative:o});return I.useCallback(d=>{if(B8e(d,n)){d.preventDefault();let f=r!==void 0?r:eT(l)===eT(u);c(t,{replace:f,state:s,preventScrollReset:i,relative:o,viewTransition:a})}},[l,c,u,r,s,n,t,i,o,a])}var Ct=(t=>(t.WALLET_UNCONNECTED="wallet-unconnected",t.WALLET_CONNECTED="wallet-connected",t.ENS_ORDINAL_VERIFIED="ens-ordinal-verified",t))(Ct||{}),_l=(t=>(t.CALL_SIGN="call-sign",t.WALLET_ADDRESS="wallet-address",t))(_l||{});const q8e="modulepreload",K8e=function(t){return"/"+t},hY={},et=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");s=Promise.allSettled(n.map(c=>{if(c=K8e(c),c in hY)return;hY[c]=!0;const l=c.endsWith(".css"),u=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const d=document.createElement("link");if(d.rel=l?"stylesheet":q8e,l||(d.as="script"),d.crossOrigin="",d.href=c,a&&d.setAttribute("nonce",a),document.head.appendChild(d),l)return new Promise((f,p)=>{d.addEventListener("load",f),d.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return e().catch(i)})},nT=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"}],hL=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],Ice=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],skt=[...Ice,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],G8e=[...Ice,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],ikt=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],okt=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],Tce=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],pY=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],akt=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}];function cf(t,{includeName:e=!1}={}){if(t.type!=="function"&&t.type!=="event"&&t.type!=="error")throw new oRe(t.type);return`${t.name}(${PP(t.inputs,{includeName:e})})`}function PP(t,{includeName:e=!1}={}){return t?t.map(n=>Z8e(n,{includeName:e})).join(e?", ":","):""}function Z8e(t,{includeName:e}){return t.type.startsWith("tuple")?`(${PP(t.components,{includeName:e})})${t.type.slice(5)}`:t.type+(e&&t.name?` ${t.name}`:"")}function Hh(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Hs(t){return Hh(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Nce="2.37.1";let qO={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:n})=>e?`${t??"https://viem.sh"}${e}${n?`#${n}`:""}`:void 0,version:`viem@${Nce}`},ot=class pL extends Error{constructor(e,n={}){const r=n.cause instanceof pL?n.cause.details:n.cause?.message?n.cause.message:n.details,s=n.cause instanceof pL&&n.cause.docsPath||n.docsPath,i=qO.getDocsUrl?.({...n,docsPath:s}),o=[e||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...r?[`Details: ${r}`]:[],...qO.version?[`Version: ${qO.version}`]:[]].join(` +`);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=s,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=e,this.version=Nce}walk(e){return Pce(this,e)}};function Pce(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Pce(t.cause,e):e?null:t}class Y8e extends ot{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(` +`),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class gY extends ot{constructor({docsPath:e}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(` +`),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class kce extends ot{constructor({data:e,params:n,size:r}){super([`Data size of ${r} bytes is too small for given parameters.`].join(` +`),{metaMessages:[`Params: (${PP(n,{includeName:!0})})`,`Data: ${e} (${r} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=n,this.size=r}}class kP extends ot{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class X8e extends ot{constructor({expectedLength:e,givenLength:n,type:r}){super([`ABI encoding array length mismatch for type ${r}.`,`Expected length: ${e}`,`Given length: ${n}`].join(` +`),{name:"AbiEncodingArrayLengthMismatchError"})}}class Q8e extends ot{constructor({expectedSize:e,value:n}){super(`Size of bytes "${n}" (bytes${Hs(n)}) does not match expected size (bytes${e}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class J8e extends ot{constructor({expectedLength:e,givenLength:n}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${e}`,`Given length (values): ${n}`].join(` +`),{name:"AbiEncodingLengthMismatchError"})}}class eRe extends ot{constructor(e,{docsPath:n}){super([`Arguments (\`args\`) were provided to "${e}", but "${e}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(` +`),{docsPath:n,name:"AbiErrorInputsNotFoundError"})}}class mY extends ot{constructor(e,{docsPath:n}={}){super([`Error ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(` +`),{docsPath:n,name:"AbiErrorNotFoundError"})}}class Rce extends ot{constructor(e,{docsPath:n}){super([`Encoded error signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${e}.`].join(` +`),{docsPath:n,name:"AbiErrorSignatureNotFoundError"}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=e}}class tRe extends ot{constructor({docsPath:e}){super("Cannot extract event signature from empty topics.",{docsPath:e,name:"AbiEventSignatureEmptyTopicsError"})}}class Oce extends ot{constructor(e,{docsPath:n}){super([`Encoded event signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(` +`),{docsPath:n,name:"AbiEventSignatureNotFoundError"})}}class ckt extends ot{constructor(e,{docsPath:n}={}){super([`Event ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(` +`),{docsPath:n,name:"AbiEventNotFoundError"})}}class Rv extends ot{constructor(e,{docsPath:n}={}){super([`Function ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(` +`),{docsPath:n,name:"AbiFunctionNotFoundError"})}}class $ce extends ot{constructor(e,{docsPath:n}){super([`Function "${e}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(` +`),{docsPath:n,name:"AbiFunctionOutputsNotFoundError"})}}class nRe extends ot{constructor(e,{docsPath:n}){super([`Encoded function signature "${e}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://openchain.xyz/signatures?query=${e}.`].join(` +`),{docsPath:n,name:"AbiFunctionSignatureNotFoundError"})}}class rRe extends ot{constructor(e,n){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${e.type}\` in \`${cf(e.abiItem)}\`, and`,`\`${n.type}\` in \`${cf(n.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}let lkt=class extends ot{constructor({expectedSize:e,givenSize:n}){super(`Expected bytes${e}, got bytes${n}.`,{name:"BytesSizeMismatchError"})}};class gL extends ot{constructor({abiItem:e,data:n,params:r,size:s}){super([`Data size of ${s} bytes is too small for non-indexed event parameters.`].join(` +`),{metaMessages:[`Params: (${PP(r,{includeName:!0})})`,`Data: ${n} (${s} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e,this.data=n,this.params=r,this.size=s}}class Dce extends ot{constructor({abiItem:e,param:n}){super([`Expected a topic for indexed event parameter${n.name?` "${n.name}"`:""} on event "${cf(e,{includeName:!0})}".`].join(` +`),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=e}}class sRe extends ot{constructor(e,{docsPath:n}){super([`Type "${e}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(` +`),{docsPath:n,name:"InvalidAbiEncodingType"})}}class iRe extends ot{constructor(e,{docsPath:n}){super([`Type "${e}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(` +`),{docsPath:n,name:"InvalidAbiDecodingType"})}}let Mce=class extends ot{constructor(e){super([`Value "${e}" is not a valid array.`].join(` +`),{name:"InvalidArrayError"})}};class oRe extends ot{constructor(e){super([`"${e}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(` +`),{name:"InvalidDefinitionTypeError"})}}class fkt extends ot{constructor(e){super(`Type "${e}" is not supported for packed encoding.`,{name:"UnsupportedPackedAbiType"})}}let iy=class extends ot{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},Lce=class extends ot{constructor({offset:e,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${r}).`,{name:"SliceOffsetOutOfBoundsError"})}},Bce=class extends ot{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${n}).`,{name:"SizeExceedsPaddingSizeError"})}};class yY extends ot{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} is expected to be ${n} ${r} long, but is ${e} ${r} long.`,{name:"InvalidBytesLengthError"})}}function Y1(t,{dir:e,size:n=32}={}){return typeof t=="string"?Kg(t,{dir:e,size:n}):aRe(t,{dir:e,size:n})}function Kg(t,{dir:e,size:n=32}={}){if(n===null)return t;const r=t.replace("0x","");if(r.length>n*2)throw new Bce({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](n*2,"0")}`}function aRe(t,{dir:e,size:n=32}={}){if(n===null)return t;if(t.length>n)throw new Bce({size:t.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let s=0;se)throw new uRe({givenSize:Hs(t),maxSize:e})}function l0(t,e={}){const{signed:n}=e;e.size&&Yl(t,{size:e.size});const r=BigInt(t);if(!n)return r;const s=(t.length-2)/2,i=(1n<e.toString(16).padStart(2,"0"));function Ov(t,e={}){return typeof t=="number"||typeof t=="bigint"?$n(t,e):typeof t=="string"?$v(t,e):typeof t=="boolean"?jce(t,e):Po(t,e)}function jce(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(Yl(n,{size:e.size}),Y1(n,{size:e.size})):n}function Po(t,e={}){let n="";for(let s=0;si||s=zf.zero&&t<=zf.nine)return t-zf.zero;if(t>=zf.A&&t<=zf.F)return t-(zf.A-10);if(t>=zf.a&&t<=zf.f)return t-(zf.a-10)}function nd(t,e={}){let n=t;e.size&&(Yl(n,{size:e.size}),n=Y1(n,{dir:"right",size:e.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const s=r.length/2,i=new Uint8Array(s);for(let o=0,a=0;o>bY&oA)}:{h:Number(t>>bY&oA)|0,l:Number(t&oA)|0}}function Wce(t,e=!1){const n=t.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let i=0;it>>>n,xY=(t,e,n)=>t<<32-n|e>>>n,jw=(t,e,n)=>t>>>n|e<<32-n,zw=(t,e,n)=>t<<32-n|e>>>n,aA=(t,e,n)=>t<<64-n|e>>>n-32,cA=(t,e,n)=>t>>>n-32|e<<64-n,wRe=(t,e,n)=>t<>>32-n,bRe=(t,e,n)=>e<>>32-n,vRe=(t,e,n)=>e<>>64-n,xRe=(t,e,n)=>t<>>64-n;function Wf(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}const ERe=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),CRe=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,_Re=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),SRe=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,ARe=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),IRe=(t,e,n,r,s,i)=>e+n+r+s+i+(t/2**32|0)|0,Ww=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function uj(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function u0(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function jl(t,...e){if(!uj(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function OP(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");u0(t.outputLen),u0(t.blockLen)}function ay(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function dj(t,e){jl(t);const n=e.outputLen;if(t.length>>e}function NRe(t,e){return t<>>32-e>>>0}const fj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function hj(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Hce=fj?t=>t:t=>hj(t),PRe=Hce;function qce(t){for(let e=0;et:qce,Kce=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kRe=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Dv(t){if(jl(t),Kce)return t.toHex();let e="";for(let n=0;n=Vf._0&&t<=Vf._9)return t-Vf._0;if(t>=Vf.A&&t<=Vf.F)return t-(Vf.A-10);if(t>=Vf.a&&t<=Vf.f)return t-(Vf.a-10)}function pj(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Kce)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let s=0,i=0;s{};async function RRe(t,e,n){let r=Date.now();for(let s=0;s=0&&it().update(qh(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Zce(t){const e=(r,s)=>t(s).update(qh(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Yce(t){const e=(r,s)=>t(s).update(qh(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const MRe=gp,LRe=Zce,BRe=Yce;function LS(t=32){if(Ww&&typeof Ww.getRandomValues=="function")return Ww.getRandomValues(new Uint8Array(t));if(Ww&&typeof Ww.randomBytes=="function")return Uint8Array.from(Ww.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const URe=Object.freeze(Object.defineProperty({__proto__:null,Hash:$P,abytes:jl,aexists:ay,ahash:OP,anumber:u0,aoutput:dj,asyncLoop:RRe,byteSwap:hj,byteSwap32:qce,byteSwapIfBE:PRe,bytesToHex:Dv,bytesToUtf8:ORe,checkOpts:DRe,clean:lf,concatBytes:mC,createHasher:gp,createOptHasher:Zce,createView:BI,createXOFer:Yce,hexToBytes:pj,isBytes:uj,isLE:fj,kdfInputToBytes:$Re,nextTick:Gce,randomBytes:LS,rotl:NRe,rotr:xu,swap32IfBE:mL,swap8IfBE:Hce,toBytes:qh,u32:Vce,u8:TRe,utf8ToBytes:gj,wrapConstructor:MRe,wrapConstructorWithOpts:LRe,wrapXOFConstructorWithOpts:BRe},Symbol.toStringTag,{value:"Module"})),FRe=BigInt(0),Xx=BigInt(1),jRe=BigInt(2),zRe=BigInt(7),WRe=BigInt(256),VRe=BigInt(113),Xce=[],Qce=[],Jce=[];for(let t=0,e=Xx,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Xce.push(2*(5*r+n)),Qce.push((t+1)*(t+2)/2%64);let s=FRe;for(let i=0;i<7;i++)e=(e<>zRe)*VRe)%WRe,e&jRe&&(s^=Xx<<(Xx<n>32?vRe(t,e,n):wRe(t,e,n),_Y=(t,e,n)=>n>32?xRe(t,e,n):bRe(t,e,n);function KRe(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=n[c],u=n[c+1],d=CY(l,u,1)^n[a],f=_Y(l,u,1)^n[a+1];for(let p=0;p<50;p+=10)t[o+p]^=d,t[o+p+1]^=f}let s=t[2],i=t[3];for(let o=0;o<24;o++){const a=Qce[o],c=CY(s,i,a),l=_Y(s,i,a),u=Xce[o];s=t[u],i=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=HRe[r],t[1]^=qRe[r]}lf(n)}class mj extends $P{constructor(e,n,r,s=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=i,u0(r),!(0=r&&this.keccak();const o=Math.min(r-this.posOut,i-s);e.set(n.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=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 u0(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(dj(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,lf(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new mj(n,r,s,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const GRe=(t,e,n)=>gp(()=>new mj(e,t,n)),yj=GRe(1,136,256/8);function X1(t,e){const n=e||"hex",r=yj(Hh(t,{strict:!1})?RP(t):t);return n==="bytes"?r:Ov(r)}let DP=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}};const ZRe=/^0x[a-fA-F0-9]{40}$/,KO=new DP(8192);function uf(t,e){const{strict:n=!0}=e??{},r=`${t}.${n}`;if(KO.has(r))return KO.get(r);const s=ZRe.test(t)?t.toLowerCase()===t?!0:n?MP(t)===t:!0:!1;return KO.set(r,s),s}const GO=new DP(8192);function MP(t,e){if(GO.has(`${t}.${e}`))return GO.get(`${t}.${e}`);const n=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),r=X1(zce(n),"bytes"),s=(e?n.substring(`${e}0x`.length):n).split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(r[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const i=`0x${s.join("")}`;return GO.set(`${t}.${e}`,i),i}function wh(t,e){if(!uf(t,{strict:!1}))throw new iy({address:t});return MP(t,e)}let SY=class extends ot{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}},tle=class extends ot{constructor({length:e,position:n}){super(`Position \`${n}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}},YRe=class extends ot{constructor({count:e,limit:n}){super(`Recursive read limit of \`${n}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}};const XRe={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new YRe({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new tle({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new SY({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new SY({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const n=e??this.position;return this.assertPosition(n+t-1),this.bytes.subarray(n,n+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const n=this.inspectBytes(t);return this.position+=e??t,n},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function wj(t,{recursiveReadLimit:e=8192}={}){const n=Object.create(XRe);return n.bytes=t,n.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=e,n}function Mv(t,e,n,{strict:r}={}){return Hh(t,{strict:!1})?QRe(t,e,n,{strict:r}):sle(t,e,n,{strict:r})}function nle(t,e){if(typeof e=="number"&&e>0&&e>Hs(t)-1)throw new Lce({offset:e,position:"start",size:Hs(t)})}function rle(t,e,n){if(typeof e=="number"&&typeof n=="number"&&Hs(t)!==n-e)throw new Lce({offset:n,position:"end",size:Hs(t)})}function sle(t,e,n,{strict:r}={}){nle(t,e);const s=t.slice(e,n);return r&&rle(s,e,n),s}function QRe(t,e,n,{strict:r}={}){nle(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(n??t.length)*2)}`;return r&&rle(s,e,n),s}function JRe(t,e={}){typeof e.size<"u"&&Yl(t,{size:e.size});const n=Po(t,e);return l0(n,e)}function eOe(t,e={}){let n=t;if(typeof e.size<"u"&&(Yl(n,{size:e.size}),n=Gg(n)),n.length>1||n[0]>1)throw new cRe(n);return!!n[0]}function Ah(t,e={}){typeof e.size<"u"&&Yl(t,{size:e.size});const n=Po(t,e);return oy(n,e)}function tOe(t,e={}){let n=t;return typeof e.size<"u"&&(Yl(n,{size:e.size}),n=Gg(n,{dir:"right"})),new TextDecoder().decode(n)}function cy(t){return typeof t[0]=="string"?Q1(t):nOe(t)}function nOe(t){let e=0;for(const s of t)e+=s.length;const n=new Uint8Array(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}function Q1(t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}const Ckt=/^(.*)\[([0-9]*)\]$/,_kt=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,rOe=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function LP(t,e){if(t.length!==e.length)throw new J8e({expectedLength:t.length,givenLength:e.length});const n=sOe({params:t,values:e}),r=vj(n);return r.length===0?"0x":r}function sOe({params:t,values:e}){const n=[];for(let r=0;r0?cy([a,o]):a}}if(s)return{dynamic:!0,encoded:o}}return{dynamic:!1,encoded:cy(i.map(({encoded:o})=>o))}}function aOe(t,{param:e}){const[,n]=e.type.split("bytes"),r=Hs(t);if(!n){let s=t;return r%32!==0&&(s=Kg(s,{dir:"right",size:Math.ceil((t.length-2)/2/32)*32})),{dynamic:!0,encoded:cy([Kg($n(r,{size:32})),s])}}if(r!==Number.parseInt(n,10))throw new Q8e({expectedSize:Number.parseInt(n,10),value:t});return{dynamic:!1,encoded:Kg(t,{dir:"right"})}}function cOe(t){if(typeof t!="boolean")throw new ot(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Kg(jce(t))}}function lOe(t,{signed:e,size:n=256}){if(typeof n=="number"){const r=2n**(BigInt(n)-(e?1n:0n))-1n,s=e?-r-1n:0n;if(t>r||ts))}}function xj(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function BS(t,e){const n=typeof e=="string"?nd(e):e,r=wj(n);if(Hs(n)===0&&t.length>0)throw new kP;if(Hs(e)&&Hs(e)<32)throw new kce({data:typeof e=="string"?e:Po(e),params:t,size:Hs(e)});let s=0;const i=[];for(let o=0;o48?JRe(s,{signed:n}):Ah(s,{signed:n}),32]}function yOe(t,e,{staticPosition:n}){const r=e.components.length===0||e.components.some(({name:o})=>!o),s=r?[]:{};let i=0;if(yC(e)){const o=Ah(t.readBytes(yL)),a=n+o;for(let c=0;cX1(RP(t));function vOe(t){return bOe(t)}const xOe="1.0.8";let Xl=class wL extends Error{constructor(e,n={}){const r=n.cause instanceof wL?n.cause.details:n.cause?.message?n.cause.message:n.details,s=n.cause instanceof wL&&n.cause.docsPath||n.docsPath,i=[e||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...r?[`Details: ${r}`]:[],`Version: abitype@${xOe}`].join(` +`);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),n.cause&&(this.cause=n.cause),this.details=r,this.docsPath=s,this.metaMessages=n.metaMessages,this.shortMessage=e}};function mp(t,e){return t.exec(e)?.groups}const ile=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,ole=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,ale=/^\(.+?\).*?$/,IY=/^tuple(?(\[(\d*)\])*)$/;function bL(t){let e=t.type;if(IY.test(t.type)&&"components"in t){e="(";const n=t.components.length;for(let s=0;s[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;function COe(t){return cle.test(t)}function _Oe(t){return mp(cle,t)}const lle=/^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;function SOe(t){return lle.test(t)}function AOe(t){return mp(lle,t)}const ule=/^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/;function IOe(t){return ule.test(t)}function TOe(t){return mp(ule,t)}const dle=/^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/;function fle(t){return dle.test(t)}function NOe(t){return mp(dle,t)}const hle=/^constructor\((?.*?)\)(?:\s(?payable{1}))?$/;function POe(t){return hle.test(t)}function kOe(t){return mp(hle,t)}const ple=/^fallback\(\) external(?:\s(?payable{1}))?$/;function ROe(t){return ple.test(t)}function OOe(t){return mp(ple,t)}const $Oe=/^receive\(\) external payable$/;function DOe(t){return $Oe.test(t)}const MOe=new Set(["indexed"]),vL=new Set(["calldata","memory","storage"]);let LOe=class extends Xl{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},BOe=class extends Xl{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}},UOe=class extends Xl{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},FOe=class extends Xl{constructor({param:e,name:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${n}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},jOe=class extends Xl{constructor({param:e,type:n,modifier:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${r}" not allowed${n?` in "${n}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},zOe=class extends Xl{constructor({param:e,type:n,modifier:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${r}" not allowed${n?` in "${n}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${r}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},WOe=class extends Xl{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}},J1=class extends Xl{constructor({signature:e,type:n}){super(`Invalid ${n} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},VOe=class extends Xl{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},HOe=class extends Xl{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}},qOe=class extends Xl{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}},KOe=class extends Xl{constructor({current:e,depth:n}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${n>0?"opening":"closing"} parentheses.`],details:`Depth "${n}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};function GOe(t,e,n){let r="";if(n)for(const s of Object.entries(n)){if(!s)continue;let i="";for(const o of s[1])i+=`[${o.type}${o.name?`:${o.name}`:""}]`;r+=`(${s[0]}{${i}})`}return e?`${e}:${t}${r}`:t}const ZO=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]]);function ZOe(t,e={}){if(IOe(t))return YOe(t,e);if(SOe(t))return XOe(t,e);if(COe(t))return QOe(t,e);if(POe(t))return JOe(t,e);if(ROe(t))return e$e(t);if(DOe(t))return{type:"receive",stateMutability:"payable"};throw new VOe({signature:t})}function YOe(t,e={}){const n=TOe(t);if(!n)throw new J1({signature:t,type:"function"});const r=$u(n.parameters),s=[],i=r.length;for(let a=0;a[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,n$e=/^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,r$e=/^u?int$/;function ly(t,e){const n=GOe(t,e?.type,e?.structs);if(ZO.has(n))return ZO.get(n);const r=ale.test(t),s=mp(r?n$e:t$e,t);if(!s)throw new UOe({param:t});if(s.name&&i$e(s.name))throw new FOe({param:t,name:s.name});const i=s.name?{name:s.name}:{},o=s.modifier==="indexed"?{indexed:!0}:{},a=e?.structs??{};let c,l={};if(r){c="tuple";const d=$u(s.type),f=[],p=d.length;for(let m=0;m[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/;function mle(t,e,n=new Set){const r=[],s=t.length;for(let i=0;i{const e=typeof t=="string"?t:EOe(t);return l$e(e)};function wle(t){return vOe(u$e(t))}const Ej=wle,US=t=>Mv(wle(t),0,4);function FS(t){const{abi:e,args:n=[],name:r}=t,s=Hh(r,{strict:!1}),i=e.filter(a=>s?a.type==="function"?US(a)===r:a.type==="event"?Ej(a)===r:!1:"name"in a&&a.name===r);if(i.length===0)return;if(i.length===1)return i[0];let o;for(const a of i){if(!("inputs"in a))continue;if(!n||n.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==n.length)continue;if(n.every((l,u)=>{const d="inputs"in a&&a.inputs[u];return d?xL(l,d):!1})){if(o&&"inputs"in o&&o.inputs){const l=ble(a.inputs,o.inputs,n);if(l)throw new rRe({abiItem:a,type:l[0]},{abiItem:o,type:l[1]})}o=a}}return o||i[0]}function xL(t,e){const n=typeof t,r=e.type;switch(r){case"address":return uf(t,{strict:!1});case"bool":return n==="boolean";case"function":return n==="string";case"string":return n==="string";default:return r==="tuple"&&"components"in e?Object.values(e.components).every((s,i)=>xL(Object.values(t)[i],s)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(r)?n==="number"||n==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(r)?n==="string"||t instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(r)?Array.isArray(t)&&t.every(s=>xL(s,{...e,type:r.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function ble(t,e,n){for(const r in t){const s=t[r],i=e[r];if(s.type==="tuple"&&i.type==="tuple"&&"components"in s&&"components"in i)return ble(s.components,i.components,n[r]);const o=[s.type,i.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?uf(n[r],{strict:!1}):o.includes("address")&&o.includes("bytes")?uf(n[r],{strict:!1}):!1)return o}}const YO="/docs/contract/decodeFunctionResult";function Cj(t){const{abi:e,args:n,functionName:r,data:s}=t;let i=e[0];if(r){const a=FS({abi:e,args:n,name:r});if(!a)throw new Rv(r,{docsPath:YO});i=a}if(i.type!=="function")throw new Rv(void 0,{docsPath:YO});if(!i.outputs)throw new $ce(i.name,{docsPath:YO});const o=BS(i.outputs,s);if(o&&o.length>1)return o;if(o&&o.length===1)return o[0]}const TY="/docs/contract/encodeFunctionData";function d$e(t){const{abi:e,args:n,functionName:r}=t;let s=e[0];if(r){const i=FS({abi:e,args:n,name:r});if(!i)throw new Rv(r,{docsPath:TY});s=i}if(s.type!=="function")throw new Rv(void 0,{docsPath:TY});return{abi:[s],functionName:US(cf(s))}}function ex(t){const{args:e}=t,{abi:n,functionName:r}=t.abi.length===1&&t.functionName?.startsWith("0x")?t:d$e(t),s=n[0],i=r,o="inputs"in s&&s.inputs?LP(s.inputs,e??[]):void 0;return Q1([i,o??"0x"])}class EL extends ot{constructor({blockNumber:e,chain:n,contract:r}){super(`Chain "${n.name}" does not support contract "${r.name}".`,{metaMessages:["This could be due to any of the following:",...e&&r.blockCreated&&r.blockCreated>e?[`- The contract "${r.name}" was not deployed until block ${r.blockCreated} (current block ${e}).`]:[`- The chain does not have the contract "${r.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class f$e extends ot{constructor({chain:e,currentChainId:n}){super(`The current chain of the wallet (id: ${n}) does not match the target chain for the transaction (id: ${e.id} – ${e.name}).`,{metaMessages:[`Current Chain ID: ${n}`,`Expected Chain ID: ${e.id} – ${e.name}`],name:"ChainMismatchError"})}}class h$e extends ot{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(` +`),{name:"ChainNotFoundError"})}}class vle extends ot{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}function _j({blockNumber:t,chain:e,contract:n}){const r=e?.contracts?.[n];if(!r)throw new EL({chain:e,contract:{name:n}});if(t&&r.blockCreated&&r.blockCreated>t)throw new EL({blockNumber:t,chain:e,contract:{name:n,blockCreated:r.blockCreated}});return r.address}function Cf(t){return typeof t=="string"?{address:t,type:"json-rpc"}:t}const p$e={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},xle={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},g$e={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};function m$e(t){const{abi:e,data:n}=t,r=Mv(n,0,4);if(r==="0x")throw new kP;const i=[...e||[],xle,g$e].find(o=>o.type==="error"&&r===US(cf(o)));if(!i)throw new Rce(r,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?BS(i.inputs,Mv(n,4)):void 0,errorName:i.name}}const Dl=(t,e,n)=>JSON.stringify(t,(r,s)=>typeof s=="bigint"?s.toString():s,n);function Ele({abiItem:t,args:e,includeFunctionName:n=!0,includeName:r=!1}){if("name"in t&&"inputs"in t&&t.inputs)return`${n?t.name:""}(${t.inputs.map((s,i)=>`${r&&s.name?`${s.name}: `:""}${typeof e[i]=="object"?Dl(e[i]):e[i]}`).join(", ")})`}const y$e={gwei:9,wei:18},w$e={ether:-9,wei:9},b$e={ether:-18,gwei:-9};function tx(t,e){let n=t.toString();const r=n.startsWith("-");r&&(n=n.slice(1)),n=n.padStart(e,"0");let[s,i]=[n.slice(0,n.length-e),n.slice(n.length-e)];return i=i.replace(/(0+)$/,""),`${r?"-":""}${s||"0"}${i?`.${i}`:""}`}function Sj(t,e="wei"){return tx(t,y$e[e])}function Ga(t,e="wei"){return tx(t,w$e[e])}class v$e extends ot{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class x$e extends ot{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function NY(t){return t.reduce((e,{slot:n,value:r})=>`${e} ${n}: ${r} +`,"")}function E$e(t){return t.reduce((e,{address:n,...r})=>{let s=`${e} ${n}: +`;return r.nonce&&(s+=` nonce: ${r.nonce} +`),r.balance&&(s+=` balance: ${r.balance} +`),r.code&&(s+=` code: ${r.code} +`),r.state&&(s+=` state: +`,s+=NY(r.state)),r.stateDiff&&(s+=` stateDiff: +`,s+=NY(r.stateDiff)),s},` State Override: +`).slice(0,-1)}function jS(t){const e=Object.entries(t).map(([r,s])=>s===void 0||s===!1?null:[r,s]).filter(Boolean),n=e.reduce((r,[s])=>Math.max(r,s.length),0);return e.map(([r,s])=>` ${`${r}:`.padEnd(n+1)} ${s}`).join(` +`)}class C$e extends ot{constructor(){super(["Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.","Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."].join(` +`),{name:"FeeConflictError"})}}class _$e extends ot{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",jS(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class S$e extends ot{constructor(e,{account:n,docsPath:r,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:l,nonce:u,to:d,value:f}){const p=jS({chain:s&&`${s?.name} (id: ${s?.id})`,from:n?.address,to:d,value:typeof f<"u"&&`${Sj(f)} ${s?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Ga(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Ga(c)} gwei`,maxPriorityFeePerGas:typeof l<"u"&&`${Ga(l)} gwei`,nonce:u});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Request Arguments:",p].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class Cle extends ot{constructor({blockHash:e,blockNumber:n,blockTag:r,hash:s,index:i}){let o="Transaction";r&&i!==void 0&&(o=`Transaction at block time "${r}" at index "${i}"`),e&&i!==void 0&&(o=`Transaction at block hash "${e}" at index "${i}"`),n&&i!==void 0&&(o=`Transaction at block number "${n}" at index "${i}"`),s&&(o=`Transaction with hash "${s}"`),super(`${o} could not be found.`,{name:"TransactionNotFoundError"})}}class _le extends ot{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class A$e extends ot{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}const I$e=t=>t,Aj=t=>t;class Sle extends ot{constructor(e,{account:n,docsPath:r,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:l,nonce:u,to:d,value:f,stateOverride:p}){const m=n?Cf(n):void 0;let y=jS({from:m?.address,to:d,value:typeof f<"u"&&`${Sj(f)} ${s?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Ga(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Ga(c)} gwei`,maxPriorityFeePerGas:typeof l<"u"&&`${Ga(l)} gwei`,nonce:u});p&&(y+=` +${E$e(p)}`),super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Raw Call Arguments:",y].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class Ij extends ot{constructor(e,{abi:n,args:r,contractAddress:s,docsPath:i,functionName:o,sender:a}){const c=FS({abi:n,args:r,name:o}),l=c?Ele({abiItem:c,args:r,includeFunctionName:!1,includeName:!1}):void 0,u=c?cf(c,{includeName:!0}):void 0,d=jS({address:s&&I$e(s),function:u,args:l&&l!=="()"&&`${[...Array(o?.length??0).keys()].map(()=>" ").join("")}${l}`,sender:a});super(e.shortMessage||`An unknown error occurred while executing the contract function "${o}".`,{cause:e,docsPath:i,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],d&&"Contract Call:",d].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=n,this.args=r,this.cause=e,this.contractAddress=s,this.functionName=o,this.sender=a}}class CL extends ot{constructor({abi:e,data:n,functionName:r,message:s}){let i,o,a,c;if(n&&n!=="0x")try{o=m$e({abi:e,data:n});const{abiItem:u,errorName:d,args:f}=o;if(d==="Error")c=f[0];else if(d==="Panic"){const[p]=f;c=p$e[p]}else{const p=u?cf(u,{includeName:!0}):void 0,m=u&&f?Ele({abiItem:u,args:f,includeFunctionName:!1,includeName:!1}):void 0;a=[p?`Error: ${p}`:"",m&&m!=="()"?` ${[...Array(d?.length??0).keys()].map(()=>" ").join("")}${m}`:""]}}catch(u){i=u}else s&&(c=s);let l;i instanceof Rce&&(l=i.signature,a=[`Unable to decode signature "${l}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://openchain.xyz/signatures?query=${l}.`]),super(c&&c!=="execution reverted"||l?[`The contract function "${r}" reverted with the following ${l?"signature":"reason"}:`,c||l].join(` +`):`The contract function "${r}" reverted.`,{cause:i,metaMessages:a,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=o,this.raw=n,this.reason=c,this.signature=l}}class T$e extends ot{constructor({functionName:e}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class N$e extends ot{constructor({factory:e}){super(`Deployment for counterfactual contract call failed${e?` for factory "${e}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}}class Tj extends ot{constructor({data:e,message:n}){super(n||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e}}function P$e(t){if(!(t instanceof ot))return!1;const e=t.walk(n=>n instanceof CL);return e instanceof CL?e.data?.errorName==="HttpError"||e.data?.errorName==="ResolverError"||e.data?.errorName==="ResolverNotContract"||e.data?.errorName==="ResolverNotFound"||e.data?.errorName==="ReverseAddressMismatch"||e.data?.errorName==="UnsupportedResolverProfile":!1}function k$e(t){const{abi:e,data:n}=t,r=Mv(n,0,4),s=e.find(i=>i.type==="function"&&r===US(cf(i)));if(!s)throw new nRe(r,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:s.name,args:"inputs"in s&&s.inputs&&s.inputs.length>0?BS(s.inputs,Mv(n,4)):void 0}}const XO="/docs/contract/encodeErrorResult";function PY(t){const{abi:e,errorName:n,args:r}=t;let s=e[0];if(n){const c=FS({abi:e,args:r,name:n});if(!c)throw new mY(n,{docsPath:XO});s=c}if(s.type!=="error")throw new mY(void 0,{docsPath:XO});const i=cf(s),o=US(i);let a="0x";if(r&&r.length>0){if(!s.inputs)throw new eRe(s.name,{docsPath:XO});a=LP(s.inputs,r)}return Q1([o,a])}const QO="/docs/contract/encodeFunctionResult";function R$e(t){const{abi:e,functionName:n,result:r}=t;let s=e[0];if(n){const o=FS({abi:e,name:n});if(!o)throw new Rv(n,{docsPath:QO});s=o}if(s.type!=="function")throw new Rv(void 0,{docsPath:QO});if(!s.outputs)throw new $ce(s.name,{docsPath:QO});const i=(()=>{if(s.outputs.length===0)return[];if(s.outputs.length===1)return[r];if(Array.isArray(r))return r;throw new Mce(r)})();return LP(s.outputs,i)}const Ale="x-batch-gateway:true";async function O$e(t){const{data:e,ccipRequest:n}=t,{args:[r]}=k$e({abi:hL,data:e}),s=[],i=[];return await Promise.all(r.map(async(o,a)=>{try{i[a]=o.urls.includes(Ale)?await O$e({data:o.data,ccipRequest:n}):await n(o),s[a]=!1}catch(c){s[a]=!0,i[a]=$$e(c)}})),R$e({abi:hL,functionName:"query",result:[s,i]})}function $$e(t){return t.name==="HttpRequestError"&&t.status?PY({abi:hL,errorName:"HttpError",args:[t.status,t.shortMessage]}):PY({abi:[xle],errorName:"Error",args:["shortMessage"in t?t.shortMessage:t.message]})}function $r(t,e,n){const r=t[e.name];if(typeof r=="function")return r;const s=t[n];return typeof s=="function"?s:i=>e(t,i)}class mE extends ot{constructor({body:e,cause:n,details:r,headers:s,status:i,url:o}){super("HTTP request failed.",{cause:n,details:r,metaMessages:[i&&`Status: ${i}`,`URL: ${Aj(o)}`,e&&`Request body: ${Dl(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=s,this.status=i,this.url=o}}class Nj extends ot{constructor({body:e,error:n,url:r}){super("RPC Request failed.",{cause:n,details:n.message,metaMessages:[`URL: ${Aj(r)}`,`Request body: ${Dl(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=n.code,this.data=n.data}}let kY=class extends ot{constructor({body:e,url:n}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Aj(n)}`,`Request body: ${Dl(e)}`],name:"TimeoutError"})}};const D$e=-1;class tc extends ot{constructor(e,{code:n,docsPath:r,metaMessages:s,name:i,shortMessage:o}){super(o,{cause:e,docsPath:r,metaMessages:s||e?.metaMessages,name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||e.name,this.code=e instanceof Nj?e.code:n??D$e}}class Zc extends tc{constructor(e,n){super(e,n),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=n.data}}class wC extends tc{constructor(e){super(e,{code:wC.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(wC,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class bC extends tc{constructor(e){super(e,{code:bC.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(bC,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class vC extends tc{constructor(e,{method:n}={}){super(e,{code:vC.code,name:"MethodNotFoundRpcError",shortMessage:`The method${n?` "${n}"`:""} does not exist / is not available.`})}}Object.defineProperty(vC,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class xC extends tc{constructor(e){super(e,{code:xC.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(` +`)})}}Object.defineProperty(xC,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class uy extends tc{constructor(e){super(e,{code:uy.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(uy,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class EC extends tc{constructor(e){super(e,{code:EC.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(` +`)})}}Object.defineProperty(EC,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class CC extends tc{constructor(e){super(e,{code:CC.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(CC,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class Zg extends tc{constructor(e){super(e,{code:Zg.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(Zg,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Lv extends tc{constructor(e){super(e,{code:Lv.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Lv,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class ym extends tc{constructor(e,{method:n}={}){super(e,{code:ym.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${n?` "${n}"`:""} is not supported.`})}}Object.defineProperty(ym,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Bv extends tc{constructor(e){super(e,{code:Bv.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Bv,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class _C extends tc{constructor(e){super(e,{code:_C.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(_C,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class ti extends Zc{constructor(e){super(e,{code:ti.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(ti,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class SC extends Zc{constructor(e){super(e,{code:SC.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(SC,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class AC extends Zc{constructor(e,{method:n}={}){super(e,{code:AC.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${n?` " ${n}"`:""}.`})}}Object.defineProperty(AC,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class IC extends Zc{constructor(e){super(e,{code:IC.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(IC,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class TC extends Zc{constructor(e){super(e,{code:TC.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(TC,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class df extends Zc{constructor(e){super(e,{code:df.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(df,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class NC extends Zc{constructor(e){super(e,{code:NC.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(NC,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class PC extends Zc{constructor(e){super(e,{code:PC.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(PC,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class kC extends Zc{constructor(e){super(e,{code:kC.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(kC,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class RC extends Zc{constructor(e){super(e,{code:RC.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(RC,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class OC extends Zc{constructor(e){super(e,{code:OC.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(OC,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class $C extends Zc{constructor(e){super(e,{code:$C.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty($C,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class DC extends Zc{constructor(e){super(e,{code:DC.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(DC,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class M$e extends tc{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const L$e=3;function rT(t,{abi:e,address:n,args:r,docsPath:s,functionName:i,sender:o}){const a=t instanceof Tj?t:t instanceof ot?t.walk(m=>"data"in m)||t.walk():{},{code:c,data:l,details:u,message:d,shortMessage:f}=a,p=t instanceof kP?new T$e({functionName:i}):[L$e,uy.code].includes(c)&&(l||u||d||f)?new CL({abi:e,data:typeof l=="object"?l.data:l,functionName:i,message:a instanceof Nj?u:f??d}):t;return new Ij(p,{abi:e,args:r,contractAddress:n,docsPath:s,functionName:i,sender:o})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Pj=BigInt(0),_L=BigInt(1);function zS(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function kj(t){if(!zS(t))throw new Error("Uint8Array expected")}function MC(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function lA(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Ile(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Pj:BigInt("0x"+t)}const Tle=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",B$e=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function LC(t){if(kj(t),Tle)return t.toHex();let e="";for(let n=0;n=Hf._0&&t<=Hf._9)return t-Hf._0;if(t>=Hf.A&&t<=Hf.F)return t-(Hf.A-10);if(t>=Hf.a&&t<=Hf.f)return t-(Hf.a-10)}function sT(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Tle)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let s=0,i=0;stypeof t=="bigint"&&Pj<=t;function Rj(t,e,n){return JO(t)&&JO(e)&&JO(n)&&e<=t&&tPj;t>>=_L,e+=1);return e}const BP=t=>(_L<new Uint8Array(t),OY=t=>Uint8Array.from(t);function F$e(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=e$(t),s=e$(t),i=0;const o=()=>{r.fill(1),s.fill(0),i=0},a=(...d)=>n(s,r,...d),c=(d=e$(0))=>{s=a(OY([0]),d),r=a(),d.length!==0&&(s=a(OY([1]),d),r=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const f=[];for(;d{o(),c(d);let p;for(;!(p=f(l()));)c();return o(),p}}const j$e={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||zS(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function UP(t,e,n={}){const r=(s,i,o)=>{const a=j$e[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))r(s,i,!1);for(const[s,i]of Object.entries(n))r(s,i,!0);return t}function $Y(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const i=t(n,...r);return e.set(n,i),i}}const z$e="0.1.1";function W$e(){return z$e}let vr=class SL extends Error{constructor(e,n={}){const r=(()=>{if(n.cause instanceof SL){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&"details"in n.cause&&typeof n.cause.details=="string"?n.cause.details:n.cause?.message?n.cause.message:n.details})(),s=n.cause instanceof SL&&n.cause.docsPath||n.docsPath,o=`https://oxlib.sh${s??""}`,a=[e||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||s?["",r?`Details: ${r}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(` +`);super(a,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${W$e()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=s,this.shortMessage=e}walk(e){return kle(this,e)}};function kle(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?kle(t.cause,e):e?null:t}function VS(t,e){if(Bb(t)>e)throw new oDe({givenSize:Bb(t),maxSize:e})}const qf={zero:48,nine:57,A:65,F:70,a:97,f:102};function DY(t){if(t>=qf.zero&&t<=qf.nine)return t-qf.zero;if(t>=qf.A&&t<=qf.F)return t-(qf.A-10);if(t>=qf.a&&t<=qf.f)return t-(qf.a-10)}function V$e(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new aDe({size:t.length,targetSize:r,type:"Bytes"});const s=new Uint8Array(r);for(let i=0;ie)throw new fDe({givenSize:Fc(t),maxSize:e})}function H$e(t,e){if(typeof e=="number"&&e>0&&e>Fc(t)-1)throw new zle({offset:e,position:"start",size:Fc(t)})}function q$e(t,e,n){if(typeof e=="number"&&typeof n=="number"&&Fc(t)!==n-e)throw new zle({offset:n,position:"end",size:Fc(t)})}function Ole(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;const s=t.replace("0x","");if(s.length>r*2)throw new hDe({size:Math.ceil(s.length/2),targetSize:r,type:"Hex"});return`0x${s[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const K$e="#__bigint";function $le(t,e,n){return JSON.stringify(t,(r,s)=>typeof s=="bigint"?s.toString()+K$e:s,n)}const G$e=new TextDecoder,Z$e=new TextEncoder;function Y$e(t){return t instanceof Uint8Array?t:typeof t=="string"?Dle(t):X$e(t)}function X$e(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Dle(t,e={}){const{size:n}=e;let r=t;n&&(FP(t,n),r=fy(t,n));let s=r.slice(2);s.length%2&&(s=`0${s}`);const i=s.length/2,o=new Uint8Array(i);for(let a=0,c=0;a1||r[0]>1)throw new iDe(r);return!!r[0]}function Ih(t,e={}){const{size:n}=e;typeof n<"u"&&VS(t,n);const r=rd(t,e);return Fle(r,e)}function rDe(t,e={}){const{size:n}=e;let r=t;return typeof n<"u"&&(VS(r,n),r=sDe(r)),G$e.decode(r)}function Mle(t){return Rle(t,{dir:"left"})}function sDe(t){return Rle(t,{dir:"right"})}class iDe extends vr{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}}let oDe=class extends vr{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},aDe=class extends vr{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const cDe=new TextEncoder,lDe=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function uDe(t,e={}){const{strict:n=!1}=e;if(!t)throw new MY(t);if(typeof t!="string")throw new MY(t);if(n&&!/^0x[0-9a-fA-F]*$/.test(t))throw new LY(t);if(!t.startsWith("0x"))throw new LY(t)}function Kh(...t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}function dDe(t){return t instanceof Uint8Array?rd(t):Array.isArray(t)?rd(new Uint8Array(t)):t}function Lle(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(FP(n,e.size),dy(n,e.size)):n}function rd(t,e={}){let n="";for(let s=0;si||s>1n;return r<=o?r:r-i-1n}function Fle(t,e={}){const{signed:n,size:r}=e;return Number(!n&&!r?t:Ule(t,e))}function Fkt(t,e={}){const{strict:n=!1}=e;try{return uDe(t,{strict:n}),!0}catch{return!1}}let jle=class extends vr{constructor({max:e,min:n,signed:r,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*8}-bit`:""}${r?" signed":" unsigned"} integer range ${e?`(\`${n}\` to \`${e}\`)`:`(above \`${n}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}};class MY extends vr{constructor(e){super(`Value \`${typeof e=="object"?$le(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class LY extends vr{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}let fDe=class extends vr{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};class zle extends vr{constructor({offset:e,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let hDe=class extends vr{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};function pDe(t){return{address:t.address,amount:Zo(t.amount),index:Zo(t.index),validatorIndex:Zo(t.validatorIndex)}}function gDe(t){return{...typeof t.baseFeePerGas=="bigint"&&{baseFeePerGas:Zo(t.baseFeePerGas)},...typeof t.blobBaseFee=="bigint"&&{blobBaseFee:Zo(t.blobBaseFee)},...typeof t.feeRecipient=="string"&&{feeRecipient:t.feeRecipient},...typeof t.gasLimit=="bigint"&&{gasLimit:Zo(t.gasLimit)},...typeof t.number=="bigint"&&{number:Zo(t.number)},...typeof t.prevRandao=="bigint"&&{prevRandao:Zo(t.prevRandao)},...typeof t.time=="bigint"&&{time:Zo(t.time)},...t.withdrawals&&{withdrawals:t.withdrawals.map(pDe)}}}const mDe="0x82ad56cb",yDe="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",wDe="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",bDe="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",Oj="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033",t$="/docs/contract/encodeDeployData";function $j(t){const{abi:e,args:n,bytecode:r}=t;if(!n||n.length===0)return r;const s=e.find(o=>"type"in o&&o.type==="constructor");if(!s)throw new Y8e({docsPath:t$});if(!("inputs"in s))throw new gY({docsPath:t$});if(!s.inputs||s.inputs.length===0)throw new gY({docsPath:t$});const i=LP(s.inputs,n);return Q1([r,i])}class wm extends ot{constructor({cause:e,message:n}={}){const r=n?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${r?`with reason: ${r}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(wm,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(wm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class oT extends ot{constructor({cause:e,maxFeePerGas:n}={}){super(`The fee cap (\`maxFeePerGas\`${n?` = ${Ga(n)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(oT,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class AL extends ot{constructor({cause:e,maxFeePerGas:n}={}){super(`The fee cap (\`maxFeePerGas\`${n?` = ${Ga(n)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(AL,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class IL extends ot{constructor({cause:e,nonce:n}={}){super(`Nonce provided for the transaction ${n?`(${n}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty(IL,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class TL extends ot{constructor({cause:e,nonce:n}={}){super([`Nonce provided for the transaction ${n?`(${n}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(` +`),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(TL,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class NL extends ot{constructor({cause:e,nonce:n}={}){super(`Nonce provided for the transaction ${n?`(${n}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(NL,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class PL extends ot{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(` +`),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(PL,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class kL extends ot{constructor({cause:e,gas:n}={}){super(`The amount of gas ${n?`(${n}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(kL,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class RL extends ot{constructor({cause:e,gas:n}={}){super(`The amount of gas ${n?`(${n}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(RL,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class OL extends ot{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(OL,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class aT extends ot{constructor({cause:e,maxPriorityFeePerGas:n,maxFeePerGas:r}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${n?` = ${Ga(n)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${r?` = ${Ga(r)} gwei`:""}).`].join(` +`),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(aT,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class jP extends ot{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function Dj(t,e){const n=(t.details||"").toLowerCase(),r=t instanceof ot?t.walk(s=>s?.code===wm.code):t;return r instanceof ot?new wm({cause:t,message:r.details}):wm.nodeMessage.test(n)?new wm({cause:t,message:t.details}):oT.nodeMessage.test(n)?new oT({cause:t,maxFeePerGas:e?.maxFeePerGas}):AL.nodeMessage.test(n)?new AL({cause:t,maxFeePerGas:e?.maxFeePerGas}):IL.nodeMessage.test(n)?new IL({cause:t,nonce:e?.nonce}):TL.nodeMessage.test(n)?new TL({cause:t,nonce:e?.nonce}):NL.nodeMessage.test(n)?new NL({cause:t,nonce:e?.nonce}):PL.nodeMessage.test(n)?new PL({cause:t}):kL.nodeMessage.test(n)?new kL({cause:t,gas:e?.gas}):RL.nodeMessage.test(n)?new RL({cause:t,gas:e?.gas}):OL.nodeMessage.test(n)?new OL({cause:t}):aT.nodeMessage.test(n)?new aT({cause:t,maxFeePerGas:e?.maxFeePerGas,maxPriorityFeePerGas:e?.maxPriorityFeePerGas}):new jP({cause:t})}function vDe(t,{docsPath:e,...n}){const r=(()=>{const s=Dj(t,n);return s instanceof jP?t:s})();return new Sle(r,{docsPath:e,...n})}function Mj(t,{format:e}){if(!e)return{};const n={};function r(i){const o=Object.keys(i);for(const a of o)a in t&&(n[a]=t[a]),i[a]&&typeof i[a]=="object"&&!Array.isArray(i[a])&&r(i[a])}const s=e(t||{});return r(s),n}const xDe={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Lj(t){const e={};return typeof t.authorizationList<"u"&&(e.authorizationList=EDe(t.authorizationList)),typeof t.accessList<"u"&&(e.accessList=t.accessList),typeof t.blobVersionedHashes<"u"&&(e.blobVersionedHashes=t.blobVersionedHashes),typeof t.blobs<"u"&&(typeof t.blobs[0]!="string"?e.blobs=t.blobs.map(n=>Po(n)):e.blobs=t.blobs),typeof t.data<"u"&&(e.data=t.data),typeof t.from<"u"&&(e.from=t.from),typeof t.gas<"u"&&(e.gas=$n(t.gas)),typeof t.gasPrice<"u"&&(e.gasPrice=$n(t.gasPrice)),typeof t.maxFeePerBlobGas<"u"&&(e.maxFeePerBlobGas=$n(t.maxFeePerBlobGas)),typeof t.maxFeePerGas<"u"&&(e.maxFeePerGas=$n(t.maxFeePerGas)),typeof t.maxPriorityFeePerGas<"u"&&(e.maxPriorityFeePerGas=$n(t.maxPriorityFeePerGas)),typeof t.nonce<"u"&&(e.nonce=$n(t.nonce)),typeof t.to<"u"&&(e.to=t.to),typeof t.type<"u"&&(e.type=xDe[t.type]),typeof t.value<"u"&&(e.value=$n(t.value)),e}function EDe(t){return t.map(e=>({address:e.address,r:e.r?$n(BigInt(e.r)):e.r,s:e.s?$n(BigInt(e.s)):e.s,chainId:$n(e.chainId),nonce:$n(e.nonce),...typeof e.yParity<"u"?{yParity:$n(e.yParity)}:{},...typeof e.v<"u"&&typeof e.yParity>"u"?{v:$n(e.v)}:{}}))}function Wle(){let t=()=>{},e=()=>{};return{promise:new Promise((r,s)=>{t=r,e=s}),resolve:t,reject:e}}const n$=new Map;function Vle({fn:t,id:e,shouldSplitBatch:n,wait:r=0,sort:s}){const i=async()=>{const u=c();o();const d=u.map(({args:f})=>f);d.length!==0&&t(d).then(f=>{s&&Array.isArray(f)&&f.sort(s);for(let p=0;p{for(let p=0;pn$.delete(e),a=()=>c().map(({args:u})=>u),c=()=>n$.get(e)||[],l=u=>n$.set(e,[...c(),u]);return{flush:o,async schedule(u){const{promise:d,resolve:f,reject:p}=Wle();return n?.([...a(),u])&&i(),c().length>0?(l({args:u,resolve:f,reject:p}),d):(l({args:u,resolve:f,reject:p}),setTimeout(i,r),d)}}}function BY(t){if(!(!t||t.length===0))return t.reduce((e,{slot:n,value:r})=>{if(n.length!==66)throw new yY({size:n.length,targetSize:66,type:"hex"});if(r.length!==66)throw new yY({size:r.length,targetSize:66,type:"hex"});return e[n]=r,e},{})}function CDe(t){const{balance:e,nonce:n,state:r,stateDiff:s,code:i}=t,o={};if(i!==void 0&&(o.code=i),e!==void 0&&(o.balance=$n(e)),n!==void 0&&(o.nonce=$n(n)),r!==void 0&&(o.state=BY(r)),s!==void 0){if(o.state)throw new x$e;o.stateDiff=BY(s)}return o}function Hle(t){if(!t)return;const e={};for(const{address:n,...r}of t){if(!uf(n,{strict:!1}))throw new iy({address:n});if(e[n])throw new v$e({address:n});e[n]=CDe(r)}return e}const _De=2n**256n-1n;function zP(t){const{account:e,gasPrice:n,maxFeePerGas:r,maxPriorityFeePerGas:s,to:i}=t,o=e?Cf(e):void 0;if(o&&!uf(o.address))throw new iy({address:o.address});if(i&&!uf(i))throw new iy({address:i});if(typeof n<"u"&&(typeof r<"u"||typeof s<"u"))throw new C$e;if(r&&r>_De)throw new oT({maxFeePerGas:r});if(s&&r&&s>r)throw new aT({maxFeePerGas:r,maxPriorityFeePerGas:s})}async function Bj(t,e){const{account:n=t.account,authorizationList:r,batch:s=!!t.batch?.multicall,blockNumber:i,blockTag:o=t.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:l,code:u,data:d,factory:f,factoryData:p,gas:m,gasPrice:y,maxFeePerBlobGas:b,maxFeePerGas:v,maxPriorityFeePerGas:x,nonce:E,to:A,value:_,stateOverride:k,...B}=e,W=n?Cf(n):void 0;if(u&&(f||p))throw new ot("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(u&&A)throw new ot("Cannot provide both `code` & `to` as parameters.");const S=u&&d,$=f&&p&&A&&d,R=S||$,M=S?qle({code:u,data:d}):$?IDe({data:d,factory:f,factoryData:p,to:A}):d;try{zP(e);const z=(typeof i=="bigint"?$n(i):void 0)||o,N=l?gDe(l):void 0,T=Hle(k),U=t.chain?.formatters?.transactionRequest?.format,P=(U||Lj)({...Mj(B,{format:U}),from:W?.address,accessList:a,authorizationList:r,blobs:c,data:M,gas:m,gasPrice:y,maxFeePerBlobGas:b,maxFeePerGas:v,maxPriorityFeePerGas:x,nonce:E,to:R?void 0:A,value:_});if(s&&SDe({request:P})&&!T&&!N)try{return await ADe(t,{...P,blockNumber:i,blockTag:o})}catch(re){if(!(re instanceof vle)&&!(re instanceof EL))throw re}const H=(()=>{const re=[P,z];return T&&N?[...re,T,N]:T?[...re,T]:N?[...re,{},N]:re})(),Y=await t.request({method:"eth_call",params:H});return Y==="0x"?{data:void 0}:{data:Y}}catch(j){const z=TDe(j),{offchainLookup:N,offchainLookupSignature:T}=await et(async()=>{const{offchainLookup:U,offchainLookupSignature:L}=await import("./ccip-CSxoh1Sw.js");return{offchainLookup:U,offchainLookupSignature:L}},[]);if(t.ccipRead!==!1&&z?.slice(0,10)===T&&A)return{data:await N(t,{data:z,to:A})};throw R&&z?.slice(0,10)==="0x101bb98d"?new N$e({factory:f}):vDe(j,{...e,account:W,chain:t.chain})}}function SDe({request:t}){const{data:e,to:n,...r}=t;return!(!e||e.startsWith(mDe)||!n||Object.values(r).filter(s=>typeof s<"u").length>0)}async function ADe(t,e){const{batchSize:n=1024,deployless:r=!1,wait:s=0}=typeof t.batch?.multicall=="object"?t.batch.multicall:{},{blockNumber:i,blockTag:o=t.experimental_blockTag??"latest",data:a,to:c}=e,l=(()=>{if(r)return null;if(e.multicallAddress)return e.multicallAddress;if(t.chain)return _j({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new vle})(),d=(typeof i=="bigint"?$n(i):void 0)||o,{schedule:f}=Vle({id:`${t.uid}.${d}`,wait:s,shouldSplitBatch(y){return y.reduce((v,{data:x})=>v+(x.length-2),0)>n*2},fn:async y=>{const b=y.map(E=>({allowFailure:!0,callData:E.data,target:E.to})),v=ex({abi:nT,args:[b],functionName:"aggregate3"}),x=await t.request({method:"eth_call",params:[{...l===null?{data:qle({code:Oj,data:v})}:{to:l,data:v}},d]});return Cj({abi:nT,args:[b],functionName:"aggregate3",data:x||"0x"})}}),[{returnData:p,success:m}]=await f({data:a,to:c});if(!m)throw new Tj({data:p});return p==="0x"?{data:void 0}:{data:p}}function qle(t){const{code:e,data:n}=t;return $j({abi:yle(["constructor(bytes, bytes)"]),bytecode:yDe,args:[e,n]})}function IDe(t){const{data:e,factory:n,factoryData:r,to:s}=t;return $j({abi:yle(["constructor(address, bytes, address, bytes)"]),bytecode:wDe,args:[s,e,n,r]})}function TDe(t){if(!(t instanceof ot))return;const e=t.walk();return typeof e?.data=="object"?e.data?.data:e.data}async function HS(t,e){const{abi:n,address:r,args:s,functionName:i,...o}=e,a=ex({abi:n,args:s,functionName:i});try{const{data:c}=await $r(t,Bj,"call")({...o,data:a,to:r});return Cj({abi:n,args:s,functionName:i,data:c||"0x"})}catch(c){throw rT(c,{abi:n,address:r,args:s,docsPath:"/docs/contract/readContract",functionName:i})}}async function NDe(t,e){const{address:n,blockNumber:r,blockTag:s,coinType:i=60n,gatewayUrls:o,strict:a}=e,{chain:c}=t,l=(()=>{if(e.universalResolverAddress)return e.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return _j({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})();try{const u={address:l,abi:G8e,args:[n,i,o??[Ale]],functionName:"reverseWithGateways",blockNumber:r,blockTag:s},d=$r(t,HS,"readContract"),[f]=await d(u);return f||null}catch(u){if(a)throw u;if(P$e(u))return null;throw u}}function PDe(t,{method:e}){const n={};return t.transport.type==="fallback"&&t.transport.onResponse?.(({method:r,response:s,status:i,transport:o})=>{i==="success"&&e===r&&(n[s]=o.request)}),r=>n[r]||t.request}async function kDe(t){const e=PDe(t,{method:"eth_newPendingTransactionFilter"}),n=await t.request({method:"eth_newPendingTransactionFilter"});return{id:n,request:e(n),type:"transaction"}}function RDe(t){const e=X1(`0x${t.substring(4)}`).substring(26);return MP(`0x${e}`)}async function ODe({hash:t,signature:e}){const n=Hh(t)?t:Ov(t),{secp256k1:r}=await et(async()=>{const{secp256k1:o}=await Promise.resolve().then(()=>PLe);return{secp256k1:o}},void 0);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:d,yParity:f}=e,p=Number(f??d),m=UY(p);return new r.Signature(l0(l),l0(u)).addRecoveryBit(m)}const o=Hh(e)?e:Ov(e);if(Hs(o)!==65)throw new Error("invalid signature length");const a=oy(`0x${o.slice(130)}`),c=UY(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(n.substring(2)).toHex(!1)}`}function UY(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Kle({hash:t,signature:e}){return RDe(await ODe({hash:t,signature:e}))}function $De(t,e="hex"){const n=Gle(t),r=wj(new Uint8Array(n.length));return n.encode(r),e==="hex"?Po(r.bytes):r.bytes}function Gle(t){return Array.isArray(t)?DDe(t.map(e=>Gle(e))):MDe(t)}function DDe(t){const e=t.reduce((s,i)=>s+i.length,0),n=Zle(e);return{length:e<=55?1+e:1+n+e,encode(s){e<=55?s.pushByte(192+e):(s.pushByte(247+n),n===1?s.pushUint8(e):n===2?s.pushUint16(e):n===3?s.pushUint24(e):s.pushUint32(e));for(const{encode:i}of t)i(s)}}}function MDe(t){const e=typeof t=="string"?nd(t):t,n=Zle(e.length);return{length:e.length===1&&e[0]<128?1:e.length<=55?1+e.length:1+n+e.length,encode(s){e.length===1&&e[0]<128?s.pushBytes(e):e.length<=55?(s.pushByte(128+e.length),s.pushBytes(e)):(s.pushByte(183+n),n===1?s.pushUint8(e.length):n===2?s.pushUint16(e.length):n===3?s.pushUint24(e.length):s.pushUint32(e.length),s.pushBytes(e))}}}function Zle(t){if(t<2**8)return 1;if(t<2**16)return 2;if(t<2**24)return 3;if(t<2**32)return 4;throw new ot("Length is too large.")}function LDe(t){const{chainId:e,nonce:n,to:r}=t,s=t.contractAddress??t.address,i=X1(Q1(["0x05",$De([e?$n(e):"0x",s,n?$n(n):"0x"])]));return r==="bytes"?nd(i):i}async function Uj(t){const{authorization:e,signature:n}=t;return Kle({hash:LDe(e),signature:n??e})}class BDe extends ot{constructor(e,{account:n,docsPath:r,chain:s,data:i,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:l,nonce:u,to:d,value:f}){const p=jS({from:n?.address,to:d,value:typeof f<"u"&&`${Sj(f)} ${s?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:o,gasPrice:typeof a<"u"&&`${Ga(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Ga(c)} gwei`,maxPriorityFeePerGas:typeof l<"u"&&`${Ga(l)} gwei`,nonce:u});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",p].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}function UDe(t,{docsPath:e,...n}){const r=(()=>{const s=Dj(t,n);return s instanceof jP?t:s})();return new BDe(r,{docsPath:e,...n})}class FDe extends ot{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Fj extends ot{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class jDe extends ot{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Ga(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class Yle extends ot{constructor({blockHash:e,blockNumber:n}){let r="Block";e&&(r=`Block at hash "${e}"`),n&&(r=`Block at number "${n}"`),super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}const Xle={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Qle(t){const e={...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,chainId:t.chainId?oy(t.chainId):void 0,gas:t.gas?BigInt(t.gas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,maxFeePerBlobGas:t.maxFeePerBlobGas?BigInt(t.maxFeePerBlobGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,nonce:t.nonce?oy(t.nonce):void 0,to:t.to?t.to:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,type:t.type?Xle[t.type]:void 0,typeHex:t.type?t.type:void 0,value:t.value?BigInt(t.value):void 0,v:t.v?BigInt(t.v):void 0};return t.authorizationList&&(e.authorizationList=zDe(t.authorizationList)),e.yParity=(()=>{if(t.yParity)return Number(t.yParity);if(typeof e.v=="bigint"){if(e.v===0n||e.v===27n)return 0;if(e.v===1n||e.v===28n)return 1;if(e.v>=35n)return e.v%2n===0n?1:0}})(),e.type==="legacy"&&(delete e.accessList,delete e.maxFeePerBlobGas,delete e.maxFeePerGas,delete e.maxPriorityFeePerGas,delete e.yParity),e.type==="eip2930"&&(delete e.maxFeePerBlobGas,delete e.maxFeePerGas,delete e.maxPriorityFeePerGas),e.type==="eip1559"&&delete e.maxFeePerBlobGas,e}function zDe(t){return t.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))}function WDe(t){const e=(t.transactions??[]).map(n=>typeof n=="string"?n:Qle(n));return{...t,baseFeePerGas:t.baseFeePerGas?BigInt(t.baseFeePerGas):null,blobGasUsed:t.blobGasUsed?BigInt(t.blobGasUsed):void 0,difficulty:t.difficulty?BigInt(t.difficulty):void 0,excessBlobGas:t.excessBlobGas?BigInt(t.excessBlobGas):void 0,gasLimit:t.gasLimit?BigInt(t.gasLimit):void 0,gasUsed:t.gasUsed?BigInt(t.gasUsed):void 0,hash:t.hash?t.hash:null,logsBloom:t.logsBloom?t.logsBloom:null,nonce:t.nonce?t.nonce:null,number:t.number?BigInt(t.number):null,size:t.size?BigInt(t.size):void 0,timestamp:t.timestamp?BigInt(t.timestamp):void 0,transactions:e,totalDifficulty:t.totalDifficulty?BigInt(t.totalDifficulty):null}}async function BC(t,{blockHash:e,blockNumber:n,blockTag:r=t.experimental_blockTag??"latest",includeTransactions:s}={}){const i=s??!1,o=n!==void 0?$n(n):void 0;let a=null;if(e?a=await t.request({method:"eth_getBlockByHash",params:[e,i]},{dedupe:!0}):a=await t.request({method:"eth_getBlockByNumber",params:[o||r,i]},{dedupe:!!o}),!a)throw new Yle({blockHash:e,blockNumber:n});return(t.chain?.formatters?.block?.format||WDe)(a)}async function Jle(t){const e=await t.request({method:"eth_gasPrice"});return BigInt(e)}async function Vkt(t,e){return eue(t,e)}async function eue(t,e){const{block:n,chain:r=t.chain,request:s}=e||{};try{const i=r?.fees?.maxPriorityFeePerGas??r?.fees?.defaultPriorityFee;if(typeof i=="function"){const a=n||await $r(t,BC,"getBlock")({}),c=await i({block:a,client:t,request:s});if(c===null)throw new Error;return c}if(typeof i<"u")return i;const o=await t.request({method:"eth_maxPriorityFeePerGas"});return l0(o)}catch{const[i,o]=await Promise.all([n?Promise.resolve(n):$r(t,BC,"getBlock")({}),$r(t,Jle,"getGasPrice")({})]);if(typeof i.baseFeePerGas!="bigint")throw new Fj;const a=o-i.baseFeePerGas;return a<0n?0n:a}}async function Hkt(t,e){return $L(t,e)}async function $L(t,e){const{block:n,chain:r=t.chain,request:s,type:i="eip1559"}=e||{},o=await(async()=>typeof r?.fees?.baseFeeMultiplier=="function"?r.fees.baseFeeMultiplier({block:n,client:t,request:s}):r?.fees?.baseFeeMultiplier??1.2)();if(o<1)throw new FDe;const c=10**(o.toString().split(".")[1]?.length??0),l=f=>f*BigInt(Math.ceil(o*c))/BigInt(c),u=n||await $r(t,BC,"getBlock")({});if(typeof r?.fees?.estimateFeesPerGas=="function"){const f=await r.fees.estimateFeesPerGas({block:n,client:t,multiply:l,request:s,type:i});if(f!==null)return f}if(i==="eip1559"){if(typeof u.baseFeePerGas!="bigint")throw new Fj;const f=typeof s?.maxPriorityFeePerGas=="bigint"?s.maxPriorityFeePerGas:await eue(t,{block:u,chain:r,request:s}),p=l(u.baseFeePerGas);return{maxFeePerGas:s?.maxFeePerGas??p+f,maxPriorityFeePerGas:f}}return{gasPrice:s?.gasPrice??l(await $r(t,Jle,"getGasPrice")({}))}}async function VDe(t,{address:e,blockTag:n="latest",blockNumber:r}){const s=await t.request({method:"eth_getTransactionCount",params:[e,typeof r=="bigint"?$n(r):n]},{dedupe:!!r});return oy(s)}function tue(t){const{kzg:e}=t,n=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),r=typeof t.blobs[0]=="string"?t.blobs.map(i=>nd(i)):t.blobs,s=[];for(const i of r)s.push(Uint8Array.from(e.blobToKzgCommitment(i)));return n==="bytes"?s:s.map(i=>Po(i))}function nue(t){const{kzg:e}=t,n=t.to??(typeof t.blobs[0]=="string"?"hex":"bytes"),r=typeof t.blobs[0]=="string"?t.blobs.map(o=>nd(o)):t.blobs,s=typeof t.commitments[0]=="string"?t.commitments.map(o=>nd(o)):t.commitments,i=[];for(let o=0;oPo(o))}function HDe(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function qDe(t,e,n){return t&e^~t&n}function KDe(t,e,n){return t&e^t&n^e&n}class rue extends $P{constructor(e,n,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=BI(this.buffer)}update(e){ay(this),e=qh(e),jl(e);const{view:n,buffer:r,blockLen:s}=this,i=e.length;for(let o=0;os-o&&(this.process(r,0),o=0);for(let d=o;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d>>3,y=xu(p,17)^xu(p,19)^p>>>10;Fp[d]=y+Fp[d-7]+m+Fp[d-16]|0}let{A:r,B:s,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const f=xu(a,6)^xu(a,11)^xu(a,25),p=u+f+qDe(a,c,l)+GDe[d]+Fp[d]|0,y=(xu(r,2)^xu(r,13)^xu(r,22))+KDe(r,s,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=s,s=r,r=p+y|0}r=r+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,s,i,o,a,c,l,u)}roundClean(){lf(Fp)}destroy(){this.set(0,0,0,0,0,0,0,0),lf(this.buffer)}},jj=class extends WP{constructor(){super(28),this.A=Up[0]|0,this.B=Up[1]|0,this.C=Up[2]|0,this.D=Up[3]|0,this.E=Up[4]|0,this.F=Up[5]|0,this.G=Up[6]|0,this.H=Up[7]|0}};const sue=Wce(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),ZDe=sue[0],YDe=sue[1],jp=new Uint32Array(80),zp=new Uint32Array(80);class qS extends rue{constructor(e=64){super(128,e,16,!1),this.Ah=oo[0]|0,this.Al=oo[1]|0,this.Bh=oo[2]|0,this.Bl=oo[3]|0,this.Ch=oo[4]|0,this.Cl=oo[5]|0,this.Dh=oo[6]|0,this.Dl=oo[7]|0,this.Eh=oo[8]|0,this.El=oo[9]|0,this.Fh=oo[10]|0,this.Fl=oo[11]|0,this.Gh=oo[12]|0,this.Gl=oo[13]|0,this.Hh=oo[14]|0,this.Hl=oo[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:s,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:p,Gl:m,Hh:y,Hl:b}=this;return[e,n,r,s,i,o,a,c,l,u,d,f,p,m,y,b]}set(e,n,r,s,i,o,a,c,l,u,d,f,p,m,y,b){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=p|0,this.Gl=m|0,this.Hh=y|0,this.Hl=b|0}process(e,n){for(let E=0;E<16;E++,n+=4)jp[E]=e.getUint32(n),zp[E]=e.getUint32(n+=4);for(let E=16;E<80;E++){const A=jp[E-15]|0,_=zp[E-15]|0,k=jw(A,_,1)^jw(A,_,8)^vY(A,_,7),B=zw(A,_,1)^zw(A,_,8)^xY(A,_,7),W=jp[E-2]|0,S=zp[E-2]|0,$=jw(W,S,19)^aA(W,S,61)^vY(W,S,6),R=zw(W,S,19)^cA(W,S,61)^xY(W,S,6),M=_Re(B,R,zp[E-7],zp[E-16]),j=SRe(M,k,$,jp[E-7],jp[E-16]);jp[E]=j|0,zp[E]=M|0}let{Ah:r,Al:s,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:p,Fl:m,Gh:y,Gl:b,Hh:v,Hl:x}=this;for(let E=0;E<80;E++){const A=jw(d,f,14)^jw(d,f,18)^aA(d,f,41),_=zw(d,f,14)^zw(d,f,18)^cA(d,f,41),k=d&p^~d&y,B=f&m^~f&b,W=ARe(x,_,B,YDe[E],zp[E]),S=IRe(W,v,A,k,ZDe[E],jp[E]),$=W|0,R=jw(r,s,28)^aA(r,s,34)^aA(r,s,39),M=zw(r,s,28)^cA(r,s,34)^cA(r,s,39),j=r&i^r&a^i&a,z=s&o^s&c^o&c;v=y|0,x=b|0,y=p|0,b=m|0,p=d|0,m=f|0,{h:d,l:f}=Wf(l|0,u|0,S|0,$|0),l=a|0,u=c|0,a=i|0,c=o|0,i=r|0,o=s|0;const N=ERe($,M,z);r=CRe(N,S,R,j),s=N|0}({h:r,l:s}=Wf(this.Ah|0,this.Al|0,r|0,s|0)),{h:i,l:o}=Wf(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Wf(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Wf(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=Wf(this.Eh|0,this.El|0,d|0,f|0),{h:p,l:m}=Wf(this.Fh|0,this.Fl|0,p|0,m|0),{h:y,l:b}=Wf(this.Gh|0,this.Gl|0,y|0,b|0),{h:v,l:x}=Wf(this.Hh|0,this.Hl|0,v|0,x|0),this.set(r,s,i,o,a,c,l,u,d,f,p,m,y,b,v,x)}roundClean(){lf(jp,zp)}destroy(){lf(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class iue extends qS{constructor(){super(48),this.Ah=io[0]|0,this.Al=io[1]|0,this.Bh=io[2]|0,this.Bl=io[3]|0,this.Ch=io[4]|0,this.Cl=io[5]|0,this.Dh=io[6]|0,this.Dl=io[7]|0,this.Eh=io[8]|0,this.El=io[9]|0,this.Fh=io[10]|0,this.Fl=io[11]|0,this.Gh=io[12]|0,this.Gl=io[13]|0,this.Hh=io[14]|0,this.Hl=io[15]|0}}const ao=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),co=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class oue extends qS{constructor(){super(28),this.Ah=ao[0]|0,this.Al=ao[1]|0,this.Bh=ao[2]|0,this.Bl=ao[3]|0,this.Ch=ao[4]|0,this.Cl=ao[5]|0,this.Dh=ao[6]|0,this.Dl=ao[7]|0,this.Eh=ao[8]|0,this.El=ao[9]|0,this.Fh=ao[10]|0,this.Fl=ao[11]|0,this.Gh=ao[12]|0,this.Gl=ao[13]|0,this.Hh=ao[14]|0,this.Hl=ao[15]|0}}class aue extends qS{constructor(){super(32),this.Ah=co[0]|0,this.Al=co[1]|0,this.Bh=co[2]|0,this.Bl=co[3]|0,this.Ch=co[4]|0,this.Cl=co[5]|0,this.Dh=co[6]|0,this.Dl=co[7]|0,this.Eh=co[8]|0,this.El=co[9]|0,this.Fh=co[10]|0,this.Fl=co[11]|0,this.Gh=co[12]|0,this.Gl=co[13]|0,this.Hh=co[14]|0,this.Hl=co[15]|0}}const VP=gp(()=>new WP),cue=gp(()=>new jj),zj=gp(()=>new qS),XDe=gp(()=>new iue),QDe=gp(()=>new aue),JDe=gp(()=>new oue),e9e=Object.freeze(Object.defineProperty({__proto__:null,SHA224:jj,SHA256:WP,SHA384:iue,SHA512:qS,SHA512_224:oue,SHA512_256:aue,sha224:cue,sha256:VP,sha384:XDe,sha512:zj,sha512_224:JDe,sha512_256:QDe},Symbol.toStringTag,{value:"Module"})),t9e=WP,Th=VP,n9e=jj,r9e=cue,s9e=Object.freeze(Object.defineProperty({__proto__:null,SHA224:n9e,SHA256:t9e,sha224:r9e,sha256:Th},Symbol.toStringTag,{value:"Module"}));function i9e(t,e){return Th(Hh(t,{strict:!1})?RP(t):t)}function o9e(t){const{commitment:e,version:n=1}=t,r=t.to??(typeof e=="string"?"hex":"bytes"),s=i9e(e);return s.set([n],0),r==="bytes"?s:Po(s)}function a9e(t){const{commitments:e,version:n}=t,r=t.to??(typeof e[0]=="string"?"hex":"bytes"),s=[];for(const i of e)s.push(o9e({commitment:i,to:r,version:n}));return s}const FY=6,lue=32,Wj=4096,uue=lue*Wj,jY=uue*FY-1-1*Wj*FY;class c9e extends ot{constructor({maxSize:e,size:n}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${n} bytes`],name:"BlobSizeTooLargeError"})}}class l9e extends ot{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}function u9e(t){const e=t.to??(typeof t.data=="string"?"hex":"bytes"),n=typeof t.data=="string"?nd(t.data):t.data,r=Hs(n);if(!r)throw new l9e;if(r>jY)throw new c9e({maxSize:jY,size:r});const s=[];let i=!0,o=0;for(;i;){const a=wj(new Uint8Array(uue));let c=0;for(;ca.bytes):s.map(a=>Po(a.bytes))}function d9e(t){const{data:e,kzg:n,to:r}=t,s=t.blobs??u9e({data:e,to:r}),i=t.commitments??tue({blobs:s,kzg:n,to:r}),o=t.proofs??nue({blobs:s,commitments:i,kzg:n,to:r}),a=[];for(let c=0;c"u"&&d)if(c){const v=await b();f.nonce=await c.consume({address:d.address,chainId:v,client:t})}else f.nonce=await $r(t,VDe,"getTransactionCount")({address:d.address,blockTag:"pending"});if((l.includes("blobVersionedHashes")||l.includes("sidecars"))&&r&&o){const v=tue({blobs:r,kzg:o});if(l.includes("blobVersionedHashes")){const x=a9e({commitments:v,to:"hex"});f.blobVersionedHashes=x}if(l.includes("sidecars")){const x=nue({blobs:r,commitments:v,kzg:o}),E=d9e({blobs:r,commitments:v,proofs:x,to:"hex"});f.sidecars=E}}if(l.includes("chainId")&&(f.chainId=await b()),(l.includes("fees")||l.includes("type"))&&typeof u>"u")try{f.type=f9e(f)}catch{let v=zY.get(t.uid);typeof v>"u"&&(v=typeof(await m())?.baseFeePerGas=="bigint",zY.set(t.uid,v)),f.type=v?"eip1559":"legacy"}if(l.includes("fees"))if(f.type!=="legacy"&&f.type!=="eip2930"){if(typeof f.maxFeePerGas>"u"||typeof f.maxPriorityFeePerGas>"u"){const v=await m(),{maxFeePerGas:x,maxPriorityFeePerGas:E}=await $L(t,{block:v,chain:s,request:f});if(typeof e.maxPriorityFeePerGas>"u"&&e.maxFeePerGas&&e.maxFeePerGas"u"){const v=await m(),{gasPrice:x}=await $L(t,{block:v,chain:s,request:f,type:"legacy"});f.gasPrice=x}}return l.includes("gas")&&typeof i>"u"&&(f.gas=await $r(t,pue,"estimateGas")({...f,account:d&&{address:d.address,type:"json-rpc"}})),zP(f),delete f.parameters,f}async function hue(t,{address:e,blockNumber:n,blockTag:r=t.experimental_blockTag??"latest"}){const s=typeof n=="bigint"?$n(n):void 0,i=await t.request({method:"eth_getBalance",params:[e,s||r]});return BigInt(i)}async function pue(t,e){const{account:n=t.account}=e,r=n?Cf(n):void 0;try{let R=function(j){const{block:z,request:N,rpcStateOverride:T}=j;return t.request({method:"eth_estimateGas",params:T?[N,z??t.experimental_blockTag??"latest",T]:z?[N,z]:[N]})};const{accessList:s,authorizationList:i,blobs:o,blobVersionedHashes:a,blockNumber:c,blockTag:l,data:u,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:y,nonce:b,value:v,stateOverride:x,...E}=await Vj(t,{...e,parameters:r?.type==="local"?void 0:["blobVersionedHashes"]}),_=(typeof c=="bigint"?$n(c):void 0)||l,k=Hle(x),B=await(async()=>{if(E.to)return E.to;if(i&&i.length>0)return await Uj({authorization:i[0]}).catch(()=>{throw new ot("`to` is required. Could not infer from `authorizationList`")})})();zP(e);const W=t.chain?.formatters?.transactionRequest?.format,$=(W||Lj)({...Mj(E,{format:W}),from:r?.address,accessList:s,authorizationList:i,blobs:o,blobVersionedHashes:a,data:u,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:y,nonce:b,to:B,value:v});let M=BigInt(await R({block:_,request:$,rpcStateOverride:k}));if(i){const j=await hue(t,{address:$.from}),z=await Promise.all(i.map(async N=>{const{address:T}=N,U=await R({block:_,request:{authorizationList:void 0,data:u,from:r?.address,to:T,value:$n(j)},rpcStateOverride:k}).catch(()=>100000n);return 2n*BigInt(U)}));M+=z.reduce((N,T)=>N+T,0n)}return M}catch(s){throw UDe(s,{...e,account:r,chain:t.chain})}}const h9e=new Map,p9e=new Map;function g9e(t){const e=(s,i)=>({clear:()=>i.delete(s),get:()=>i.get(s),set:o=>i.set(s,o)}),n=e(t,h9e),r=e(t,p9e);return{clear:()=>{n.clear(),r.clear()},promise:n,response:r}}async function m9e(t,{cacheKey:e,cacheTime:n=Number.POSITIVE_INFINITY}){const r=g9e(e),s=r.response.get();if(s&&n>0&&Date.now()-s.created.getTime()`blockNumber.${t}`;async function w9e(t,{cacheTime:e=t.cacheTime}={}){const n=await m9e(()=>t.request({method:"eth_blockNumber"}),{cacheKey:y9e(t.uid),cacheTime:e});return BigInt(n)}async function b9e(t,{address:e,blockNumber:n,blockTag:r="latest"}){const s=n!==void 0?$n(n):void 0,i=await t.request({method:"eth_getCode",params:[e,s||r]},{dedupe:!!s});if(i!=="0x")return i}function Hj(t,e){if(!uf(t,{strict:!1}))throw new iy({address:t});if(!uf(e,{strict:!1}))throw new iy({address:e});return t.toLowerCase()===e.toLowerCase()}const WY="/docs/contract/decodeEventLog";function v9e(t){const{abi:e,data:n,strict:r,topics:s}=t,i=r??!0,[o,...a]=s;if(!o)throw new tRe({docsPath:WY});const c=e.find(y=>y.type==="event"&&o===Ej(cf(y)));if(!(c&&"name"in c)||c.type!=="event")throw new Oce(o,{docsPath:WY});const{name:l,inputs:u}=c,d=u?.some(y=>!("name"in y&&y.name)),f=d?[]:{},p=u.map((y,b)=>[y,b]).filter(([y])=>"indexed"in y&&y.indexed);for(let y=0;y!("indexed"in y&&y.indexed));if(m.length>0){if(n&&n!=="0x")try{const y=BS(m,n);if(y)if(d)for(let b=0;b0?f:void 0}}function x9e({param:t,value:e}){return t.type==="string"||t.type==="bytes"||t.type==="tuple"||t.type.match(/^(.*)\[(\d+)?\]$/)?e:(BS([t],e)||[])[0]}function E9e(t){const{abi:e,args:n,logs:r,strict:s=!0}=t,i=(()=>{if(t.eventName)return Array.isArray(t.eventName)?t.eventName:[t.eventName]})();return r.map(o=>{try{const a=e.find(l=>l.type==="event"&&o.topics[0]===Ej(l));if(!a)return null;const c=v9e({...o,abi:[a],strict:s});return i&&!i.includes(c.eventName)||!C9e({args:c.args,inputs:a.inputs,matchArgs:n})?null:{...c,...o}}catch(a){let c,l;if(a instanceof Oce)return null;if(a instanceof gL||a instanceof Dce){if(s)return null;c=a.abiItem.name,l=a.abiItem.inputs?.some(u=>!("name"in u&&u.name))}return{...o,args:l?[]:{},eventName:c}}}).filter(Boolean)}function C9e(t){const{args:e,inputs:n,matchArgs:r}=t;if(!r)return!0;if(!e)return!1;function s(i,o,a){try{return i.type==="address"?Hj(o,a):i.type==="string"||i.type==="bytes"?X1(RP(o))===a:o===a}catch{return!1}}return Array.isArray(e)&&Array.isArray(r)?r.every((i,o)=>{if(i==null)return!0;const a=n[o];return a?(Array.isArray(i)?i:[i]).some(l=>s(a,l,e[o])):!1}):typeof e=="object"&&!Array.isArray(e)&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).every(([i,o])=>{if(o==null)return!0;const a=n.find(l=>l.name===i);return a?(Array.isArray(o)?o:[o]).some(l=>s(a,l,e[i])):!1}):!1}function gue(t,{args:e,eventName:n}={}){return{...t,blockHash:t.blockHash?t.blockHash:null,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,logIndex:t.logIndex?Number(t.logIndex):null,transactionHash:t.transactionHash?t.transactionHash:null,transactionIndex:t.transactionIndex?Number(t.transactionIndex):null,...n?{args:e,eventName:n}:{}}}async function _9e(t,{filter:e}){const n="strict"in e&&e.strict,r=await e.request({method:"eth_getFilterChanges",params:[e.id]});if(typeof r[0]=="string")return r;const s=r.map(i=>gue(i));return!("abi"in e)||!e.abi?s:E9e({abi:e.abi,logs:s,strict:n})}async function S9e({address:t,authorization:e,signature:n}){return Hj(wh(t),await Uj({authorization:e,signature:n}))}const uA=new DP(8192);function A9e(t,{enabled:e=!0,id:n}){if(!e||!n)return t();if(uA.get(n))return uA.get(n);const r=t().finally(()=>uA.delete(n));return uA.set(n,r),r}async function cT(t){return new Promise(e=>setTimeout(e,t))}function lT(t,{delay:e=100,retryCount:n=2,shouldRetry:r=()=>!0}={}){return new Promise((s,i)=>{const o=async({count:a=0}={})=>{const c=async({error:l})=>{const u=typeof e=="function"?e({count:a,error:l}):e;u&&await cT(u),o({count:a+1})};try{const l=await t();s(l)}catch(l){if(a{const{dedupe:s=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...r},{method:l}=n;if(i?.exclude?.includes(l))throw new ym(new Error("method not supported"),{method:l});if(i?.include&&!i.include.includes(l))throw new ym(new Error("method not supported"),{method:l});const u=s?$v(`${c}.${Dl(n)}`):void 0;return A9e(()=>lT(async()=>{try{return await t(n)}catch(d){const f=d;switch(f.code){case wC.code:throw new wC(f);case bC.code:throw new bC(f);case vC.code:throw new vC(f,{method:n.method});case xC.code:throw new xC(f);case uy.code:throw new uy(f);case EC.code:throw new EC(f);case CC.code:throw new CC(f);case Zg.code:throw new Zg(f);case Lv.code:throw new Lv(f);case ym.code:throw new ym(f,{method:n.method});case Bv.code:throw new Bv(f);case _C.code:throw new _C(f);case ti.code:throw new ti(f);case SC.code:throw new SC(f);case AC.code:throw new AC(f);case IC.code:throw new IC(f);case TC.code:throw new TC(f);case df.code:throw new df(f);case NC.code:throw new NC(f);case PC.code:throw new PC(f);case kC.code:throw new kC(f);case RC.code:throw new RC(f);case OC.code:throw new OC(f);case $C.code:throw new $C(f);case DC.code:throw new DC(f);case 5e3:throw new ti(f);default:throw d instanceof ot?d:new M$e(f)}}},{delay:({count:d,error:f})=>{if(f&&f instanceof mE){const p=f?.headers?.get("Retry-After");if(p?.match(/\d/))return Number.parseInt(p,10)*1e3}return~~(1<T9e(d)}),{enabled:s,id:u})}}function T9e(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===Bv.code||t.code===uy.code:t instanceof mE&&t.status?t.status===403||t.status===408||t.status===413||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function N9e({chain:t,currentChainId:e}){if(!t)throw new h$e;if(e!==t.id)throw new f$e({chain:t,currentChainId:e})}function P9e(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}function k9e(t,{docsPath:e,...n}){const r=(()=>{const s=Dj(t,n);return s instanceof jP?t:s})();return new S$e(r,{docsPath:e,...n})}const R9e={"0x0":"reverted","0x1":"success"};function O9e(t){const e={...t,blockNumber:t.blockNumber?BigInt(t.blockNumber):null,contractAddress:t.contractAddress?t.contractAddress:null,cumulativeGasUsed:t.cumulativeGasUsed?BigInt(t.cumulativeGasUsed):null,effectiveGasPrice:t.effectiveGasPrice?BigInt(t.effectiveGasPrice):null,gasUsed:t.gasUsed?BigInt(t.gasUsed):null,logs:t.logs?t.logs.map(n=>gue(n)):null,to:t.to?t.to:null,transactionIndex:t.transactionIndex?oy(t.transactionIndex):null,status:t.status?R9e[t.status]:null,type:t.type?Xle[t.type]||t.type:null};return t.blobGasPrice&&(e.blobGasPrice=BigInt(t.blobGasPrice)),t.blobGasUsed&&(e.blobGasUsed=BigInt(t.blobGasUsed)),e}function mue(t,{errorInstance:e=new Error("timed out"),timeout:n,signal:r}){return new Promise((s,i)=>{(async()=>{let o;try{const a=new AbortController;n>0&&(o=setTimeout(()=>{r?a.abort():i(e)},n)),s(await t({signal:a?.signal||null}))}catch(a){a?.name==="AbortError"&&i(e),i(a)}finally{clearTimeout(o)}})()})}function $9e(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const VY=$9e();function D9e(t,e={}){return{async request(n){const{body:r,fetchFn:s=e.fetchFn??fetch,onRequest:i=e.onRequest,onResponse:o=e.onResponse,timeout:a=e.timeout??1e4}=n,c={...e.fetchOptions??{},...n.fetchOptions??{}},{headers:l,method:u,signal:d}=c;try{const f=await mue(async({signal:m})=>{const y={...c,body:Array.isArray(r)?Dl(r.map(E=>({jsonrpc:"2.0",id:E.id??VY.take(),...E}))):Dl({jsonrpc:"2.0",id:r.id??VY.take(),...r}),headers:{"Content-Type":"application/json",...l},method:u||"POST",signal:d||(a>0?m:null)},b=new Request(t,y),v=await i?.(b,y)??{...y,url:t};return await s(v.url??t,v)},{errorInstance:new kY({body:r,url:t}),timeout:a,signal:!0});o&&await o(f);let p;if(f.headers.get("Content-Type")?.startsWith("application/json"))p=await f.json();else{p=await f.text();try{p=JSON.parse(p||"{}")}catch(m){if(f.ok)throw m;p={error:p}}}if(!f.ok)throw new mE({body:r,details:Dl(p.error)||f.statusText,headers:f.headers,status:f.status,url:t});return p}catch(f){throw f instanceof mE||f instanceof kY?f:new mE({body:r,cause:f,url:t})}}}}const M9e=`Ethereum Signed Message: +`;function L9e(t){const e=typeof t=="string"?$v(t):typeof t.raw=="string"?t.raw:Po(t.raw),n=$v(`${M9e}${Hs(e)}`);return cy([n,e])}function B9e(t,e){return X1(L9e(t),e)}const U9e="1.0.9";let nc=class DL extends Error{constructor(e,n={}){const r=n.cause instanceof DL?n.cause.details:n.cause?.message?n.cause.message:n.details,s=n.cause instanceof DL&&n.cause.docsPath||n.docsPath,i=[e||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: https://abitype.dev${s}`]:[],...r?[`Details: ${r}`]:[],`Version: abitype@${U9e}`].join(` +`);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),n.cause&&(this.cause=n.cause),this.details=r,this.docsPath=s,this.metaMessages=n.metaMessages,this.shortMessage=e}};function yp(t,e){return t.exec(e)?.groups}const yue=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,wue=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,bue=/^\(.+?\).*?$/,HY=/^tuple(?(\[(\d*)\])*)$/;function ML(t){let e=t.type;if(HY.test(t.type)&&"components"in t){e="(";const n=t.components.length;for(let s=0;s[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;function j9e(t){return vue.test(t)}function z9e(t){return yp(vue,t)}const xue=/^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;function W9e(t){return xue.test(t)}function V9e(t){return yp(xue,t)}const Eue=/^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/;function H9e(t){return Eue.test(t)}function q9e(t){return yp(Eue,t)}const Cue=/^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/;function _ue(t){return Cue.test(t)}function K9e(t){return yp(Cue,t)}const Sue=/^constructor\((?.*?)\)(?:\s(?payable{1}))?$/;function G9e(t){return Sue.test(t)}function Z9e(t){return yp(Sue,t)}const Aue=/^fallback\(\) external(?:\s(?payable{1}))?$/;function Y9e(t){return Aue.test(t)}function X9e(t){return yp(Aue,t)}const Q9e=/^receive\(\) external payable$/;function J9e(t){return Q9e.test(t)}const qY=new Set(["memory","indexed","storage","calldata"]),eMe=new Set(["indexed"]),LL=new Set(["calldata","memory","storage"]);class Gkt extends nc{constructor({signature:e}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class tMe extends nc{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class nMe extends nc{constructor({type:e}){super("Unknown type.",{metaMessages:[`Type "${e}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class rMe extends nc{constructor({params:e}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(e,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}}class sMe extends nc{constructor({param:e}){super("Invalid ABI parameter.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class iMe extends nc{constructor({param:e,name:n}){super("Invalid ABI parameter.",{details:e,metaMessages:[`"${n}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}}class oMe extends nc{constructor({param:e,type:n,modifier:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${r}" not allowed${n?` in "${n}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class aMe extends nc{constructor({param:e,type:n,modifier:r}){super("Invalid ABI parameter.",{details:e,metaMessages:[`Modifier "${r}" not allowed${n?` in "${n}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${r}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}}class cMe extends nc{constructor({abiParameter:e}){super("Invalid ABI parameter.",{details:JSON.stringify(e,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}let nx=class extends nc{constructor({signature:e,type:n}){super(`Invalid ${n} signature.`,{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}};class lMe extends nc{constructor({signature:e}){super("Unknown signature.",{details:e}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class uMe extends nc{constructor({signature:e}){super("Invalid struct signature.",{details:e,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class dMe extends nc{constructor({type:e}){super("Circular reference detected.",{metaMessages:[`Struct "${e}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class fMe extends nc{constructor({current:e,depth:n}){super("Unbalanced parentheses.",{metaMessages:[`"${e.trim()}" has too many ${n>0?"opening":"closing"} parentheses.`],details:`Depth "${n}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}function hMe(t,e,n){let r="";if(n)for(const s of Object.entries(n)){if(!s)continue;let i="";for(const o of s[1])i+=`[${o.type}${o.name?`:${o.name}`:""}]`;r+=`(${s[0]}{${i}})`}return e?`${e}:${t}${r}`:t}const r$=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]]);function Ykt(t,e={}){if(H9e(t))return pMe(t,e);if(W9e(t))return gMe(t,e);if(j9e(t))return mMe(t,e);if(G9e(t))return yMe(t,e);if(Y9e(t))return wMe(t);if(J9e(t))return{type:"receive",stateMutability:"payable"};throw new lMe({signature:t})}function pMe(t,e={}){const n=q9e(t);if(!n)throw new nx({signature:t,type:"function"});const r=Rc(n.parameters),s=[],i=r.length;for(let a=0;a[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,vMe=/^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,xMe=/^u?int$/;function Gh(t,e){const n=hMe(t,e?.type,e?.structs);if(r$.has(n))return r$.get(n);const r=bue.test(t),s=yp(r?vMe:bMe,t);if(!s)throw new sMe({param:t});if(s.name&&CMe(s.name))throw new iMe({param:t,name:s.name});const i=s.name?{name:s.name}:{},o=s.modifier==="indexed"?{indexed:!0}:{},a=e?.structs??{};let c,l={};if(r){c="tuple";const d=Rc(s.type),f=[],p=d.length;for(let m=0;m[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/;function Tue(t,e,n=new Set){const r=[],s=t.length;for(let i=0;ithis.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}};const TMe={checksum:new IMe(8192)},s$=TMe.checksum;function NMe(t,e={}){const{as:n=typeof t=="string"?"Hex":"Bytes"}=e,r=yj(Y$e(t));return n==="Bytes"?r:rd(r)}const PMe=/^0x[a-fA-F0-9]{40}$/;function HP(t,e={}){const{strict:n=!0}=e;if(!PMe.test(t))throw new GY({address:t,cause:new kMe});if(n){if(t.toLowerCase()===t)return;if(Nue(t)!==t)throw new GY({address:t,cause:new RMe})}}function Nue(t){if(s$.has(t))return s$.get(t);HP(t,{strict:!1});const e=t.substring(2).toLowerCase(),n=NMe(Q$e(e),{as:"Bytes"}),r=e.split("");for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&r[i]&&(r[i]=r[i].toUpperCase()),(n[i>>1]&15)>=8&&r[i+1]&&(r[i+1]=r[i+1].toUpperCase());const s=`0x${r.join("")}`;return s$.set(t,s),s}function Qkt(t,e={}){const{strict:n=!0}=e??{};try{return HP(t,{strict:n}),!0}catch{return!1}}class GY extends vr{constructor({address:e,cause:n}){super(`Address "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class kMe extends vr{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class RMe extends vr{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const OMe=/^(.*)\[([0-9]*)\]$/,$Me=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Pue=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,ZY=2n**256n-1n;function av(t,e,n){const{checksumAddress:r,staticPosition:s}=n,i=Gj(e.type);if(i){const[o,a]=i;return MMe(t,{...e,type:a},{checksumAddress:r,length:o,staticPosition:s})}if(e.type==="tuple")return FMe(t,e,{checksumAddress:r,staticPosition:s});if(e.type==="address")return DMe(t,{checksum:r});if(e.type==="bool")return LMe(t);if(e.type.startsWith("bytes"))return BMe(t,e,{staticPosition:s});if(e.type.startsWith("uint")||e.type.startsWith("int"))return UMe(t,e);if(e.type==="string")return jMe(t,{staticPosition:s});throw new Zj(e.type)}const YY=32,BL=32;function DMe(t,e={}){const{checksum:n=!1}=e,r=t.readBytes(32);return[(i=>n?Nue(i):i)(rd(eDe(r,-20))),32]}function MMe(t,e,n){const{checksumAddress:r,length:s,staticPosition:i}=n;if(!s){const c=Ih(t.readBytes(BL)),l=i+c,u=l+YY;t.setPosition(l);const d=Ih(t.readBytes(YY)),f=UC(e);let p=0;const m=[];for(let y=0;y48?tDe(s,{signed:n}):Ih(s,{signed:n}),32]}function FMe(t,e,n){const{checksumAddress:r,staticPosition:s}=n,i=e.components.length===0||e.components.some(({name:c})=>!c),o=i?[]:{};let a=0;if(UC(e)){const c=Ih(t.readBytes(BL)),l=s+c;for(let u=0;u0?Kh(l,c):l}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Kh(...a.map(({encoded:c})=>c))}}function HMe(t,{type:e}){const[,n]=e.split("bytes"),r=Fc(t);if(!n){let s=t;return r%32!==0&&(s=fy(s,Math.ceil((t.length-2)/2/32)*32)),{dynamic:!0,encoded:Kh(dy(Zo(r,{size:32})),s)}}if(r!==Number.parseInt(n,10))throw new Rue({expectedSize:Number.parseInt(n,10),value:t});return{dynamic:!1,encoded:fy(t)}}function qMe(t){if(typeof t!="boolean")throw new vr(`Invalid boolean value: "${t}" (type: ${typeof t}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:dy(Lle(t))}}function KMe(t,{signed:e,size:n}){if(typeof n=="number"){const r=2n**(BigInt(n)-(e?1n:0n))-1n,s=e?-r-1n:0n;if(t>r||to))}}function Gj(t){const e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function UC(t){const{type:e}=t;if(e==="string"||e==="bytes"||e.endsWith("[]"))return!0;if(e==="tuple")return t.components?.some(UC);const n=Gj(t.type);return!!(n&&UC({...t,type:n[1]}))}const YMe={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new JMe({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(t){if(t<0||t>this.bytes.length-1)throw new QMe({length:this.bytes.length,position:t})},decrementPosition(t){if(t<0)throw new XY({offset:t});const e=this.position-t;this.assertPosition(e),this.position=e},getReadCount(t){return this.positionReadCount.get(t||this.position)||0},incrementPosition(t){if(t<0)throw new XY({offset:t});const e=this.position+t;this.assertPosition(e),this.position=e},inspectByte(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectBytes(t,e){const n=e??this.position;return this.assertPosition(n+t-1),this.bytes.subarray(n,n+t)},inspectUint8(t){const e=t??this.position;return this.assertPosition(e),this.bytes[e]},inspectUint16(t){const e=t??this.position;return this.assertPosition(e+1),this.dataView.getUint16(e)},inspectUint24(t){const e=t??this.position;return this.assertPosition(e+2),(this.dataView.getUint16(e)<<8)+this.dataView.getUint8(e+2)},inspectUint32(t){const e=t??this.position;return this.assertPosition(e+3),this.dataView.getUint32(e)},pushByte(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushBytes(t){this.assertPosition(this.position+t.length-1),this.bytes.set(t,this.position),this.position+=t.length},pushUint8(t){this.assertPosition(this.position),this.bytes[this.position]=t,this.position++},pushUint16(t){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,t),this.position+=2},pushUint24(t){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,t>>8),this.dataView.setUint8(this.position+2,t&255),this.position+=3},pushUint32(t){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,t),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const t=this.inspectByte();return this.position++,t},readBytes(t,e){this.assertReadLimit(),this._touch();const n=this.inspectBytes(t);return this.position+=e??t,n},readUint8(){this.assertReadLimit(),this._touch();const t=this.inspectUint8();return this.position+=1,t},readUint16(){this.assertReadLimit(),this._touch();const t=this.inspectUint16();return this.position+=2,t},readUint24(){this.assertReadLimit(),this._touch();const t=this.inspectUint24();return this.position+=3,t},readUint32(){this.assertReadLimit(),this._touch();const t=this.inspectUint32();return this.position+=4,t},get remaining(){return this.bytes.length-this.position},setPosition(t){const e=this.position;return this.assertPosition(t),this.position=t,()=>this.position=e},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const t=this.getReadCount();this.positionReadCount.set(this.position,t+1),t>0&&this.recursiveReadCount++}};function XMe(t,{recursiveReadLimit:e=8192}={}){const n=Object.create(YMe);return n.bytes=t,n.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=e,n}class XY extends vr{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class QMe extends vr{constructor({length:e,position:n}){super(`Position \`${n}\` is out of bounds (\`0 < position < ${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class JMe extends vr{constructor({count:e,limit:n}){super(`Recursive read limit of \`${n}\` exceeded (recursive read count: \`${e}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function eLe(t,e,n={}){const{as:r="Array",checksumAddress:s=!1}=n,i=typeof e=="string"?Dle(e):e,o=XMe(i);if(Bb(i)===0&&t.length>0)throw new rLe;if(Bb(i)&&Bb(i)<32)throw new nLe({data:typeof e=="string"?e:rd(e),parameters:t,size:Bb(i)});let a=0;const c=r==="Array"?[]:{};for(let l=0;ls?e.create().update(r).digest():r);for(let o=0;onew Yj(t,e).update(n).digest();KS.create=(t,e)=>new Yj(t,e);const oLe=Object.freeze(Object.defineProperty({__proto__:null,HMAC:Yj,hmac:KS},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ja=BigInt(0),ta=BigInt(1),bm=BigInt(2),aLe=BigInt(3),$ue=BigInt(4),Due=BigInt(5),Mue=BigInt(8);function Pa(t,e){const n=t%e;return n>=ja?n:e+n}function cl(t,e,n){let r=t;for(;e-- >ja;)r*=r,r%=n;return r}function FL(t,e){if(t===ja)throw new Error("invert: expected non-zero number");if(e<=ja)throw new Error("invert: expected positive modulus, got "+e);let n=Pa(t,e),r=e,s=ja,i=ta;for(;n!==ja;){const a=r/n,c=r%n,l=s-i*a;r=n,n=c,s=i,i=l}if(r!==ta)throw new Error("invert: does not exist");return Pa(s,e)}function Lue(t,e){const n=(t.ORDER+ta)/$ue,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function cLe(t,e){const n=(t.ORDER-Due)/Mue,r=t.mul(e,bm),s=t.pow(r,n),i=t.mul(e,s),o=t.mul(t.mul(i,bm),s),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function lLe(t){if(t1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Lue;let i=s.pow(r,e);const o=(e+ta)/bm;return function(c,l){if(c.is0(l))return l;if(QY(c,l)!==1)throw new Error("Cannot find square root");let u=n,d=c.mul(c.ONE,i),f=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let m=1,y=c.sqr(f);for(;!c.eql(y,c.ONE);)if(m++,y=c.sqr(y),m===u)throw new Error("Cannot find square root");const b=ta<(r[s]="function",r),e);return UP(t,n)}function hLe(t,e,n){if(nja;)n&ta&&(r=t.mul(r,s)),s=t.sqr(s),n>>=ta;return r}function Bue(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),i),r}function QY(t,e){const n=(t.ORDER-ta)/bm,r=t.pow(e,n),s=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Uue(t,e){e!==void 0&&u0(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Xj(t,e,n=!1,r={}){if(t<=ja)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=Uue(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:s,BYTES:i,MASK:BP(s),ZERO:ja,ONE:ta,create:c=>Pa(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ja<=c&&cc===ja,isOdd:c=>(c&ta)===ta,neg:c=>Pa(-c,t),eql:(c,l)=>c===l,sqr:c=>Pa(c*c,t),add:(c,l)=>Pa(c+l,t),sub:(c,l)=>Pa(c-l,t),mul:(c,l)=>Pa(c*l,t),pow:(c,l)=>hLe(a,c,l),div:(c,l)=>Pa(c*FL(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>FL(c,t),sqrt:r.sqrt||(c=>(o||(o=uLe(t)),o(a,c))),toBytes:c=>n?Ple(c,i):WS(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return n?Nle(c):Wm(c)},invertBatch:c=>Bue(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function Fue(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function jue(t){const e=Fue(t);return e+Math.ceil(e/2)}function pLe(t,e,n=!1){const r=t.length,s=Fue(e),i=jue(e);if(r<16||r1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const o=n?Nle(t):Wm(t),a=Pa(o,e-ta)+ta;return n?Ple(a,s):WS(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const JY=BigInt(0),jL=BigInt(1);function i$(t,e){const n=e.negate();return t?n:e}function zue(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function o$(t,e){zue(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,i=BP(t),o=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function eX(t,e,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=n;let a=Number(t&s),c=t>>o;a>r&&(a-=i,c+=jL);const l=e*r,u=l+Math.abs(a)-1,d=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function gLe(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function mLe(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const a$=new WeakMap,Wue=new WeakMap;function c$(t){return Wue.get(t)||1}function yLe(t,e){return{constTimeNegate:i$,hasPrecomputes(n){return c$(n)!==1},unsafeLadder(n,r,s=t.ZERO){let i=n;for(;r>JY;)r&jL&&(s=s.add(i)),i=i.double(),r>>=jL;return s},precomputeWindow(n,r){const{windows:s,windowSize:i}=o$(r,e),o=[];let a=n,c=a;for(let l=0;l12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=BP(c),u=new Array(Number(l)+1).fill(o),d=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=d;p>=0;p-=c){u.fill(o);for(let y=0;y>BigInt(p)&l);u[v]=u[v].add(n[y])}let m=o;for(let y=u.length-1,b=o;y>0;y--)b=b.add(u[y]),m=m.add(b);if(f=f.add(m),p!==0)for(let y=0;y{const{Err:n}=dh;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,s=lA(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?lA(s.length/2|128):"";return lA(t)+i+s+e},decode(t,e){const{Err:n}=dh;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const s=e[r++],i=!!(s&128);let o=0;if(!i)o=s;else{const c=s&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=dh;if(t{const k=A.toAffine();return iT(Uint8Array.from([4]),n.toBytes(k.x),n.toBytes(k.y))}),i=e.fromBytes||(E=>{const A=E.subarray(1),_=n.fromBytes(A.subarray(0,n.BYTES)),k=n.fromBytes(A.subarray(n.BYTES,2*n.BYTES));return{x:_,y:k}});function o(E){const{a:A,b:_}=e,k=n.sqr(E),B=n.mul(k,E);return n.add(n.add(B,n.mul(E,A)),_)}function a(E,A){const _=n.sqr(A),k=o(E);return n.eql(_,k)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=n.mul(n.pow(e.a,u$),xLe),l=n.mul(n.sqr(e.b),BigInt(27));if(n.is0(n.add(c,l)))throw new Error("bad curve params: a or b");function u(E){return Rj(E,hi,e.n)}function d(E){const{allowedPrivateKeyLengths:A,nByteLength:_,wrapPrivateKey:k,n:B}=e;if(A&&typeof E!="bigint"){if(zS(E)&&(E=LC(E)),typeof E!="string"||!A.includes(E.length))throw new Error("invalid private key");E=E.padStart(_*2,"0")}let W;try{W=typeof E=="bigint"?E:Wm(gl("private key",E,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof E)}return k&&(W=Pa(W,B)),ov("private key",W,hi,B),W}function f(E){if(!(E instanceof y))throw new Error("ProjectivePoint expected")}const p=$Y((E,A)=>{const{px:_,py:k,pz:B}=E;if(n.eql(B,n.ONE))return{x:_,y:k};const W=E.is0();A==null&&(A=W?n.ONE:n.inv(B));const S=n.mul(_,A),$=n.mul(k,A),R=n.mul(B,A);if(W)return{x:n.ZERO,y:n.ZERO};if(!n.eql(R,n.ONE))throw new Error("invZ was invalid");return{x:S,y:$}}),m=$Y(E=>{if(E.is0()){if(e.allowInfinityPoint&&!n.is0(E.py))return;throw new Error("bad point: ZERO")}const{x:A,y:_}=E.toAffine();if(!n.isValid(A)||!n.isValid(_))throw new Error("bad point: x or y not FE");if(!a(A,_))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class y{constructor(A,_,k){if(A==null||!n.isValid(A))throw new Error("x required");if(_==null||!n.isValid(_)||n.is0(_))throw new Error("y required");if(k==null||!n.isValid(k))throw new Error("z required");this.px=A,this.py=_,this.pz=k,Object.freeze(this)}static fromAffine(A){const{x:_,y:k}=A||{};if(!A||!n.isValid(_)||!n.isValid(k))throw new Error("invalid affine point");if(A instanceof y)throw new Error("projective point not allowed");const B=W=>n.eql(W,n.ZERO);return B(_)&&B(k)?y.ZERO:new y(_,k,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(A){const _=Bue(n,A.map(k=>k.pz));return A.map((k,B)=>k.toAffine(_[B])).map(y.fromAffine)}static fromHex(A){const _=y.fromAffine(i(gl("pointHex",A)));return _.assertValidity(),_}static fromPrivateKey(A){return y.BASE.multiply(d(A))}static msm(A,_){return wLe(y,r,A,_)}_setWindowSize(A){x.setWindowSize(this,A)}assertValidity(){m(this)}hasEvenY(){const{y:A}=this.toAffine();if(n.isOdd)return!n.isOdd(A);throw new Error("Field doesn't support isOdd")}equals(A){f(A);const{px:_,py:k,pz:B}=this,{px:W,py:S,pz:$}=A,R=n.eql(n.mul(_,$),n.mul(W,B)),M=n.eql(n.mul(k,$),n.mul(S,B));return R&&M}negate(){return new y(this.px,n.neg(this.py),this.pz)}double(){const{a:A,b:_}=e,k=n.mul(_,u$),{px:B,py:W,pz:S}=this;let $=n.ZERO,R=n.ZERO,M=n.ZERO,j=n.mul(B,B),z=n.mul(W,W),N=n.mul(S,S),T=n.mul(B,W);return T=n.add(T,T),M=n.mul(B,S),M=n.add(M,M),$=n.mul(A,M),R=n.mul(k,N),R=n.add($,R),$=n.sub(z,R),R=n.add(z,R),R=n.mul($,R),$=n.mul(T,$),M=n.mul(k,M),N=n.mul(A,N),T=n.sub(j,N),T=n.mul(A,T),T=n.add(T,M),M=n.add(j,j),j=n.add(M,j),j=n.add(j,N),j=n.mul(j,T),R=n.add(R,j),N=n.mul(W,S),N=n.add(N,N),j=n.mul(N,T),$=n.sub($,j),M=n.mul(N,z),M=n.add(M,M),M=n.add(M,M),new y($,R,M)}add(A){f(A);const{px:_,py:k,pz:B}=this,{px:W,py:S,pz:$}=A;let R=n.ZERO,M=n.ZERO,j=n.ZERO;const z=e.a,N=n.mul(e.b,u$);let T=n.mul(_,W),U=n.mul(k,S),L=n.mul(B,$),P=n.add(_,k),H=n.add(W,S);P=n.mul(P,H),H=n.add(T,U),P=n.sub(P,H),H=n.add(_,B);let Y=n.add(W,$);return H=n.mul(H,Y),Y=n.add(T,L),H=n.sub(H,Y),Y=n.add(k,B),R=n.add(S,$),Y=n.mul(Y,R),R=n.add(U,L),Y=n.sub(Y,R),j=n.mul(z,H),R=n.mul(N,L),j=n.add(R,j),R=n.sub(U,j),j=n.add(U,j),M=n.mul(R,j),U=n.add(T,T),U=n.add(U,T),L=n.mul(z,L),H=n.mul(N,H),U=n.add(U,L),L=n.sub(T,L),L=n.mul(z,L),H=n.add(H,L),T=n.mul(U,H),M=n.add(M,T),T=n.mul(Y,H),R=n.mul(P,R),R=n.sub(R,T),T=n.mul(P,U),j=n.mul(Y,j),j=n.add(j,T),new y(R,M,j)}subtract(A){return this.add(A.negate())}is0(){return this.equals(y.ZERO)}wNAF(A){return x.wNAFCached(this,A,y.normalizeZ)}multiplyUnsafe(A){const{endo:_,n:k}=e;ov("scalar",A,gh,k);const B=y.ZERO;if(A===gh)return B;if(this.is0()||A===hi)return this;if(!_||x.hasPrecomputes(this))return x.wNAFCachedUnsafe(this,A,y.normalizeZ);let{k1neg:W,k1:S,k2neg:$,k2:R}=_.splitScalar(A),M=B,j=B,z=this;for(;S>gh||R>gh;)S&hi&&(M=M.add(z)),R&hi&&(j=j.add(z)),z=z.double(),S>>=hi,R>>=hi;return W&&(M=M.negate()),$&&(j=j.negate()),j=new y(n.mul(j.px,_.beta),j.py,j.pz),M.add(j)}multiply(A){const{endo:_,n:k}=e;ov("scalar",A,hi,k);let B,W;if(_){const{k1neg:S,k1:$,k2neg:R,k2:M}=_.splitScalar(A);let{p:j,f:z}=this.wNAF($),{p:N,f:T}=this.wNAF(M);j=x.constTimeNegate(S,j),N=x.constTimeNegate(R,N),N=new y(n.mul(N.px,_.beta),N.py,N.pz),B=j.add(N),W=z.add(T)}else{const{p:S,f:$}=this.wNAF(A);B=S,W=$}return y.normalizeZ([B,W])[0]}multiplyAndAddUnsafe(A,_,k){const B=y.BASE,W=($,R)=>R===gh||R===hi||!$.equals(B)?$.multiplyUnsafe(R):$.multiply(R),S=W(this,_).add(W(A,k));return S.is0()?void 0:S}toAffine(A){return p(this,A)}isTorsionFree(){const{h:A,isTorsionFree:_}=e;if(A===hi)return!0;if(_)return _(y,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:A,clearCofactor:_}=e;return A===hi?this:_?_(y,this):this.multiplyUnsafe(e.h)}toRawBytes(A=!0){return MC("isCompressed",A),this.assertValidity(),s(y,this,A)}toHex(A=!0){return MC("isCompressed",A),LC(this.toRawBytes(A))}}y.BASE=new y(e.Gx,e.Gy,n.ONE),y.ZERO=new y(n.ZERO,n.ONE,n.ZERO);const{endo:b,nBitLength:v}=e,x=yLe(y,b?Math.ceil(v/2):v);return{CURVE:e,ProjectivePoint:y,normPrivateKeyToScalar:d,weierstrassEquation:o,isWithinCurveOrder:u}}function CLe(t){const e=Vue(t);return UP(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function _Le(t){const e=CLe(t),{Fp:n,n:r,nByteLength:s,nBitLength:i}=e,o=n.BYTES+1,a=2*n.BYTES+1;function c(N){return Pa(N,r)}function l(N){return FL(N,r)}const{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:p}=ELe({...e,toBytes(N,T,U){const L=T.toAffine(),P=n.toBytes(L.x),H=iT;return MC("isCompressed",U),U?H(Uint8Array.from([T.hasEvenY()?2:3]),P):H(Uint8Array.from([4]),P,n.toBytes(L.y))},fromBytes(N){const T=N.length,U=N[0],L=N.subarray(1);if(T===o&&(U===2||U===3)){const P=Wm(L);if(!Rj(P,hi,n.ORDER))throw new Error("Point is not on curve");const H=f(P);let Y;try{Y=n.sqrt(H)}catch(fe){const ve=fe instanceof Error?": "+fe.message:"";throw new Error("Point is not on curve"+ve)}const re=(Y&hi)===hi;return(U&1)===1!==re&&(Y=n.neg(Y)),{x:P,y:Y}}else if(T===a&&U===4){const P=n.fromBytes(L.subarray(0,n.BYTES)),H=n.fromBytes(L.subarray(n.BYTES,2*n.BYTES));return{x:P,y:H}}else{const P=o,H=a;throw new Error("invalid Point, expected length of "+P+", or uncompressed "+H+", got "+T)}}});function m(N){const T=r>>hi;return N>T}function y(N){return m(N)?c(-N):N}const b=(N,T,U)=>Wm(N.slice(T,U));class v{constructor(T,U,L){ov("r",T,hi,r),ov("s",U,hi,r),this.r=T,this.s=U,L!=null&&(this.recovery=L),Object.freeze(this)}static fromCompact(T){const U=s;return T=gl("compactSignature",T,U*2),new v(b(T,0,U),b(T,U,2*U))}static fromDER(T){const{r:U,s:L}=dh.toSig(gl("DER",T));return new v(U,L)}assertValidity(){}addRecoveryBit(T){return new v(this.r,this.s,T)}recoverPublicKey(T){const{r:U,s:L,recovery:P}=this,H=B(gl("msgHash",T));if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");const Y=P===2||P===3?U+e.n:U;if(Y>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const re=P&1?"03":"02",de=u.fromHex(re+l$(Y,n.BYTES)),fe=l(Y),ve=c(-H*fe),Ee=c(L*fe),oe=u.BASE.multiplyAndAddUnsafe(de,ve,Ee);if(!oe)throw new Error("point at infinify");return oe.assertValidity(),oe}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return sT(this.toDERHex())}toDERHex(){return dh.hexFromSig(this)}toCompactRawBytes(){return sT(this.toCompactHex())}toCompactHex(){const T=s;return l$(this.r,T)+l$(this.s,T)}}const x={isValidPrivateKey(N){try{return d(N),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{const N=jue(e.n);return pLe(e.randomBytes(N),e.n)},precompute(N=8,T=u.BASE){return T._setWindowSize(N),T.multiply(BigInt(3)),T}};function E(N,T=!0){return u.fromPrivateKey(N).toRawBytes(T)}function A(N){if(typeof N=="bigint")return!1;if(N instanceof u)return!0;const U=gl("key",N).length,L=n.BYTES,P=L+1,H=2*L+1;if(!(e.allowedPrivateKeyLengths||s===P))return U===P||U===H}function _(N,T,U=!0){if(A(N)===!0)throw new Error("first arg must be private key");if(A(T)===!1)throw new Error("second arg must be public key");return u.fromHex(T).multiply(d(N)).toRawBytes(U)}const k=e.bits2int||function(N){if(N.length>8192)throw new Error("input is too large");const T=Wm(N),U=N.length*8-i;return U>0?T>>BigInt(U):T},B=e.bits2int_modN||function(N){return c(k(N))},W=BP(i);function S(N){return ov("num < 2^"+i,N,gh,W),WS(N,s)}function $(N,T,U=R){if(["recovered","canonical"].some(je=>je in U))throw new Error("sign() legacy options not supported");const{hash:L,randomBytes:P}=e;let{lowS:H,prehash:Y,extraEntropy:re}=U;H==null&&(H=!0),N=gl("msgHash",N),tX(U),Y&&(N=gl("prehashed msgHash",L(N)));const de=B(N),fe=d(T),ve=[S(fe),S(de)];if(re!=null&&re!==!1){const je=re===!0?P(n.BYTES):re;ve.push(gl("extraEntropy",je))}const Ee=iT(...ve),oe=de;function Oe(je){const V=k(je);if(!p(V))return;const we=l(V),Ae=u.BASE.multiply(V).toAffine(),Ie=c(Ae.x);if(Ie===gh)return;const ge=c(we*c(oe+Ie*fe));if(ge===gh)return;let Me=(Ae.x===Ie?0:2)|Number(Ae.y&hi),be=ge;return H&&m(ge)&&(be=y(ge),Me^=1),new v(Ie,be,Me)}return{seed:Ee,k2sig:Oe}}const R={lowS:e.lowS,prehash:!1},M={lowS:e.lowS,prehash:!1};function j(N,T,U=R){const{seed:L,k2sig:P}=$(N,T,U),H=e;return F$e(H.hash.outputLen,H.nByteLength,H.hmac)(L,P)}u.BASE._setWindowSize(8);function z(N,T,U,L=M){const P=N;T=gl("msgHash",T),U=gl("publicKey",U);const{lowS:H,prehash:Y,format:re}=L;if(tX(L),"strict"in L)throw new Error("options.strict was renamed to lowS");if(re!==void 0&&re!=="compact"&&re!=="der")throw new Error("format must be compact or der");const de=typeof P=="string"||zS(P),fe=!de&&!re&&typeof P=="object"&&P!==null&&typeof P.r=="bigint"&&typeof P.s=="bigint";if(!de&&!fe)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let ve,Ee;try{if(fe&&(ve=new v(P.r,P.s)),de){try{re!=="compact"&&(ve=v.fromDER(P))}catch(Me){if(!(Me instanceof dh.Err))throw Me}!ve&&re!=="der"&&(ve=v.fromCompact(P))}Ee=u.fromHex(U)}catch{return!1}if(!ve||H&&ve.hasHighS())return!1;Y&&(T=e.hash(T));const{r:oe,s:Oe}=ve,je=B(T),V=l(Oe),we=c(je*V),Ae=c(oe*V),Ie=u.BASE.multiplyAndAddUnsafe(Ee,we,Ae)?.toAffine();return Ie?c(Ie.x)===oe:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:_,sign:j,verify:z,ProjectivePoint:u,Signature:v,utils:x}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function SLe(t){return{hash:t,hmac:(e,...n)=>KS(t,e,mC(...n)),randomBytes:LS}}function ALe(t,e){const n=r=>_Le({...t,...SLe(r)});return{...n(e),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hue=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),nX=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ILe=BigInt(0),TLe=BigInt(1),zL=BigInt(2),rX=(t,e)=>(t+e/zL)/e;function NLe(t){const e=Hue,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,d=cl(u,n,e)*u%e,f=cl(d,n,e)*u%e,p=cl(f,zL,e)*l%e,m=cl(p,s,e)*p%e,y=cl(m,i,e)*m%e,b=cl(y,a,e)*y%e,v=cl(b,c,e)*b%e,x=cl(v,a,e)*y%e,E=cl(x,n,e)*u%e,A=cl(E,o,e)*m%e,_=cl(A,r,e)*l%e,k=cl(_,zL,e);if(!WL.eql(WL.sqr(k),t))throw new Error("Cannot find square root");return k}const WL=Xj(Hue,void 0,void 0,{sqrt:NLe}),que=ALe({a:ILe,b:BigInt(7),Fp:WL,n:nX,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=nX,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-TLe*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=n,o=BigInt("0x100000000000000000000000000000000"),a=rX(i*t,e),c=rX(-r*t,e);let l=Pa(t-a*n-c*s,e),u=Pa(-a*r-c*i,e);const d=l>o,f=u>o;if(d&&(l=e-l),f&&(u=e-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:d,k1:l,k2neg:f,k2:u}}}},VP),PLe=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:que},Symbol.toStringTag,{value:"Module"}));function Kue(t,e={}){const{recovered:n}=e;if(typeof t.r>"u")throw new d$({signature:t});if(typeof t.s>"u")throw new d$({signature:t});if(n&&typeof t.yParity>"u")throw new d$({signature:t});if(t.r<0n||t.r>ZY)throw new LLe({value:t.r});if(t.s<0n||t.s>ZY)throw new BLe({value:t.s});if(typeof t.yParity=="number"&&t.yParity!==0&&t.yParity!==1)throw new Jj({value:t.yParity})}function kLe(t){return Gue(rd(t))}function Gue(t){if(t.length!==130&&t.length!==132)throw new MLe({signature:t});const e=BigInt(Yg(t,0,32)),n=BigInt(Yg(t,32,64)),r=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return Qj(s)}catch{throw new Jj({value:s})}})();return typeof r>"u"?{r:e,s:n}:{r:e,s:n,yParity:r}}function RLe(t){if(!(typeof t.r>"u")&&!(typeof t.s>"u"))return OLe(t)}function OLe(t){const e=typeof t=="string"?Gue(t):t instanceof Uint8Array?kLe(t):typeof t.r=="string"?DLe(t):t.v?$Le(t):{r:t.r,s:t.s,...typeof t.yParity<"u"?{yParity:t.yParity}:{}};return Kue(e),e}function $Le(t){return{r:t.r,s:t.s,yParity:Qj(t.v)}}function DLe(t){const e=(()=>{const n=t.v?Number(t.v):void 0;let r=t.yParity?Number(t.yParity):void 0;if(typeof n=="number"&&typeof r!="number"&&(r=Qj(n)),typeof r!="number")throw new Jj({value:t.yParity});return r})();return{r:BigInt(t.r),s:BigInt(t.s),yParity:e}}function Qj(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new ULe({value:t})}class MLe extends vr{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Fc(dDe(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class d$ extends vr{constructor({signature:e}){super(`Signature \`${$le(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class LLe extends vr{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class BLe extends vr{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class Jj extends vr{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class ULe extends vr{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function FLe(t,e={}){return typeof t.chainId=="string"?jLe(t):{...t,...e.signature}}function jLe(t){const{address:e,chainId:n,nonce:r}=t,s=RLe(t);return{address:e,chainId:Number(n),nonce:BigInt(r),...s}}const zLe="0x8010801080108010801080108010801080108010801080108010801080108010",WLe=kue("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function Zue(t){if(typeof t=="string"){if(Yg(t,-32)!==zLe)throw new qLe(t)}else Kue(t.authorization)}function VLe(t){Zue(t);const e=Fle(Yg(t,-64,-32)),n=Yg(t,-e-64,-64),r=Yg(t,0,-e-64),[s,i,o]=eLe(WLe,n);return{authorization:FLe({address:s.delegation,chainId:Number(s.chainId),nonce:s.nonce,yParity:s.yParity,r:s.r,s:s.s}),signature:r,...o&&o!=="0x"?{data:o,to:i}:{}}}function HLe(t){try{return Zue(t),!0}catch{return!1}}let qLe=class extends vr{constructor(e){super(`Value \`${e}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}};class KLe extends ot{constructor({value:e}){super(`Number \`${e}\` is not a valid decimal number.`,{name:"InvalidDecimalNumberError"})}}function GLe(t,e){if(!/^(-?)([0-9]*)\.?([0-9]*)$/.test(t))throw new KLe({value:t});let[n,r="0"]=t.split(".");const s=n.startsWith("-");if(s&&(n=n.slice(1)),r=r.replace(/(0+)$/,""),e===0)Math.round(+`.${r}`)===1&&(n=`${BigInt(n)+1n}`),r="";else if(r.length>e){const[i,o,a]=[r.slice(0,e-1),r.slice(e-1,e),r.slice(e)],c=Math.round(+`${o}.${a}`);c>9?r=`${BigInt(i)+BigInt(1)}0`.padStart(i.length+1,"0"):r=`${i}${c}`,r.length>e&&(r=r.slice(1),n=`${BigInt(n)+1n}`),r=r.slice(0,e)}else r=r.padEnd(e,"0");return BigInt(`${s?"-":""}${n}${r}`)}async function Yue(t,{blockHash:e,blockNumber:n,blockTag:r,hash:s,index:i}){const o=r||"latest",a=n!==void 0?$n(n):void 0;let c=null;if(s?c=await t.request({method:"eth_getTransactionByHash",params:[s]},{dedupe:!0}):e?c=await t.request({method:"eth_getTransactionByBlockHashAndIndex",params:[e,$n(i)]},{dedupe:!0}):(a||o)&&(c=await t.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[a||o,$n(i)]},{dedupe:!!a})),!c)throw new Cle({blockHash:e,blockNumber:n,blockTag:o,hash:s,index:i});return(t.chain?.formatters?.transaction?.format||Qle)(c)}async function f$(t,{hash:e}){const n=await t.request({method:"eth_getTransactionReceipt",params:[e]},{dedupe:!0});if(!n)throw new _le({hash:e});return(t.chain?.formatters?.transactionReceipt?.format||O9e)(n)}async function ZLe(t,e){const{account:n,authorizationList:r,allowFailure:s=!0,blockNumber:i,blockTag:o,stateOverride:a}=e,c=e.contracts,{batchSize:l=e.batchSize??1024,deployless:u=e.deployless??!1}=typeof t.batch?.multicall=="object"?t.batch.multicall:{},d=(()=>{if(e.multicallAddress)return e.multicallAddress;if(u)return null;if(t.chain)return _j({blockNumber:i,chain:t.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),f=[[]];let p=0,m=0;for(let v=0;v0&&m>l&&f[p].length>0&&(p++,m=(k.length-2)/2,f[p]=[]),f[p]=[...f[p],{allowFailure:!0,callData:k,target:E}]}catch(k){const B=rT(k,{abi:x,address:E,args:A,docsPath:"/docs/contract/multicall",functionName:_,sender:n});if(!s)throw B;f[p]=[...f[p],{allowFailure:!0,callData:"0x",target:E}]}}const y=await Promise.allSettled(f.map(v=>$r(t,HS,"readContract")({...d===null?{code:Oj}:{address:d},abi:nT,account:n,args:[v],authorizationList:r,blockNumber:i,blockTag:o,functionName:"aggregate3",stateOverride:a}))),b=[];for(let v=0;v{if(s===0||s===1)return s;if(r&&(r===27n||r===28n||r>=35n))return r%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),o=`0x${new que.Signature(l0(t),l0(e)).toCompactHex()}${i===0?"1b":"1c"}`;return n==="hex"?o:nd(o)}async function n7e(t,e){const{address:n,hash:r,erc6492VerifierAddress:s=e.universalSignatureVerifierAddress??t.chain?.contracts?.erc6492Verifier?.address,multicallAddress:i=e.multicallAddress??t.chain?.contracts?.multicall3?.address}=e,o=(()=>{const a=e.signature;return Hh(a)?a:typeof a=="object"&&"r"in a&&"s"in a?t7e(a):Po(a)})();try{return HLe(o)?await r7e(t,{...e,multicallAddress:i,signature:o}):await s7e(t,{...e,verifierAddress:s,signature:o})}catch(a){try{if(Hj(wh(n),await Kle({hash:r,signature:o})))return!0}catch{}if(a instanceof hy)return!1;throw a}}async function r7e(t,e){const{address:n,blockNumber:r,blockTag:s,hash:i,multicallAddress:o}=e,{authorization:a,data:c,signature:l,to:u}=VLe(e.signature);if(await b9e(t,{address:n,blockNumber:r,blockTag:s})===Q1(["0xef0100",a.address]))return await i7e(t,{address:n,blockNumber:r,blockTag:s,hash:i,signature:l});const f={address:a.address,chainId:Number(a.chainId),nonce:Number(a.nonce),r:$n(a.r,{size:32}),s:$n(a.s,{size:32}),yParity:a.yParity};if(!await S9e({address:n,authorization:f}))throw new hy;const m=await $r(t,HS,"readContract")({...o?{address:o}:{code:Oj},authorizationList:[f],abi:nT,blockNumber:r,blockTag:"pending",functionName:"aggregate3",args:[[...c?[{allowFailure:!0,target:u??n,callData:c}]:[],{allowFailure:!0,target:n,callData:ex({abi:Tce,functionName:"isValidSignature",args:[i,l]})}]]});if(m[m.length-1]?.returnData?.startsWith("0x1626ba7e"))return!0;throw new hy}async function s7e(t,e){const{address:n,factory:r,factoryData:s,hash:i,signature:o,verifierAddress:a,...c}=e,l=await(async()=>!r&&!s||JLe(o)?o:QLe({data:s,signature:o,to:r}))(),u=a?{to:a,data:ex({abi:pY,functionName:"isValidSig",args:[n,i,l]}),...c}:{data:$j({abi:pY,args:[n,i,l],bytecode:bDe}),...c},{data:d}=await $r(t,Bj,"call")(u).catch(f=>{throw f instanceof Sle?new hy:f});if(dRe(d??"0x0"))return!0;throw new hy}async function i7e(t,e){const{address:n,blockNumber:r,blockTag:s,hash:i,signature:o}=e;if((await $r(t,HS,"readContract")({address:n,abi:Tce,args:[i,o],blockNumber:r,blockTag:s,functionName:"isValidSignature"}).catch(c=>{throw c instanceof Ij?new hy:c})).startsWith("0x1626ba7e"))return!0;throw new hy}let hy=class extends Error{};async function o7e(t,{address:e,message:n,factory:r,factoryData:s,signature:i,...o}){const a=B9e(n);return n7e(t,{address:e,factory:r,factoryData:s,hash:a,signature:i,...o})}const h$=new Map,sX=new Map;let a7e=0;function uT(t,e,n){const r=++a7e,s=()=>h$.get(t)||[],i=()=>{const u=s();h$.set(t,u.filter(d=>d.id!==r))},o=()=>{const u=s();if(!u.some(f=>f.id===r))return;const d=sX.get(t);if(u.length===1&&d){const f=d();f instanceof Promise&&f.catch(()=>{})}i()},a=s();if(h$.set(t,[...a,{id:r,fns:e}]),a&&a.length>0)return o;const c={};for(const u in e)c[u]=(...d)=>{const f=s();if(f.length!==0)for(const p of f)p.fns[u]?.(...d)};const l=n(c);return typeof l=="function"&&sX.set(t,l),o}function Que(t,{emitOnBegin:e,initialWaitTime:n,interval:r}){let s=!0;const i=()=>s=!1;return(async()=>{let a;e&&(a=await t({unpoll:i}));const c=await n?.(a)??r;await cT(c);const l=async()=>{s&&(await t({unpoll:i}),await cT(r),l())};l()})(),i}function c7e(t,{emitOnBegin:e=!1,emitMissed:n=!1,onBlockNumber:r,onError:s,poll:i,pollingInterval:o=t.pollingInterval}){const a=typeof i<"u"?i:!(t.transport.type==="webSocket"||t.transport.type==="ipc"||t.transport.type==="fallback"&&(t.transport.transports[0].config.type==="webSocket"||t.transport.transports[0].config.type==="ipc"));let c;return a?(()=>{const d=Dl(["watchBlockNumber",t.uid,e,n,o]);return uT(d,{onBlockNumber:r,onError:s},f=>Que(async()=>{try{const p=await $r(t,w9e,"getBlockNumber")({cacheTime:0});if(c){if(p===c)return;if(p-c>1&&n)for(let m=c+1n;mc)&&(f.onBlockNumber(p,c),c=p)}catch(p){f.onError?.(p)}},{emitOnBegin:e,interval:o}))})():(()=>{const d=Dl(["watchBlockNumber",t.uid,e,n]);return uT(d,{onBlockNumber:r,onError:s},f=>{let p=!0,m=()=>p=!1;return(async()=>{try{const y=(()=>{if(t.transport.type==="fallback"){const v=t.transport.transports.find(x=>x.config.type==="webSocket"||x.config.type==="ipc");return v?v.value:t.transport}return t.transport})(),{unsubscribe:b}=await y.subscribe({params:["newHeads"],onData(v){if(!p)return;const x=l0(v.result?.number);f.onBlockNumber(x,c),c=x},onError(v){f.onError?.(v)}});m=b,p||m()}catch(y){s?.(y)}})(),()=>m()})})()}async function l7e(t,e){const{checkReplacement:n=!0,confirmations:r=1,hash:s,onReplaced:i,retryCount:o=6,retryDelay:a=({count:_})=>~~(1<<_)*200,timeout:c=18e4}=e,l=Dl(["waitForTransactionReceipt",t.uid,s]),u=e.pollingInterval?e.pollingInterval:t.chain?.experimental_preconfirmationTime?t.chain.experimental_preconfirmationTime:t.pollingInterval;let d,f,p,m=!1,y,b;const{promise:v,resolve:x,reject:E}=Wle(),A=c?setTimeout(()=>{b?.(),y?.(),E(new A$e({hash:s}))},c):void 0;return y=uT(l,{onReplaced:i,resolve:x,reject:E},async _=>{if(p=await $r(t,f$,"getTransactionReceipt")({hash:s}).catch(()=>{}),p&&r<=1){clearTimeout(A),_.resolve(p),y?.();return}b=$r(t,c7e,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:u,async onBlockNumber(k){const B=S=>{clearTimeout(A),b?.(),S(),y?.()};let W=k;if(!m)try{if(p){if(r>1&&(!p.blockNumber||W-p.blockNumber+1n_.resolve(p));return}if(n&&!d&&(m=!0,await lT(async()=>{d=await $r(t,Yue,"getTransaction")({hash:s}),d.blockNumber&&(W=d.blockNumber)},{delay:a,retryCount:o}),m=!1),p=await $r(t,f$,"getTransactionReceipt")({hash:s}),r>1&&(!p.blockNumber||W-p.blockNumber+1n_.resolve(p))}catch(S){if(S instanceof Cle||S instanceof _le){if(!d){m=!1;return}try{f=d,m=!0;const $=await lT(()=>$r(t,BC,"getBlock")({blockNumber:W,includeTransactions:!0}),{delay:a,retryCount:o,shouldRetry:({error:j})=>j instanceof Yle});m=!1;const R=$.transactions.find(({from:j,nonce:z})=>j===f.from&&z===f.nonce);if(!R||(p=await $r(t,f$,"getTransactionReceipt")({hash:R.hash}),r>1&&(!p.blockNumber||W-p.blockNumber+1n{_.onReplaced?.({reason:M,replacedTransaction:f,transaction:R,transactionReceipt:p}),_.resolve(p)})}catch($){B(()=>_.reject($))}}else B(()=>_.reject(S))}}})}),v}function u7e(t,{batch:e=!0,onError:n,onTransactions:r,poll:s,pollingInterval:i=t.pollingInterval}){return(typeof s<"u"?s:t.transport.type!=="webSocket"&&t.transport.type!=="ipc")?(()=>{const l=Dl(["watchPendingTransactions",t.uid,e,i]);return uT(l,{onTransactions:r,onError:n},u=>{let d;const f=Que(async()=>{try{if(!d)try{d=await $r(t,kDe,"createPendingTransactionFilter")({});return}catch(m){throw f(),m}const p=await $r(t,_9e,"getFilterChanges")({filter:d});if(p.length===0)return;if(e)u.onTransactions(p);else for(const m of p)u.onTransactions([m])}catch(p){u.onError?.(p)}},{emitOnBegin:!0,interval:i});return async()=>{d&&await $r(t,YLe,"uninstallFilter")({filter:d}),f()}})})():(()=>{let l=!0,u=()=>l=!1;return(async()=>{try{const{unsubscribe:d}=await t.transport.subscribe({params:["newPendingTransactions"],onData(f){if(!l)return;const p=f.result;r([p])},onError(f){n?.(f)}});u=d,l||u()}catch(d){n?.(d)}})(),()=>u()})()}class ez extends ot{constructor({docsPath:e}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(` +`),{docsPath:e,docsSlug:"account",name:"AccountNotFoundError"})}}class p$ extends ot{constructor({docsPath:e,metaMessages:n,type:r}){super(`Account type "${r}" is not supported.`,{docsPath:e,metaMessages:n,name:"AccountTypeNotSupportedError"})}}async function d7e(t,{serializedTransaction:e}){return t.request({method:"eth_sendRawTransaction",params:[e]},{retryCount:0})}const g$=new DP(128);async function Jue(t,e){const{account:n=t.account,chain:r=t.chain,accessList:s,authorizationList:i,blobs:o,data:a,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:f,nonce:p,type:m,value:y,...b}=e;if(typeof n>"u")throw new ez({docsPath:"/docs/actions/wallet/sendTransaction"});const v=n?Cf(n):null;try{zP(e);const x=await(async()=>{if(e.to)return e.to;if(e.to!==null&&i&&i.length>0)return await Uj({authorization:i[0]}).catch(()=>{throw new ot("`to` is required. Could not infer from `authorizationList`.")})})();if(v?.type==="json-rpc"||v===null){let E;r!==null&&(E=await $r(t,due,"getChainId")({}),N9e({currentChainId:E,chain:r}));const A=t.chain?.formatters?.transactionRequest?.format,k=(A||Lj)({...Mj(b,{format:A}),accessList:s,authorizationList:i,blobs:o,chainId:E,data:a,from:v?.address,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:f,nonce:p,to:x,type:m,value:y}),B=g$.get(t.uid),W=B?"wallet_sendTransaction":"eth_sendTransaction";try{return await t.request({method:W,params:[k]},{retryCount:0})}catch(S){if(B===!1)throw S;const $=S;if($.name==="InvalidInputRpcError"||$.name==="InvalidParamsRpcError"||$.name==="MethodNotFoundRpcError"||$.name==="MethodNotSupportedRpcError")return await t.request({method:"wallet_sendTransaction",params:[k]},{retryCount:0}).then(R=>(g$.set(t.uid,!0),R)).catch(R=>{const M=R;throw M.name==="MethodNotFoundRpcError"||M.name==="MethodNotSupportedRpcError"?(g$.set(t.uid,!1),$):M});throw $}}if(v?.type==="local"){const E=await $r(t,Vj,"prepareTransactionRequest")({account:v,accessList:s,authorizationList:i,blobs:o,chain:r,data:a,gas:c,gasPrice:l,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:f,nonce:p,nonceManager:v.nonceManager,parameters:[...fue,"sidecars"],type:m,value:y,...b,to:x}),A=r?.serializers?.transaction,_=await v.signTransaction(E,{serializer:A});return await $r(t,d7e,"sendRawTransaction")({serializedTransaction:_})}throw v?.type==="smart"?new p$({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new p$({docsPath:"/docs/actions/wallet/sendTransaction",type:v?.type})}catch(x){throw x instanceof p$?x:k9e(x,{...e,account:v,chain:e.chain||void 0})}}async function f7e(t,{account:e=t.account,message:n}){if(!e)throw new ez({docsPath:"/docs/actions/wallet/signMessage"});const r=Cf(e);if(r.signMessage)return r.signMessage({message:n});const s=typeof n=="string"?$v(n):n.raw instanceof Uint8Array?Ov(n.raw):n.raw;return t.request({method:"personal_sign",params:[s,r.address]},{retryCount:0})}async function h7e(t,e){const{abi:n,account:r=t.account,address:s,args:i,dataSuffix:o,functionName:a,...c}=e;if(typeof r>"u")throw new ez({docsPath:"/docs/contract/writeContract"});const l=r?Cf(r):null,u=ex({abi:n,args:i,functionName:a});try{return await $r(t,Jue,"sendTransaction")({data:`${u}${o?o.replace("0x",""):""}`,to:s,account:l,...c})}catch(d){throw rT(d,{abi:n,address:s,args:i,docsPath:"/docs/contract/writeContract",functionName:a,sender:l?.address})}}function Za(t,e,n){const r=t[e.name];if(typeof r=="function")return r;const s=t[n];return typeof s=="function"?s:i=>e(t,i)}const yE="2.18.1",p7e=()=>`@wagmi/core@${yE}`;var ede=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},dT,tde;let wp=class VL extends Error{get docsBaseUrl(){return"https://wagmi.sh/core"}get version(){return p7e()}constructor(e,n={}){super(),dT.add(this),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"WagmiCoreError"});const r=n.cause instanceof VL?n.cause.details:n.cause?.message?n.cause.message:n.details,s=n.cause instanceof VL&&n.cause.docsPath||n.docsPath;this.message=[e||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: ${this.docsBaseUrl}${s}.html${n.docsSlug?`#${n.docsSlug}`:""}`]:[],...r?[`Details: ${r}`]:[],`Version: ${this.version}`].join(` +`),n.cause&&(this.cause=n.cause),this.details=r,this.docsPath=s,this.metaMessages=n.metaMessages,this.shortMessage=e}walk(e){return ede(this,dT,"m",tde).call(this,this,e)}};dT=new WeakSet,tde=function t(e,n){return n?.(e)?e:e.cause?ede(this,dT,"m",t).call(this,e.cause,n):e};class Uv extends wp{constructor(){super("Chain not configured."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ChainNotConfiguredError"})}}class nde extends wp{constructor(){super("Connector already connected."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorAlreadyConnectedError"})}}class rde extends wp{constructor(){super("Connector not connected."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorNotConnectedError"})}}class sde extends wp{constructor({address:e,connector:n}){super(`Account "${e}" not found for connector "${n.name}".`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorAccountNotFoundError"})}}class ide extends wp{constructor({connectionChainId:e,connectorChainId:n}){super(`The current chain of the connector (id: ${n}) does not match the connection's chain (id: ${e}).`,{metaMessages:[`Current Chain ID: ${n}`,`Expected Chain ID: ${e}`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorChainMismatchError"})}}class ode extends wp{constructor({connector:e}){super(`Connector "${e.name}" unavailable while reconnecting.`,{details:["During the reconnection step, the only connector methods guaranteed to be available are: `id`, `name`, `type`, `uid`.","All other methods are not guaranteed to be available until reconnection completes and connectors are fully restored.","This error commonly occurs for connectors that asynchronously inject after reconnection has already started."].join(" ")}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorUnavailableReconnectingError"})}}async function UI(t,e){let n;if(typeof e.connector=="function"?n=t._internal.connectors.setup(e.connector):n=e.connector,n.uid===t.state.current)throw new nde;try{t.setState(a=>({...a,status:"connecting"})),n.emitter.emit("message",{type:"connecting"});const{connector:r,...s}=e,i=await n.connect(s),o=i.accounts;return n.emitter.off("connect",t._internal.events.connect),n.emitter.on("change",t._internal.events.change),n.emitter.on("disconnect",t._internal.events.disconnect),await t.storage?.setItem("recentConnectorId",n.id),t.setState(a=>({...a,connections:new Map(a.connections).set(n.uid,{accounts:o,chainId:i.chainId,connector:n}),current:n.uid,status:"connected"})),{accounts:o,chainId:i.chainId}}catch(r){throw t.setState(s=>({...s,status:s.current?"connected":"disconnected"})),r}}const HL=256;let dA=HL,fA;function ade(t=11){if(!fA||dA+t>HL*2){fA="",dA=0;for(let e=0;e{const _=A(E);for(const B in v)delete _[B];const k={...E,..._};return Object.assign(k,{extend:x(k)})}}return Object.assign(v,{extend:x(v)})}function tz({key:t,methods:e,name:n,request:r,retryCount:s=3,retryDelay:i=150,timeout:o,type:a},c){const l=ade();return{config:{key:t,methods:e,name:n,request:r,retryCount:s,retryDelay:i,timeout:o,type:a},request:I9e(r,{methods:e,retryCount:s,retryDelay:i,uid:l}),value:c}}function lde(t,e={}){const{key:n="custom",methods:r,name:s="Custom Provider",retryDelay:i}=e;return({retryCount:o})=>tz({key:n,methods:r,name:s,request:t.request.bind(t),retryCount:e.retryCount??o,retryDelay:i,type:"custom"})}function iX(t,e={}){const{key:n="fallback",name:r="Fallback",rank:s=!1,shouldThrow:i=g7e,retryCount:o,retryDelay:a}=e;return({chain:c,pollingInterval:l=4e3,timeout:u,...d})=>{let f=t,p=()=>{};const m=tz({key:n,name:r,async request({method:y,params:b}){let v;const x=async(E=0)=>{const A=f[E]({...d,chain:c,retryCount:0,timeout:u});try{const _=await A.request({method:y,params:b});return p({method:y,params:b,response:_,transport:A,status:"success"}),_}catch(_){if(p({error:_,method:y,params:b,transport:A,status:"error"}),i(_)||E===f.length-1||(v??=f.slice(E+1).some(k=>{const{include:B,exclude:W}=k({chain:c}).config.methods||{};return B?B.includes(y):W?!W.includes(y):!0}),!v))throw _;return x(E+1)}};return x()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:y=>p=y,transports:f.map(y=>y({chain:c,retryCount:0}))});if(s){const y=typeof s=="object"?s:{};m7e({chain:c,interval:y.interval??l,onTransports:b=>f=b,ping:y.ping,sampleCount:y.sampleCount,timeout:y.timeout,transports:f,weights:y.weights})}return m}}function g7e(t){return!!("code"in t&&typeof t.code=="number"&&(t.code===Lv.code||t.code===ti.code||wm.nodeMessage.test(t.message)||t.code===5e3))}function m7e({chain:t,interval:e=4e3,onTransports:n,ping:r,sampleCount:s=10,timeout:i=1e3,transports:o,weights:a={}}){const{stability:c=.7,latency:l=.3}=a,u=[],d=async()=>{const f=await Promise.all(o.map(async y=>{const b=y({chain:t,retryCount:0,timeout:i}),v=Date.now();let x,E;try{await(r?r({transport:b}):b.request({method:"net_listening"})),E=1}catch{E=0}finally{x=Date.now()}return{latency:x-v,success:E}}));u.push(f),u.length>s&&u.shift();const p=Math.max(...u.map(y=>Math.max(...y.map(({latency:b})=>b)))),m=o.map((y,b)=>{const v=u.map(k=>k[b].latency),E=1-v.reduce((k,B)=>k+B,0)/v.length/p,A=u.map(k=>k[b].success),_=A.reduce((k,B)=>k+B,0)/A.length;return _===0?[0,b]:[l*E+c*_,b]}).sort((y,b)=>b[0]-y[0]);n(m.map(([,y])=>o[y])),await cT(e),d()};d()}class y7e extends ot{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function B2(t,e={}){const{batch:n,fetchOptions:r,key:s="http",methods:i,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:l,raw:u}=e;return({chain:d,retryCount:f,timeout:p})=>{const{batchSize:m=1e3,wait:y=0}=typeof n=="object"?n:{},b=e.retryCount??f,v=p??e.timeout??1e4,x=t||d?.rpcUrls.default.http[0];if(!x)throw new y7e;const E=D9e(x,{fetchOptions:r,onRequest:a,onResponse:c,timeout:v});return tz({key:s,methods:i,name:o,async request({method:A,params:_}){const k={method:A,params:_},{schedule:B}=Vle({id:x,wait:y,shouldSplitBatch(R){return R.length>m},fn:R=>E.request({body:R}),sort:(R,M)=>R.id-M.id}),W=async R=>n?B(R):[await E.request({body:R})],[{error:S,result:$}]=await W(k);if(u)return{error:S,result:$};if(S)throw new Nj({body:k,error:S,url:x});return $},retryCount:b,retryDelay:l,timeout:v,type:"http"},{fetchOptions:r,url:x})}}async function GS(t,e={}){let n;if(e.connector){const{connector:l}=e;if(t.state.status==="reconnecting"&&!l.getAccounts&&!l.getChainId)throw new ode({connector:l});const[u,d]=await Promise.all([l.getAccounts().catch(f=>{if(e.account===null)return[];throw f}),l.getChainId()]);n={accounts:u,chainId:d,connector:l}}else n=t.state.connections.get(t.state.current);if(!n)throw new rde;const r=e.chainId??n.chainId,s=await n.connector.getChainId();if(s!==n.chainId)throw new ide({connectionChainId:n.chainId,connectorChainId:s});const i=n.connector;if(i.getClient)return i.getClient({chainId:r});const o=Cf(e.account??n.accounts[0]);if(o&&(o.address=wh(o.address)),e.account&&!n.accounts.some(l=>l.toLowerCase()===o.address.toLowerCase()))throw new sde({address:o.address,connector:i});const a=t.chains.find(l=>l.id===r),c=await n.connector.getProvider({chainId:r});return cde({account:o,chain:a,name:"Connector Client",transport:l=>lde(c)({...l,retryCount:0})})}async function qL(t,e={}){let n;if(e.connector)n=e.connector;else{const{connections:s,current:i}=t.state;n=s.get(i)?.connector}const r=t.state.connections;n&&(await n.disconnect(),n.emitter.off("change",t._internal.events.change),n.emitter.off("disconnect",t._internal.events.disconnect),n.emitter.on("connect",t._internal.events.connect),r.delete(n.uid)),t.setState(s=>{if(r.size===0)return{...s,connections:new Map,current:null,status:"disconnected"};const i=r.values().next().value;return{...s,connections:new Map(r),current:i.connector.uid}});{const s=t.state.current;if(!s)return;const i=t.state.connections.get(s)?.connector;if(!i)return;await t.storage?.setItem("recentConnectorId",i.id)}}function ude(t){return typeof t=="number"?t:t==="wei"?0:Math.abs(b$e[t])}async function dde(t,e){const{chainId:n,connector:r,...s}=e;let i;e.account?i=e.account:i=(await GS(t,{account:e.account,chainId:n,connector:r})).account;const o=t.getClient({chainId:n});return Za(o,pue,"estimateGas")({...s,account:i})}function cv(t){const e=t.state.current,n=t.state.connections.get(e),r=n?.accounts,s=r?.[0],i=t.chains.find(a=>a.id===n?.chainId),o=t.state.status;switch(o){case"connected":return{address:s,addresses:r,chain:i,chainId:n?.chainId,connector:n?.connector,isConnected:!0,isConnecting:!1,isDisconnected:!1,isReconnecting:!1,status:o};case"reconnecting":return{address:s,addresses:r,chain:i,chainId:n?.chainId,connector:n?.connector,isConnected:!!s,isConnecting:!1,isDisconnected:!1,isReconnecting:!0,status:o};case"connecting":return{address:s,addresses:r,chain:i,chainId:n?.chainId,connector:n?.connector,isConnected:!1,isConnecting:!0,isDisconnected:!1,isReconnecting:!1,status:o};case"disconnected":return{address:void 0,addresses:void 0,chain:void 0,chainId:void 0,connector:void 0,isConnected:!1,isConnecting:!1,isDisconnected:!0,isReconnecting:!1,status:o}}}async function fde(t,e){const{allowFailure:n=!0,chainId:r,contracts:s,...i}=e,o=t.getClient({chainId:r});return Za(o,ZLe,"multicall")({allowFailure:n,contracts:s,...i})}function hde(t,e){const{chainId:n,...r}=e,s=t.getClient({chainId:n});return Za(s,HS,"readContract")(r)}async function pde(t,e){const{allowFailure:n=!0,blockNumber:r,blockTag:s,...i}=e,o=e.contracts;try{const a={};for(const[d,f]of o.entries()){const p=f.chainId??t.state.chainId;a[p]||(a[p]=[]),a[p]?.push({contract:f,index:d})}const c=()=>Object.entries(a).map(([d,f])=>fde(t,{...i,allowFailure:n,blockNumber:r,blockTag:s,chainId:Number.parseInt(d),contracts:f.map(({contract:p})=>p)})),l=(await Promise.all(c())).flat(),u=Object.values(a).flatMap(d=>d.map(({index:f})=>f));return l.reduce((d,f,p)=>(d&&(d[u[p]]=f),d),[])}catch(a){if(a instanceof Ij)throw a;const c=()=>o.map(l=>hde(t,{...l,blockNumber:r,blockTag:s}));return n?(await Promise.allSettled(c())).map(l=>l.status==="fulfilled"?{result:l.value,status:"success"}:{error:l.reason,result:void 0,status:"failure"}):await Promise.all(c())}}async function KL(t,e){const{address:n,blockNumber:r,blockTag:s,chainId:i,token:o,unit:a="ether"}=e;if(o)try{return await oX(t,{balanceAddress:n,chainId:i,symbolType:"string",tokenAddress:o})}catch(f){if(f.name==="ContractFunctionExecutionError"){const p=await oX(t,{balanceAddress:n,chainId:i,symbolType:"bytes32",tokenAddress:o}),m=Fce(Gg(p.symbol,{dir:"right"}));return{...p,symbol:m}}throw f}const c=t.getClient({chainId:i}),u=await Za(c,hue,"getBalance")(r?{address:n,blockNumber:r}:{address:n,blockTag:s}),d=t.chains.find(f=>f.id===i)??c.chain;return{decimals:d.nativeCurrency.decimals,formatted:tx(u,ude(a)),symbol:d.nativeCurrency.symbol,value:u}}async function oX(t,e){const{balanceAddress:n,chainId:r,symbolType:s,tokenAddress:i,unit:o}=e,a={abi:[{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:s}]}],address:i},[c,l,u]=await pde(t,{allowFailure:!1,contracts:[{...a,functionName:"balanceOf",args:[n],chainId:r},{...a,functionName:"decimals",chainId:r},{...a,functionName:"symbol",chainId:r}]}),d=tx(c??"0",ude(o??l));return{decimals:l,formatted:d,symbol:u,value:c}}function Fv(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(t.constructor!==e.constructor)return!1;let n,r;if(Array.isArray(t)&&Array.isArray(e)){if(n=t.length,n!==e.length)return!1;for(r=n;r--!==0;)if(!Fv(t[r],e[r]))return!1;return!0}if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===e.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===e.toString();const s=Object.keys(t);if(n=s.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!Object.hasOwn(e,s[r]))return!1;for(r=n;r--!==0;){const i=s[r];if(i&&!Fv(t[i],e[i]))return!1}return!0}return t!==t&&e!==e}let hA=[];function Md(t){const e=[...t.state.connections.values()];return t.state.status==="reconnecting"||Fv(hA,e)?hA:(hA=e,e)}function fT(t,e){const{chainId:n,...r}=e,s=t.getClient({chainId:n});return Za(s,NDe,"getEnsName")(r)}async function gde(t,e){const{account:n,chainId:r,...s}=e,i=n??cv(t).address,o=t.getClient({chainId:r});return Za(o,Vj,"prepareTransactionRequest")({...s,...i?{account:i}:{}})}let m$=!1;async function hT(t,e={}){if(m$)return[];m$=!0,t.setState(l=>({...l,status:l.current?"reconnecting":"connecting"}));const n=[];if(e.connectors?.length)for(const l of e.connectors){let u;typeof l=="function"?u=t._internal.connectors.setup(l):u=l,n.push(u)}else n.push(...t.connectors);let r;try{r=await t.storage?.getItem("recentConnectorId")}catch{}const s={};for(const[,l]of t.state.connections)s[l.connector.id]=1;r&&(s[r]=0);const i=Object.keys(s).length>0?[...n].sort((l,u)=>(s[l.id]??10)-(s[u.id]??10)):n;let o=!1;const a=[],c=[];for(const l of i){const u=await l.getProvider().catch(()=>{});if(!u||c.some(p=>p===u)||!await l.isAuthorized())continue;const f=await l.connect({isReconnecting:!0}).catch(()=>null);f&&(l.emitter.off("connect",t._internal.events.connect),l.emitter.on("change",t._internal.events.change),l.emitter.on("disconnect",t._internal.events.disconnect),t.setState(p=>{const m=new Map(o?p.connections:new Map).set(l.uid,{accounts:f.accounts,chainId:f.chainId,connector:l});return{...p,current:o?p.current:l.uid,connections:m}}),a.push({accounts:f.accounts,chainId:f.chainId,connector:l}),c.push(u),o=!0)}return(t.state.status==="reconnecting"||t.state.status==="connecting")&&(o?t.setState(l=>({...l,status:"connected"})):t.setState(l=>({...l,connections:new Map,current:null,status:"disconnected"}))),m$=!1,a}async function mde(t,e){const{account:n,chainId:r,connector:s,...i}=e;let o;return typeof n=="object"&&n?.type==="local"?o=t.getClient({chainId:r}):o=await GS(t,{account:n??void 0,chainId:r,connector:s}),await Za(o,Jue,"sendTransaction")({...i,...n?{account:n}:{},chain:r?{id:r}:null,gas:i.gas??void 0})}async function yde(t,e){const{account:n,connector:r,...s}=e;let i;return typeof n=="object"&&n.type==="local"?i=t.getClient():i=await GS(t,{account:n,connector:r}),Za(i,f7e,"signMessage")({...s,...n?{account:n}:{}})}class fh extends wp{constructor(){super("Provider not found."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ProviderNotFoundError"})}}class wde extends wp{constructor({connector:e}){super(`"${e.name}" does not support programmatic chain switching.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SwitchChainNotSupportedError"})}}async function pT(t,e){const{addEthereumChainParameter:n,chainId:r}=e,s=t.state.connections.get(e.connector?.uid??t.state.current);if(s){const o=s.connector;if(!o.switchChain)throw new wde({connector:o});return await o.switchChain({addEthereumChainParameter:n,chainId:r})}const i=t.chains.find(o=>o.id===r);if(!i)throw new Uv;return t.setState(o=>({...o,chainId:r})),i}async function bde(t,e){const{chainId:n,...r}=e,s=t.getClient({chainId:n});return Za(s,o7e,"verifyMessage")(r)}async function GL(t,e){const{chainId:n,timeout:r=0,...s}=e,i=t.getClient({chainId:n}),a=await Za(i,l7e,"waitForTransactionReceipt")({...s,timeout:r});if(a.status==="reverted"){const l=await Za(i,Yue,"getTransaction")({hash:a.transactionHash}),d=await Za(i,Bj,"call")({...l,data:l.input,gasPrice:l.type!=="eip1559"?l.gasPrice:void 0,maxFeePerGas:l.type==="eip1559"?l.maxFeePerGas:void 0,maxPriorityFeePerGas:l.type==="eip1559"?l.maxPriorityFeePerGas:void 0}),f=d?.data?Fce(`0x${d.data.substring(138)}`):"unknown reason";throw new Error(f)}return{...a,chainId:i.chain.id}}function vde(t,e){const{onChange:n}=e;return t.subscribe(()=>cv(t),n,{equalityFn(r,s){const{connector:i,...o}=r,{connector:a,...c}=s;return Fv(o,c)&&i?.id===a?.id&&i?.uid===a?.uid}})}function xde(t,e){const{onChange:n}=e;return t.subscribe(()=>Md(t),n,{equalityFn:Fv})}function Ede(t,e){const{onChange:n}=e;return t._internal.connectors.subscribe((r,s)=>{n(Object.values(r),s)})}function Cde(t,e){const{syncConnectedChain:n=t._internal.syncConnectedChain,...r}=e;let s;const i=c=>{s&&s();const l=t.getClient({chainId:c});return s=Za(l,u7e,"watchPendingTransactions")(r),s},o=i(e.chainId);let a;return n&&!e.chainId&&(a=t.subscribe(({chainId:c})=>c,async c=>i(c))),()=>{o?.(),a?.()}}async function _de(t,e){const{account:n,chainId:r,connector:s,...i}=e;let o;return typeof n=="object"&&n?.type==="local"?o=t.getClient({chainId:r}):o=await GS(t,{account:n??void 0,chainId:r,connector:s}),await Za(o,h7e,"writeContract")({...i,...n?{account:n}:{},chain:r?{id:r}:null})}function w7e(t){return t}ZS.type="injected";function ZS(t={}){const{shimDisconnect:e=!0,unstable_shimAsyncInject:n}=t;function r(){const c=t.target;if(typeof c=="function"){const l=c();if(l)return l}return typeof c=="object"?c:typeof c=="string"?{...b7e[c]??{id:c,name:`${c[0].toUpperCase()}${c.slice(1)}`,provider:`is${c[0].toUpperCase()}${c.slice(1)}`}}:{id:"injected",name:"Injected",provider(l){return l?.ethereum}}}let s,i,o,a;return c=>({get icon(){return r().icon},get id(){return r().id},get name(){return r().name},get supportsSimulation(){return!0},type:ZS.type,async setup(){const l=await this.getProvider();l?.on&&t.target&&(o||(o=this.onConnect.bind(this),l.on("connect",o)),s||(s=this.onAccountsChanged.bind(this),l.on("accountsChanged",s)))},async connect({chainId:l,isReconnecting:u}={}){const d=await this.getProvider();if(!d)throw new fh;let f=[];if(u)f=await this.getAccounts().catch(()=>[]);else if(e)try{f=(await d.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}))[0]?.caveats?.[0]?.value?.map(m=>wh(m)),f.length>0&&(f=await this.getAccounts())}catch(p){const m=p;if(m.code===ti.code)throw new ti(m);if(m.code===Zg.code)throw m}try{!f?.length&&!u&&(f=(await d.request({method:"eth_requestAccounts"})).map(y=>wh(y))),o&&(d.removeListener("connect",o),o=void 0),s||(s=this.onAccountsChanged.bind(this),d.on("accountsChanged",s)),i||(i=this.onChainChanged.bind(this),d.on("chainChanged",i)),a||(a=this.onDisconnect.bind(this),d.on("disconnect",a));let p=await this.getChainId();return l&&p!==l&&(p=(await this.switchChain({chainId:l}).catch(y=>{if(y.code===ti.code)throw y;return{id:p}}))?.id??p),e&&await c.storage?.removeItem(`${this.id}.disconnected`),t.target||await c.storage?.setItem("injected.connected",!0),{accounts:f,chainId:p}}catch(p){const m=p;throw m.code===ti.code?new ti(m):m.code===Zg.code?new Zg(m):m}},async disconnect(){const l=await this.getProvider();if(!l)throw new fh;i&&(l.removeListener("chainChanged",i),i=void 0),a&&(l.removeListener("disconnect",a),a=void 0),o||(o=this.onConnect.bind(this),l.on("connect",o));try{await mue(()=>l.request({method:"wallet_revokePermissions",params:[{eth_accounts:{}}]}),{timeout:100})}catch{}e&&await c.storage?.setItem(`${this.id}.disconnected`,!0),t.target||await c.storage?.removeItem("injected.connected")},async getAccounts(){const l=await this.getProvider();if(!l)throw new fh;return(await l.request({method:"eth_accounts"})).map(d=>wh(d))},async getChainId(){const l=await this.getProvider();if(!l)throw new fh;const u=await l.request({method:"eth_chainId"});return Number(u)},async getProvider(){if(typeof window>"u")return;let l;const u=r();return typeof u.provider=="function"?l=u.provider(window):typeof u.provider=="string"?l=FI(window,u.provider):l=u.provider,l&&!l.removeListener&&("off"in l&&typeof l.off=="function"?l.removeListener=l.off:l.removeListener=()=>{}),l},async isAuthorized(){try{if(e&&await c.storage?.getItem(`${this.id}.disconnected`)||!t.target&&!await c.storage?.getItem("injected.connected"))return!1;if(!await this.getProvider()){if(n!==void 0&&n!==!1){const f=async()=>(typeof window<"u"&&window.removeEventListener("ethereum#initialized",f),!!await this.getProvider()),p=typeof n=="number"?n:1e3;if(await Promise.race([...typeof window<"u"?[new Promise(y=>window.addEventListener("ethereum#initialized",()=>y(f()),{once:!0}))]:[],new Promise(y=>setTimeout(()=>y(f()),p))]))return!0}throw new fh}return!!(await lT(()=>this.getAccounts())).length}catch{return!1}},async switchChain({addEthereumChainParameter:l,chainId:u}){const d=await this.getProvider();if(!d)throw new fh;const f=c.chains.find(m=>m.id===u);if(!f)throw new df(new Uv);const p=new Promise(m=>{const y=b=>{"chainId"in b&&b.chainId===u&&(c.emitter.off("change",y),m())};c.emitter.on("change",y)});try{return await Promise.all([d.request({method:"wallet_switchEthereumChain",params:[{chainId:$n(u)}]}).then(async()=>{await this.getChainId()===u&&c.emitter.emit("change",{chainId:u})}),p]),f}catch(m){const y=m;if(y.code===4902||y?.data?.originalError?.code===4902)try{const{default:b,...v}=f.blockExplorers??{};let x;l?.blockExplorerUrls?x=l.blockExplorerUrls:b&&(x=[b.url,...Object.values(v).map(_=>_.url)]);let E;l?.rpcUrls?.length?E=l.rpcUrls:E=[f.rpcUrls.default?.http[0]??""];const A={blockExplorerUrls:x,chainId:$n(u),chainName:l?.chainName??f.name,iconUrls:l?.iconUrls,nativeCurrency:l?.nativeCurrency??f.nativeCurrency,rpcUrls:E};return await Promise.all([d.request({method:"wallet_addEthereumChain",params:[A]}).then(async()=>{if(await this.getChainId()===u)c.emitter.emit("change",{chainId:u});else throw new ti(new Error("User rejected switch after adding network."))}),p]),f}catch(b){throw new ti(b)}throw y.code===ti.code?new ti(y):new df(y)}},async onAccountsChanged(l){if(l.length===0)this.onDisconnect();else if(c.emitter.listenerCount("connect")){const u=(await this.getChainId()).toString();this.onConnect({chainId:u}),e&&await c.storage?.removeItem(`${this.id}.disconnected`)}else c.emitter.emit("change",{accounts:l.map(u=>wh(u))})},onChainChanged(l){const u=Number(l);c.emitter.emit("change",{chainId:u})},async onConnect(l){const u=await this.getAccounts();if(u.length===0)return;const d=Number(l.chainId);c.emitter.emit("connect",{accounts:u,chainId:d});const f=await this.getProvider();f&&(o&&(f.removeListener("connect",o),o=void 0),s||(s=this.onAccountsChanged.bind(this),f.on("accountsChanged",s)),i||(i=this.onChainChanged.bind(this),f.on("chainChanged",i)),a||(a=this.onDisconnect.bind(this),f.on("disconnect",a)))},async onDisconnect(l){const u=await this.getProvider();l&&l.code===1013&&u&&(await this.getAccounts()).length||(c.emitter.emit("disconnect"),u&&(i&&(u.removeListener("chainChanged",i),i=void 0),a&&(u.removeListener("disconnect",a),a=void 0),o||(o=this.onConnect.bind(this),u.on("connect",o))))}})}const b7e={coinbaseWallet:{id:"coinbaseWallet",name:"Coinbase Wallet",provider(t){return t?.coinbaseWalletExtension?t.coinbaseWalletExtension:FI(t,"isCoinbaseWallet")}},metaMask:{id:"metaMask",name:"MetaMask",provider(t){return FI(t,e=>{if(!e.isMetaMask||e.isBraveWallet&&!e._events&&!e._state)return!1;const n=["isApexWallet","isAvalanche","isBitKeep","isBlockWallet","isKuCoinWallet","isMathWallet","isOkxWallet","isOKExWallet","isOneInchIOSWallet","isOneInchAndroidWallet","isOpera","isPhantom","isPortal","isRabby","isTokenPocket","isTokenary","isUniswapWallet","isZerion"];for(const r of n)if(e[r])return!1;return!0})}},phantom:{id:"phantom",name:"Phantom",provider(t){return t?.phantom?.ethereum?t.phantom?.ethereum:FI(t,"isPhantom")}}};function FI(t,e){function n(s){return typeof e=="function"?e(s):typeof e=="string"?s[e]:!0}const r=t.ethereum;if(r?.providers)return r.providers.find(s=>n(s));if(r&&n(r))return r}function v7e(t){if(typeof window>"u")return;const e=n=>t(n.detail);return window.addEventListener("eip6963:announceProvider",e),window.dispatchEvent(new CustomEvent("eip6963:requestProvider")),()=>window.removeEventListener("eip6963:announceProvider",e)}function x7e(){const t=new Set;let e=[];const n=()=>v7e(s=>{e.some(({info:i})=>i.uuid===s.info.uuid)||(e=[...e,s],t.forEach(i=>i(e,{added:[s]})))});let r=n();return{_listeners(){return t},clear(){t.forEach(s=>s([],{removed:[...e]})),e=[]},destroy(){this.clear(),t.clear(),r?.()},findProvider({rdns:s}){return e.find(i=>i.info.rdns===s)},getProviders(){return e},reset(){this.clear(),r?.(),r=n()},subscribe(s,{emitImmediately:i}={}){return t.add(s),i&&s(e,{added:e}),()=>t.delete(s)}}}const E7e=t=>(e,n,r)=>{const s=r.subscribe;return r.subscribe=(o,a,c)=>{let l=o;if(a){const u=c?.equalityFn||Object.is;let d=o(r.getState());l=f=>{const p=o(f);if(!u(d,p)){const m=d;a(d=p,m)}},c?.fireImmediately&&a(d,d)}return s(l)},t(e,n,r)},C7e=E7e;function _7e(t,e){let n;try{n=t()}catch{return}return{getItem:s=>{var i;const o=c=>c===null?null:JSON.parse(c,void 0),a=(i=n.getItem(s))!=null?i:null;return a instanceof Promise?a.then(o):o(a)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const ZL=t=>e=>{try{const n=t(e);return n instanceof Promise?n:{then(r){return ZL(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return ZL(r)(n)}}}},S7e=(t,e)=>(n,r,s)=>{let i={storage:_7e(()=>localStorage),partialize:y=>y,version:0,merge:(y,b)=>({...b,...y}),...e},o=!1;const a=new Set,c=new Set;let l=i.storage;if(!l)return t((...y)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...y)},r,s);const u=()=>{const y=i.partialize({...r()});return l.setItem(i.name,{state:y,version:i.version})},d=s.setState;s.setState=(y,b)=>{d(y,b),u()};const f=t((...y)=>{n(...y),u()},r,s);s.getInitialState=()=>f;let p;const m=()=>{var y,b;if(!l)return;o=!1,a.forEach(x=>{var E;return x((E=r())!=null?E:f)});const v=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(y=r())!=null?y:f))||void 0;return ZL(l.getItem.bind(l))(i.name).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==i.version){if(i.migrate)return[!0,i.migrate(x.state,x.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,x.state];return[!1,void 0]}).then(x=>{var E;const[A,_]=x;if(p=i.merge(_,(E=r())!=null?E:f),n(p,!0),A)return u()}).then(()=>{v?.(p,void 0),p=r(),o=!0,c.forEach(x=>x(p))}).catch(x=>{v?.(void 0,x)})};return s.persist={setOptions:y=>{i={...i,...y},y.storage&&(l=y.storage)},clearStorage:()=>{l?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>m(),hasHydrated:()=>o,onHydrate:y=>(a.add(y),()=>{a.delete(y)}),onFinishHydration:y=>(c.add(y),()=>{c.delete(y)})},i.skipHydration||m(),p||f},A7e=S7e,aX=t=>{let e;const n=new Set,r=(l,u)=>{const d=typeof l=="function"?l(e):l;if(!Object.is(d,e)){const f=e;e=u??(typeof d!="object"||d===null)?d:Object.assign({},e,d),n.forEach(p=>p(e,f))}},s=()=>e,a={setState:r,getState:s,getInitialState:()=>c,subscribe:l=>(n.add(l),()=>n.delete(l))},c=e=t(r,s,a);return a},y$=t=>t?aX(t):aX;var Sde={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function s(c,l,u){this.fn=c,this.context=l,this.once=u||!1}function i(c,l,u,d,f){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new s(u,d||c,f),m=n?n+l:l;return c._events[m]?c._events[m].fn?c._events[m]=[c._events[m],p]:c._events[m].push(p):(c._events[m]=p,c._eventsCount++),c}function o(c,l){--c._eventsCount===0?c._events=new r:delete c._events[l]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],u,d;if(this._eventsCount===0)return l;for(d in u=this._events)e.call(u,d)&&l.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},a.prototype.listeners=function(l){var u=n?n+l:l,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,p=d.length,m=new Array(p);f{let s=r;return s?.__type==="bigint"&&(s=BigInt(s.value)),s?.__type==="Map"&&(s=new Map(s.value)),e?.(n,s)??s})}function cX(t,e){return t.slice(0,e).join(".")||"."}function lX(t,e){const{length:n}=t;for(let r=0;r{let o=i;return typeof o=="bigint"&&(o={__type:"bigint",value:i.toString()}),o instanceof Map&&(o={__type:"Map",value:Array.from(i.entries())}),e?.(s,o)??o},r),n??void 0)}function nz(t){const{deserialize:e=Ade,key:n="wagmi",serialize:r=Ide,storage:s=rz}=t;function i(o){return o instanceof Promise?o.then(a=>a).catch(()=>null):o}return{...s,key:n,async getItem(o,a){const c=s.getItem(`${n}.${o}`),l=await i(c);return l?e(l)??null:a??null},async setItem(o,a){const c=`${n}.${o}`;a===null?await i(s.removeItem(c)):await i(s.setItem(c,r(a)))},async removeItem(o){await i(s.removeItem(`${n}.${o}`))}}}const rz={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function R7e(){const t=typeof window<"u"&&window.localStorage?window.localStorage:rz;return{getItem(e){return t.getItem(e)},removeItem(e){t.removeItem(e)},setItem(e,n){try{t.setItem(e,n)}catch{}}}}const YL=256;let pA=YL,gA;function O7e(t=11){if(!gA||pA+t>YL*2){gA="",pA=0;for(let e=0;ei.chains),c=y$(()=>{const _=[],k=new Set;for(const B of i.connectors??[]){const W=l(B);if(_.push(W),!s&&W.rdns){const S=typeof W.rdns=="string"?[W.rdns]:W.rdns;for(const $ of S)k.add($)}}if(!s&&o){const B=o.getProviders();for(const W of B)k.has(W.info.rdns)||_.push(l(u(W)))}return _});function l(_){const k=P7e(O7e()),B={..._({emitter:k,chains:a.getState(),storage:n,transports:i.transports}),emitter:k,uid:k.uid};return k.on("connect",E),B.setup?.(),B}function u(_){const{info:k}=_,B=_.provider;return ZS({target:{...k,id:k.rdns,provider:B}})}const d=new Map;function f(_={}){const k=_.chainId??b.getState().chainId,B=a.getState().find(S=>S.id===k);if(_.chainId&&!B)throw new Uv;{const S=d.get(b.getState().chainId);if(S&&!B)return S;if(!B)throw new Uv}{const S=d.get(k);if(S)return S}let W;if(i.client)W=i.client({chain:B});else{const S=B.id,$=a.getState().map(j=>j.id),R={},M=Object.entries(i);for(const[j,z]of M)if(!(j==="chains"||j==="client"||j==="connectors"||j==="transports"))if(typeof z=="object")if(S in z)R[j]=z[S];else{if($.some(T=>T in z))continue;R[j]=z}else R[j]=z;W=cde({...R,chain:B,batch:R.batch??{multicall:!0},transport:j=>i.transports[S]({...j,connectors:c})})}return d.set(k,W),W}function p(){return{chainId:a.getState()[0].id,connections:new Map,current:null,status:"disconnected"}}let m;const y="0.0.0-canary-";yE.startsWith(y)?m=Number.parseInt(yE.replace(y,"")):m=Number.parseInt(yE.split(".")[0]??"0");const b=y$(C7e(n?A7e(p,{migrate(_,k){if(k===m)return _;const B=p(),W=v(_,B.chainId);return{...B,chainId:W}},name:"store",partialize(_){return{connections:{__type:"Map",value:Array.from(_.connections.entries()).map(([k,B])=>{const{id:W,name:S,type:$,uid:R}=B.connector;return[k,{...B,connector:{id:W,name:S,type:$,uid:R}}]})},chainId:_.chainId,current:_.current}},merge(_,k){typeof _=="object"&&_&&"status"in _&&delete _.status;const B=v(_,k.chainId);return{...k,..._,chainId:B}},skipHydration:s,storage:n,version:m}):p));b.setState(p());function v(_,k){return _&&typeof _=="object"&&"chainId"in _&&typeof _.chainId=="number"&&a.getState().some(B=>B.id===_.chainId)?_.chainId:k}r&&b.subscribe(({connections:_,current:k})=>k?_.get(k)?.chainId:void 0,_=>{if(a.getState().some(B=>B.id===_))return b.setState(B=>({...B,chainId:_??B.chainId}))}),o?.subscribe(_=>{const k=new Set,B=new Set;for(const S of c.getState())if(k.add(S.id),S.rdns){const $=typeof S.rdns=="string"?[S.rdns]:S.rdns;for(const R of $)B.add(R)}const W=[];for(const S of _){if(B.has(S.info.rdns))continue;const $=l(u(S));k.has($.id)||W.push($)}n&&!b.persist.hasHydrated()||c.setState(S=>[...S,...W],!0)});function x(_){b.setState(k=>{const B=k.connections.get(_.uid);return B?{...k,connections:new Map(k.connections).set(_.uid,{accounts:_.accounts??B.accounts,chainId:_.chainId??B.chainId,connector:B.connector})}:k})}function E(_){b.getState().status==="connecting"||b.getState().status==="reconnecting"||b.setState(k=>{const B=c.getState().find(W=>W.uid===_.uid);return B?(B.emitter.listenerCount("connect")&&B.emitter.off("connect",x),B.emitter.listenerCount("change")||B.emitter.on("change",x),B.emitter.listenerCount("disconnect")||B.emitter.on("disconnect",A),{...k,connections:new Map(k.connections).set(_.uid,{accounts:_.accounts,chainId:_.chainId,connector:B}),current:_.uid,status:"connected"}):k})}function A(_){b.setState(k=>{const B=k.connections.get(_.uid);if(B){const S=B.connector;S.emitter.listenerCount("change")&&B.connector.emitter.off("change",x),S.emitter.listenerCount("disconnect")&&B.connector.emitter.off("disconnect",A),S.emitter.listenerCount("connect")||B.connector.emitter.on("connect",E)}if(k.connections.delete(_.uid),k.connections.size===0)return{...k,connections:new Map,current:null,status:"disconnected"};const W=k.connections.values().next().value;return{...k,connections:new Map(k.connections),current:W.connector.uid}})}return{get chains(){return a.getState()},get connectors(){return c.getState()},storage:n,getClient:f,get state(){return b.getState()},setState(_){let k;typeof _=="function"?k=_(b.getState()):k=_;const B=p();typeof k!="object"&&(k=B),Object.keys(B).some(S=>!(S in k))&&(k=B),b.setState(k,!0)},subscribe(_,k,B){return b.subscribe(_,k,B?{...B,fireImmediately:B.emitImmediately}:void 0)},_internal:{mipd:o,store:b,ssr:!!s,syncConnectedChain:r,transports:i.transports,chains:{setState(_){const k=typeof _=="function"?_(a.getState()):_;if(k.length!==0)return a.setState(k,!0)},subscribe(_){return a.subscribe(_)}},connectors:{providerDetailToConnector:u,setup:l,setState(_){return c.setState(typeof _=="function"?_(c.getState()):_,!0)},subscribe(_){return c.subscribe(_)}},events:{change:x,connect:E,disconnect:A}}}}function Nde(t,e){const{initialState:n,reconnectOnMount:r}=e;return n&&!t._internal.store.persist.hasHydrated()&&t.setState({...n,chainId:t.chains.some(s=>s.id===n.chainId)?n.chainId:t.chains[0].id,connections:r?n.connections:new Map,status:r?"reconnecting":"disconnected"}),{async onMount(){t._internal.ssr&&(await t._internal.store.persist.rehydrate(),t._internal.mipd&&t._internal.connectors.setState(s=>{const i=new Set;for(const c of s??[])if(c.rdns){const l=Array.isArray(c.rdns)?c.rdns:[c.rdns];for(const u of l)i.add(u)}const o=[],a=t._internal.mipd?.getProviders()??[];for(const c of a){if(i.has(c.info.rdns))continue;const l=t._internal.connectors.providerDetailToConnector(c),u=t._internal.connectors.setup(l);o.push(u)}return[...s,...o]})),r?hT(t):t.storage&&t.setState(s=>({...s,connections:new Map}))}}}const $7e=Object.freeze(Object.defineProperty({__proto__:null,BaseError:wp,ChainNotConfiguredError:Uv,ConnectorAccountNotFoundError:sde,ConnectorAlreadyConnectedError:nde,ConnectorChainMismatchError:ide,ConnectorNotConnectedError:rde,ConnectorUnavailableReconnectingError:ode,ProviderNotFoundError:fh,SwitchChainNotSupportedError:wde,connect:UI,createConfig:Tde,createConnector:w7e,createStorage:nz,custom:lde,deepEqual:Fv,deserialize:Ade,disconnect:qL,estimateGas:dde,fetchBalance:KL,fetchEnsName:fT,getAccount:cv,getBalance:KL,getConnections:Md,getConnectorClient:GS,getEnsName:fT,http:B2,hydrate:Nde,injected:ZS,multicall:fde,noopStorage:rz,prepareTransactionRequest:gde,readContract:hde,readContracts:pde,reconnect:hT,sendTransaction:mde,serialize:Ide,signMessage:yde,switchChain:pT,switchNetwork:pT,verifyMessage:bde,version:yE,waitForTransaction:GL,waitForTransactionReceipt:GL,watchAccount:vde,watchConnections:xde,watchConnectors:Ede,watchPendingTransactions:Cde,writeContract:_de},Symbol.toStringTag,{value:"Module"}));var D7e={},rx={};rx.byteLength=B7e;rx.toByteArray=F7e;rx.fromByteArray=W7e;var Wd=[],ml=[],M7e=typeof Uint8Array<"u"?Uint8Array:Array,w$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Vw=0,L7e=w$.length;Vw0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function B7e(t){var e=Pde(t),n=e[0],r=e[1];return(n+r)*3/4-r}function U7e(t,e,n){return(e+n)*3/4-n}function F7e(t){var e,n=Pde(t),r=n[0],s=n[1],i=new M7e(U7e(t,r,s)),o=0,a=s>0?r-4:r,c;for(c=0;c>16&255,i[o++]=e>>8&255,i[o++]=e&255;return s===2&&(e=ml[t.charCodeAt(c)]<<2|ml[t.charCodeAt(c+1)]>>4,i[o++]=e&255),s===1&&(e=ml[t.charCodeAt(c)]<<10|ml[t.charCodeAt(c+1)]<<4|ml[t.charCodeAt(c+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function j7e(t){return Wd[t>>18&63]+Wd[t>>12&63]+Wd[t>>6&63]+Wd[t&63]}function z7e(t,e,n){for(var r,s=[],i=e;ia?a:o+i));return r===1?(e=t[n-1],s.push(Wd[e>>2]+Wd[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],s.push(Wd[e>>10]+Wd[e>>4&63]+Wd[e<<2&63]+"=")),s.join("")}var sz={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */sz.read=function(t,e,n,r,s){var i,o,a=s*8-r-1,c=(1<>1,u=-7,d=n?s-1:0,f=n?-1:1,p=t[e+d];for(d+=f,i=p&(1<<-u)-1,p>>=-u,u+=a;u>0;i=i*256+t[e+d],d+=f,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=r;u>0;o=o*256+t[e+d],d+=f,u-=8);if(i===0)i=1-l;else{if(i===c)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,r),i=i-l}return(p?-1:1)*o*Math.pow(2,i-r)};sz.write=function(t,e,n,r,s,i){var o,a,c,l=i*8-s-1,u=(1<>1,f=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:i-1,m=r?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+d>=1?e+=f/c:e+=f*Math.pow(2,1-d),e*c>=2&&(o++,c/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(e*c-1)*Math.pow(2,s),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,s),o=0));s>=8;t[n+p]=a&255,p+=m,a/=256,s-=8);for(o=o<0;t[n+p]=o&255,p+=m,o/=256,l-=8);t[n+p-m]|=y*128};/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */(function(t){const e=rx,n=sz,r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=a,t.SlowBuffer=x,t.INSPECT_MAX_BYTES=50;const s=2147483647;t.kMaxLength=s,a.TYPED_ARRAY_SUPPORT=i(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{const Z=new Uint8Array(1),O={foo:function(){return 42}};return Object.setPrototypeOf(O,Uint8Array.prototype),Object.setPrototypeOf(Z,O),Z.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(Z){if(Z>s)throw new RangeError('The value "'+Z+'" is invalid for option "size"');const O=new Uint8Array(Z);return Object.setPrototypeOf(O,a.prototype),O}function a(Z,O,F){if(typeof Z=="number"){if(typeof O=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(Z)}return c(Z,O,F)}a.poolSize=8192;function c(Z,O,F){if(typeof Z=="string")return f(Z,O);if(ArrayBuffer.isView(Z))return m(Z);if(Z==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Z);if($e(Z,ArrayBuffer)||Z&&$e(Z.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&($e(Z,SharedArrayBuffer)||Z&&$e(Z.buffer,SharedArrayBuffer)))return y(Z,O,F);if(typeof Z=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const ne=Z.valueOf&&Z.valueOf();if(ne!=null&&ne!==Z)return a.from(ne,O,F);const he=b(Z);if(he)return he;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof Z[Symbol.toPrimitive]=="function")return a.from(Z[Symbol.toPrimitive]("string"),O,F);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Z)}a.from=function(Z,O,F){return c(Z,O,F)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function l(Z){if(typeof Z!="number")throw new TypeError('"size" argument must be of type number');if(Z<0)throw new RangeError('The value "'+Z+'" is invalid for option "size"')}function u(Z,O,F){return l(Z),Z<=0?o(Z):O!==void 0?typeof F=="string"?o(Z).fill(O,F):o(Z).fill(O):o(Z)}a.alloc=function(Z,O,F){return u(Z,O,F)};function d(Z){return l(Z),o(Z<0?0:v(Z)|0)}a.allocUnsafe=function(Z){return d(Z)},a.allocUnsafeSlow=function(Z){return d(Z)};function f(Z,O){if((typeof O!="string"||O==="")&&(O="utf8"),!a.isEncoding(O))throw new TypeError("Unknown encoding: "+O);const F=E(Z,O)|0;let ne=o(F);const he=ne.write(Z,O);return he!==F&&(ne=ne.slice(0,he)),ne}function p(Z){const O=Z.length<0?0:v(Z.length)|0,F=o(O);for(let ne=0;ne=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return Z|0}function x(Z){return+Z!=Z&&(Z=0),a.alloc(+Z)}a.isBuffer=function(O){return O!=null&&O._isBuffer===!0&&O!==a.prototype},a.compare=function(O,F){if($e(O,Uint8Array)&&(O=a.from(O,O.offset,O.byteLength)),$e(F,Uint8Array)&&(F=a.from(F,F.offset,F.byteLength)),!a.isBuffer(O)||!a.isBuffer(F))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(O===F)return 0;let ne=O.length,he=F.length;for(let Te=0,Fe=Math.min(ne,he);Tehe.length?(a.isBuffer(Fe)||(Fe=a.from(Fe)),Fe.copy(he,Te)):Uint8Array.prototype.set.call(he,Fe,Te);else if(a.isBuffer(Fe))Fe.copy(he,Te);else throw new TypeError('"list" argument must be an Array of Buffers');Te+=Fe.length}return he};function E(Z,O){if(a.isBuffer(Z))return Z.length;if(ArrayBuffer.isView(Z)||$e(Z,ArrayBuffer))return Z.byteLength;if(typeof Z!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof Z);const F=Z.length,ne=arguments.length>2&&arguments[2]===!0;if(!ne&&F===0)return 0;let he=!1;for(;;)switch(O){case"ascii":case"latin1":case"binary":return F;case"utf8":case"utf-8":return pe(Z).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F*2;case"hex":return F>>>1;case"base64":return ae(Z).length;default:if(he)return ne?-1:pe(Z).length;O=(""+O).toLowerCase(),he=!0}}a.byteLength=E;function A(Z,O,F){let ne=!1;if((O===void 0||O<0)&&(O=0),O>this.length||((F===void 0||F>this.length)&&(F=this.length),F<=0)||(F>>>=0,O>>>=0,F<=O))return"";for(Z||(Z="utf8");;)switch(Z){case"hex":return P(this,O,F);case"utf8":case"utf-8":return z(this,O,F);case"ascii":return U(this,O,F);case"latin1":case"binary":return L(this,O,F);case"base64":return j(this,O,F);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,O,F);default:if(ne)throw new TypeError("Unknown encoding: "+Z);Z=(Z+"").toLowerCase(),ne=!0}}a.prototype._isBuffer=!0;function _(Z,O,F){const ne=Z[O];Z[O]=Z[F],Z[F]=ne}a.prototype.swap16=function(){const O=this.length;if(O%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let F=0;FF&&(O+=" ... "),""},r&&(a.prototype[r]=a.prototype.inspect),a.prototype.compare=function(O,F,ne,he,Te){if($e(O,Uint8Array)&&(O=a.from(O,O.offset,O.byteLength)),!a.isBuffer(O))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof O);if(F===void 0&&(F=0),ne===void 0&&(ne=O?O.length:0),he===void 0&&(he=0),Te===void 0&&(Te=this.length),F<0||ne>O.length||he<0||Te>this.length)throw new RangeError("out of range index");if(he>=Te&&F>=ne)return 0;if(he>=Te)return-1;if(F>=ne)return 1;if(F>>>=0,ne>>>=0,he>>>=0,Te>>>=0,this===O)return 0;let Fe=Te-he,Bt=ne-F;const vn=Math.min(Fe,Bt),Kt=this.slice(he,Te),Dn=O.slice(F,ne);for(let bt=0;bt2147483647?F=2147483647:F<-2147483648&&(F=-2147483648),F=+F,Re(F)&&(F=he?0:Z.length-1),F<0&&(F=Z.length+F),F>=Z.length){if(he)return-1;F=Z.length-1}else if(F<0)if(he)F=0;else return-1;if(typeof O=="string"&&(O=a.from(O,ne)),a.isBuffer(O))return O.length===0?-1:B(Z,O,F,ne,he);if(typeof O=="number")return O=O&255,typeof Uint8Array.prototype.indexOf=="function"?he?Uint8Array.prototype.indexOf.call(Z,O,F):Uint8Array.prototype.lastIndexOf.call(Z,O,F):B(Z,[O],F,ne,he);throw new TypeError("val must be string, number or Buffer")}function B(Z,O,F,ne,he){let Te=1,Fe=Z.length,Bt=O.length;if(ne!==void 0&&(ne=String(ne).toLowerCase(),ne==="ucs2"||ne==="ucs-2"||ne==="utf16le"||ne==="utf-16le")){if(Z.length<2||O.length<2)return-1;Te=2,Fe/=2,Bt/=2,F/=2}function vn(Dn,bt){return Te===1?Dn[bt]:Dn.readUInt16BE(bt*Te)}let Kt;if(he){let Dn=-1;for(Kt=F;KtFe&&(F=Fe-Bt),Kt=F;Kt>=0;Kt--){let Dn=!0;for(let bt=0;bthe&&(ne=he)):ne=he;const Te=O.length;ne>Te/2&&(ne=Te/2);let Fe;for(Fe=0;Fe>>0,isFinite(ne)?(ne=ne>>>0,he===void 0&&(he="utf8")):(he=ne,ne=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const Te=this.length-F;if((ne===void 0||ne>Te)&&(ne=Te),O.length>0&&(ne<0||F<0)||F>this.length)throw new RangeError("Attempt to write outside buffer bounds");he||(he="utf8");let Fe=!1;for(;;)switch(he){case"hex":return W(this,O,F,ne);case"utf8":case"utf-8":return S(this,O,F,ne);case"ascii":case"latin1":case"binary":return $(this,O,F,ne);case"base64":return R(this,O,F,ne);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,O,F,ne);default:if(Fe)throw new TypeError("Unknown encoding: "+he);he=(""+he).toLowerCase(),Fe=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function j(Z,O,F){return O===0&&F===Z.length?e.fromByteArray(Z):e.fromByteArray(Z.slice(O,F))}function z(Z,O,F){F=Math.min(Z.length,F);const ne=[];let he=O;for(;he239?4:Te>223?3:Te>191?2:1;if(he+Bt<=F){let vn,Kt,Dn,bt;switch(Bt){case 1:Te<128&&(Fe=Te);break;case 2:vn=Z[he+1],(vn&192)===128&&(bt=(Te&31)<<6|vn&63,bt>127&&(Fe=bt));break;case 3:vn=Z[he+1],Kt=Z[he+2],(vn&192)===128&&(Kt&192)===128&&(bt=(Te&15)<<12|(vn&63)<<6|Kt&63,bt>2047&&(bt<55296||bt>57343)&&(Fe=bt));break;case 4:vn=Z[he+1],Kt=Z[he+2],Dn=Z[he+3],(vn&192)===128&&(Kt&192)===128&&(Dn&192)===128&&(bt=(Te&15)<<18|(vn&63)<<12|(Kt&63)<<6|Dn&63,bt>65535&&bt<1114112&&(Fe=bt))}}Fe===null?(Fe=65533,Bt=1):Fe>65535&&(Fe-=65536,ne.push(Fe>>>10&1023|55296),Fe=56320|Fe&1023),ne.push(Fe),he+=Bt}return T(ne)}const N=4096;function T(Z){const O=Z.length;if(O<=N)return String.fromCharCode.apply(String,Z);let F="",ne=0;for(;nene)&&(F=ne);let he="";for(let Te=O;Tene&&(O=ne),F<0?(F+=ne,F<0&&(F=0)):F>ne&&(F=ne),FF)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(O,F,ne){O=O>>>0,F=F>>>0,ne||Y(O,F,this.length);let he=this[O],Te=1,Fe=0;for(;++Fe>>0,F=F>>>0,ne||Y(O,F,this.length);let he=this[O+--F],Te=1;for(;F>0&&(Te*=256);)he+=this[O+--F]*Te;return he},a.prototype.readUint8=a.prototype.readUInt8=function(O,F){return O=O>>>0,F||Y(O,1,this.length),this[O]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(O,F){return O=O>>>0,F||Y(O,2,this.length),this[O]|this[O+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(O,F){return O=O>>>0,F||Y(O,2,this.length),this[O]<<8|this[O+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(O,F){return O=O>>>0,F||Y(O,4,this.length),(this[O]|this[O+1]<<8|this[O+2]<<16)+this[O+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(O,F){return O=O>>>0,F||Y(O,4,this.length),this[O]*16777216+(this[O+1]<<16|this[O+2]<<8|this[O+3])},a.prototype.readBigUInt64LE=Je(function(O){O=O>>>0,Ie(O,"offset");const F=this[O],ne=this[O+7];(F===void 0||ne===void 0)&&ge(O,this.length-8);const he=F+this[++O]*2**8+this[++O]*2**16+this[++O]*2**24,Te=this[++O]+this[++O]*2**8+this[++O]*2**16+ne*2**24;return BigInt(he)+(BigInt(Te)<>>0,Ie(O,"offset");const F=this[O],ne=this[O+7];(F===void 0||ne===void 0)&&ge(O,this.length-8);const he=F*2**24+this[++O]*2**16+this[++O]*2**8+this[++O],Te=this[++O]*2**24+this[++O]*2**16+this[++O]*2**8+ne;return(BigInt(he)<>>0,F=F>>>0,ne||Y(O,F,this.length);let he=this[O],Te=1,Fe=0;for(;++Fe=Te&&(he-=Math.pow(2,8*F)),he},a.prototype.readIntBE=function(O,F,ne){O=O>>>0,F=F>>>0,ne||Y(O,F,this.length);let he=F,Te=1,Fe=this[O+--he];for(;he>0&&(Te*=256);)Fe+=this[O+--he]*Te;return Te*=128,Fe>=Te&&(Fe-=Math.pow(2,8*F)),Fe},a.prototype.readInt8=function(O,F){return O=O>>>0,F||Y(O,1,this.length),this[O]&128?(255-this[O]+1)*-1:this[O]},a.prototype.readInt16LE=function(O,F){O=O>>>0,F||Y(O,2,this.length);const ne=this[O]|this[O+1]<<8;return ne&32768?ne|4294901760:ne},a.prototype.readInt16BE=function(O,F){O=O>>>0,F||Y(O,2,this.length);const ne=this[O+1]|this[O]<<8;return ne&32768?ne|4294901760:ne},a.prototype.readInt32LE=function(O,F){return O=O>>>0,F||Y(O,4,this.length),this[O]|this[O+1]<<8|this[O+2]<<16|this[O+3]<<24},a.prototype.readInt32BE=function(O,F){return O=O>>>0,F||Y(O,4,this.length),this[O]<<24|this[O+1]<<16|this[O+2]<<8|this[O+3]},a.prototype.readBigInt64LE=Je(function(O){O=O>>>0,Ie(O,"offset");const F=this[O],ne=this[O+7];(F===void 0||ne===void 0)&&ge(O,this.length-8);const he=this[O+4]+this[O+5]*2**8+this[O+6]*2**16+(ne<<24);return(BigInt(he)<>>0,Ie(O,"offset");const F=this[O],ne=this[O+7];(F===void 0||ne===void 0)&&ge(O,this.length-8);const he=(F<<24)+this[++O]*2**16+this[++O]*2**8+this[++O];return(BigInt(he)<>>0,F||Y(O,4,this.length),n.read(this,O,!0,23,4)},a.prototype.readFloatBE=function(O,F){return O=O>>>0,F||Y(O,4,this.length),n.read(this,O,!1,23,4)},a.prototype.readDoubleLE=function(O,F){return O=O>>>0,F||Y(O,8,this.length),n.read(this,O,!0,52,8)},a.prototype.readDoubleBE=function(O,F){return O=O>>>0,F||Y(O,8,this.length),n.read(this,O,!1,52,8)};function re(Z,O,F,ne,he,Te){if(!a.isBuffer(Z))throw new TypeError('"buffer" argument must be a Buffer instance');if(O>he||OZ.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(O,F,ne,he){if(O=+O,F=F>>>0,ne=ne>>>0,!he){const Bt=Math.pow(2,8*ne)-1;re(this,O,F,ne,Bt,0)}let Te=1,Fe=0;for(this[F]=O&255;++Fe>>0,ne=ne>>>0,!he){const Bt=Math.pow(2,8*ne)-1;re(this,O,F,ne,Bt,0)}let Te=ne-1,Fe=1;for(this[F+Te]=O&255;--Te>=0&&(Fe*=256);)this[F+Te]=O/Fe&255;return F+ne},a.prototype.writeUint8=a.prototype.writeUInt8=function(O,F,ne){return O=+O,F=F>>>0,ne||re(this,O,F,1,255,0),this[F]=O&255,F+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(O,F,ne){return O=+O,F=F>>>0,ne||re(this,O,F,2,65535,0),this[F]=O&255,this[F+1]=O>>>8,F+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(O,F,ne){return O=+O,F=F>>>0,ne||re(this,O,F,2,65535,0),this[F]=O>>>8,this[F+1]=O&255,F+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(O,F,ne){return O=+O,F=F>>>0,ne||re(this,O,F,4,4294967295,0),this[F+3]=O>>>24,this[F+2]=O>>>16,this[F+1]=O>>>8,this[F]=O&255,F+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(O,F,ne){return O=+O,F=F>>>0,ne||re(this,O,F,4,4294967295,0),this[F]=O>>>24,this[F+1]=O>>>16,this[F+2]=O>>>8,this[F+3]=O&255,F+4};function de(Z,O,F,ne,he){Ae(O,ne,he,Z,F,7);let Te=Number(O&BigInt(4294967295));Z[F++]=Te,Te=Te>>8,Z[F++]=Te,Te=Te>>8,Z[F++]=Te,Te=Te>>8,Z[F++]=Te;let Fe=Number(O>>BigInt(32)&BigInt(4294967295));return Z[F++]=Fe,Fe=Fe>>8,Z[F++]=Fe,Fe=Fe>>8,Z[F++]=Fe,Fe=Fe>>8,Z[F++]=Fe,F}function fe(Z,O,F,ne,he){Ae(O,ne,he,Z,F,7);let Te=Number(O&BigInt(4294967295));Z[F+7]=Te,Te=Te>>8,Z[F+6]=Te,Te=Te>>8,Z[F+5]=Te,Te=Te>>8,Z[F+4]=Te;let Fe=Number(O>>BigInt(32)&BigInt(4294967295));return Z[F+3]=Fe,Fe=Fe>>8,Z[F+2]=Fe,Fe=Fe>>8,Z[F+1]=Fe,Fe=Fe>>8,Z[F]=Fe,F+8}a.prototype.writeBigUInt64LE=Je(function(O,F=0){return de(this,O,F,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Je(function(O,F=0){return fe(this,O,F,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(O,F,ne,he){if(O=+O,F=F>>>0,!he){const vn=Math.pow(2,8*ne-1);re(this,O,F,ne,vn-1,-vn)}let Te=0,Fe=1,Bt=0;for(this[F]=O&255;++Te>0)-Bt&255;return F+ne},a.prototype.writeIntBE=function(O,F,ne,he){if(O=+O,F=F>>>0,!he){const vn=Math.pow(2,8*ne-1);re(this,O,F,ne,vn-1,-vn)}let Te=ne-1,Fe=1,Bt=0;for(this[F+Te]=O&255;--Te>=0&&(Fe*=256);)O<0&&Bt===0&&this[F+Te+1]!==0&&(Bt=1),this[F+Te]=(O/Fe>>0)-Bt&255;return F+ne},a.prototype.writeInt8=function(O,F,ne){return O=+O,F=F>>>0,ne||re(this,O,F,1,127,-128),O<0&&(O=255+O+1),this[F]=O&255,F+1},a.prototype.writeInt16LE=function(O,F,ne){return O=+O,F=F>>>0,ne||re(this,O,F,2,32767,-32768),this[F]=O&255,this[F+1]=O>>>8,F+2},a.prototype.writeInt16BE=function(O,F,ne){return O=+O,F=F>>>0,ne||re(this,O,F,2,32767,-32768),this[F]=O>>>8,this[F+1]=O&255,F+2},a.prototype.writeInt32LE=function(O,F,ne){return O=+O,F=F>>>0,ne||re(this,O,F,4,2147483647,-2147483648),this[F]=O&255,this[F+1]=O>>>8,this[F+2]=O>>>16,this[F+3]=O>>>24,F+4},a.prototype.writeInt32BE=function(O,F,ne){return O=+O,F=F>>>0,ne||re(this,O,F,4,2147483647,-2147483648),O<0&&(O=4294967295+O+1),this[F]=O>>>24,this[F+1]=O>>>16,this[F+2]=O>>>8,this[F+3]=O&255,F+4},a.prototype.writeBigInt64LE=Je(function(O,F=0){return de(this,O,F,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Je(function(O,F=0){return fe(this,O,F,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ve(Z,O,F,ne,he,Te){if(F+ne>Z.length)throw new RangeError("Index out of range");if(F<0)throw new RangeError("Index out of range")}function Ee(Z,O,F,ne,he){return O=+O,F=F>>>0,he||ve(Z,O,F,4),n.write(Z,O,F,ne,23,4),F+4}a.prototype.writeFloatLE=function(O,F,ne){return Ee(this,O,F,!0,ne)},a.prototype.writeFloatBE=function(O,F,ne){return Ee(this,O,F,!1,ne)};function oe(Z,O,F,ne,he){return O=+O,F=F>>>0,he||ve(Z,O,F,8),n.write(Z,O,F,ne,52,8),F+8}a.prototype.writeDoubleLE=function(O,F,ne){return oe(this,O,F,!0,ne)},a.prototype.writeDoubleBE=function(O,F,ne){return oe(this,O,F,!1,ne)},a.prototype.copy=function(O,F,ne,he){if(!a.isBuffer(O))throw new TypeError("argument should be a Buffer");if(ne||(ne=0),!he&&he!==0&&(he=this.length),F>=O.length&&(F=O.length),F||(F=0),he>0&&he=this.length)throw new RangeError("Index out of range");if(he<0)throw new RangeError("sourceEnd out of bounds");he>this.length&&(he=this.length),O.length-F>>0,ne=ne===void 0?this.length:ne>>>0,O||(O=0);let Te;if(typeof O=="number")for(Te=F;Te2**32?he=V(String(F)):typeof F=="bigint"&&(he=String(F),(F>BigInt(2)**BigInt(32)||F<-(BigInt(2)**BigInt(32)))&&(he=V(he)),he+="n"),ne+=` It must be ${O}. Received ${he}`,ne},RangeError);function V(Z){let O="",F=Z.length;const ne=Z[0]==="-"?1:0;for(;F>=ne+4;F-=3)O=`_${Z.slice(F-3,F)}${O}`;return`${Z.slice(0,F)}${O}`}function we(Z,O,F){Ie(O,"offset"),(Z[O]===void 0||Z[O+F]===void 0)&&ge(O,Z.length-(F+1))}function Ae(Z,O,F,ne,he,Te){if(Z>F||Z= 0${Fe} and < 2${Fe} ** ${(Te+1)*8}${Fe}`:Bt=`>= -(2${Fe} ** ${(Te+1)*8-1}${Fe}) and < 2 ** ${(Te+1)*8-1}${Fe}`,new Oe.ERR_OUT_OF_RANGE("value",Bt,Z)}we(ne,he,Te)}function Ie(Z,O){if(typeof Z!="number")throw new Oe.ERR_INVALID_ARG_TYPE(O,"number",Z)}function ge(Z,O,F){throw Math.floor(Z)!==Z?(Ie(Z,F),new Oe.ERR_OUT_OF_RANGE("offset","an integer",Z)):O<0?new Oe.ERR_BUFFER_OUT_OF_BOUNDS:new Oe.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${O}`,Z)}const Me=/[^+/0-9A-Za-z-_]/g;function be(Z){if(Z=Z.split("=")[0],Z=Z.trim().replace(Me,""),Z.length<2)return"";for(;Z.length%4!==0;)Z=Z+"=";return Z}function pe(Z,O){O=O||1/0;let F;const ne=Z.length;let he=null;const Te=[];for(let Fe=0;Fe55295&&F<57344){if(!he){if(F>56319){(O-=3)>-1&&Te.push(239,191,189);continue}else if(Fe+1===ne){(O-=3)>-1&&Te.push(239,191,189);continue}he=F;continue}if(F<56320){(O-=3)>-1&&Te.push(239,191,189),he=F;continue}F=(he-55296<<10|F-56320)+65536}else he&&(O-=3)>-1&&Te.push(239,191,189);if(he=null,F<128){if((O-=1)<0)break;Te.push(F)}else if(F<2048){if((O-=2)<0)break;Te.push(F>>6|192,F&63|128)}else if(F<65536){if((O-=3)<0)break;Te.push(F>>12|224,F>>6&63|128,F&63|128)}else if(F<1114112){if((O-=4)<0)break;Te.push(F>>18|240,F>>12&63|128,F>>6&63|128,F&63|128)}else throw new Error("Invalid code point")}return Te}function J(Z){const O=[];for(let F=0;F>8,he=F%256,Te.push(he),Te.push(ne);return Te}function ae(Z){return e.toByteArray(be(Z))}function Pe(Z,O,F,ne){let he;for(he=0;he=O.length||he>=Z.length);++he)O[he+F]=Z[he];return he}function $e(Z,O){return Z instanceof O||Z!=null&&Z.constructor!=null&&Z.constructor.name!=null&&Z.constructor.name===O.name}function Re(Z){return Z!==Z}const ut=function(){const Z="0123456789abcdef",O=new Array(256);for(let F=0;F<16;++F){const ne=F*16;for(let he=0;he<16;++he)O[ne+he]=Z[F]+Z[he]}return O}();function Je(Z){return typeof BigInt>"u"?ft:Z}function ft(){throw new Error("BigInt not supported")}})(D7e);const V7e=Symbol(),iz=Symbol(),U2="a",kde="f",uX="p",Rde="c",Ode="t",oz="h",wE="w",az="o",cz="k";let H7e=(t,e)=>new Proxy(t,e);const XL=Object.getPrototypeOf,QL=new WeakMap,$de=t=>t&&(QL.has(t)?QL.get(t):XL(t)===Object.prototype||XL(t)===Array.prototype),gT=t=>typeof t=="object"&&t!==null,q7e=t=>Object.values(Object.getOwnPropertyDescriptors(t)).some(e=>!e.configurable&&!e.writable),K7e=t=>{if(Array.isArray(t))return Array.from(t);const e=Object.getOwnPropertyDescriptors(t);return Object.values(e).forEach(n=>{n.configurable=!0}),Object.create(XL(t),e)},G7e=(t,e)=>{const n={[kde]:e};let r=!1;const s=(a,c)=>{if(!r){let l=n[U2].get(t);if(l||(l={},n[U2].set(t,l)),a===wE)l[wE]=!0;else{let u=l[a];u||(u=new Set,l[a]=u),u.add(c)}}},i=()=>{r=!0,n[U2].delete(t)},o={get(a,c){return c===iz?t:(s(cz,c),Dde(Reflect.get(a,c),n[U2],n[Rde],n[Ode]))},has(a,c){return c===V7e?(i(),!0):(s(oz,c),Reflect.has(a,c))},getOwnPropertyDescriptor(a,c){return s(az,c),Reflect.getOwnPropertyDescriptor(a,c)},ownKeys(a){return s(wE),Reflect.ownKeys(a)}};return e&&(o.set=o.deleteProperty=()=>!1),[o,n]},lz=t=>t[iz]||t,Dde=(t,e,n,r)=>{if(!$de(t))return t;let s=r&&r.get(t);if(!s){const c=lz(t);q7e(c)?s=[c,K7e(c)]:s=[c],r?.set(t,s)}const[i,o]=s;let a=n&&n.get(i);return(!a||a[1][kde]!==!!o)&&(a=G7e(i,!!o),a[1][uX]=H7e(o||i,a[0]),n&&n.set(i,a)),a[1][U2]=e,a[1][Rde]=n,a[1][Ode]=r,a[1][uX]},Z7e=(t,e)=>{const n=Reflect.ownKeys(t),r=Reflect.ownKeys(e);return n.length!==r.length||n.some((s,i)=>s!==r[i])},Mde=(t,e,n,r,s=Object.is)=>{if(s(t,e))return!1;if(!gT(t)||!gT(e))return!0;const i=n.get(lz(t));if(!i)return!0;if(r){if(r.get(t)===e)return!1;r.set(t,e)}let o=null;for(const a of i[oz]||[])if(o=Reflect.has(t,a)!==Reflect.has(e,a),o)return o;if(i[wE]===!0){if(o=Z7e(t,e),o)return o}else for(const a of i[az]||[]){const c=!!Reflect.getOwnPropertyDescriptor(t,a),l=!!Reflect.getOwnPropertyDescriptor(e,a);if(o=c!==l,o)return o}for(const a of i[cz]||[])if(o=Mde(t[a],e[a],n,r,s),o)return o;if(o===null)throw new Error("invalid used");return o},Y7e=t=>$de(t)&&t[iz]||null,dX=(t,e=!0)=>{QL.set(t,e)},X7e=(t,e,n)=>{const r=[],s=new WeakSet,i=(o,a)=>{var c,l,u;if(s.has(o))return;gT(o)&&s.add(o);const d=gT(o)&&e.get(lz(o));if(d){if((c=d[oz])===null||c===void 0||c.forEach(f=>{const p=`:has(${String(f)})`;r.push(a?[...a,p]:[p])}),d[wE]===!0){const f=":ownKeys";r.push(a?[...a,f]:[f])}else(l=d[az])===null||l===void 0||l.forEach(f=>{const p=`:hasOwn(${String(f)})`;r.push(a?[...a,p]:[p])});(u=d[cz])===null||u===void 0||u.forEach(f=>{"value"in(Object.getOwnPropertyDescriptor(o,f)||{})&&i(o[f],a?[...a,f]:[f])})}else a&&r.push(a)};return i(t),r},mT={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},uz=t=>typeof t=="object"&&t!==null,Q7e=t=>uz(t)&&!YS.has(t)&&(Array.isArray(t)||!(Symbol.iterator in t))&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!(t instanceof Error)&&!(t instanceof Number)&&!(t instanceof Date)&&!(t instanceof String)&&!(t instanceof RegExp)&&!(t instanceof ArrayBuffer)&&!(t instanceof Promise),Lde=(t,e)=>{const n=JL.get(t);if(n?.[0]===e)return n[1];const r=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return dX(r,!0),JL.set(t,[e,r]),Reflect.ownKeys(t).forEach(s=>{if(Object.getOwnPropertyDescriptor(r,s))return;const i=Reflect.get(t,s),{enumerable:o}=Reflect.getOwnPropertyDescriptor(t,s),a={value:i,enumerable:o,configurable:!0};if(YS.has(i))dX(i,!1);else if(d0.has(i)){const[c,l]=d0.get(i);a.value=Lde(c,l())}Object.defineProperty(r,s,a)}),Object.preventExtensions(r)},J7e=(t,e,n,r)=>({deleteProperty(s,i){const o=Reflect.get(s,i);n(i);const a=Reflect.deleteProperty(s,i);return a&&r(["delete",[i],o]),a},set(s,i,o,a){const c=!t()&&Reflect.has(s,i),l=Reflect.get(s,i,a);if(c&&(fX(l,o)||FC.has(o)&&fX(l,FC.get(o))))return!0;n(i),uz(o)&&(o=Y7e(o)||o);const u=!d0.has(o)&&tBe(o)?Br(o):o;return e(i,u),Reflect.set(s,i,u,a),r(["set",[i],o,l]),!0}}),d0=new WeakMap,YS=new WeakSet,JL=new WeakMap,F2=[1,1],FC=new WeakMap;let fX=Object.is,eBe=(t,e)=>new Proxy(t,e),tBe=Q7e,nBe=Lde,rBe=J7e;function Br(t={}){if(!uz(t))throw new Error("object required");const e=FC.get(t);if(e)return e;let n=F2[0];const r=new Set,s=(b,v=++F2[0])=>{n!==v&&(n=v,r.forEach(x=>x(b,v)))};let i=F2[1];const o=(b=++F2[1])=>(i!==b&&!r.size&&(i=b,c.forEach(([v])=>{const x=v[1](b);x>n&&(n=x)})),n),a=b=>(v,x)=>{const E=[...v];E[1]=[b,...E[1]],s(E,x)},c=new Map,l=(b,v)=>{const x=!YS.has(v)&&d0.get(v);if(x){if((mT?"production":void 0)!=="production"&&c.has(b))throw new Error("prop listener already exists");if(r.size){const E=x[2](a(b));c.set(b,[x,E])}else c.set(b,[x])}},u=b=>{var v;const x=c.get(b);x&&(c.delete(b),(v=x[1])==null||v.call(x))},d=b=>(r.add(b),r.size===1&&c.forEach(([x,E],A)=>{if((mT?"production":void 0)!=="production"&&E)throw new Error("remove already exists");const _=x[2](a(A));c.set(A,[x,_])}),()=>{r.delete(b),r.size===0&&c.forEach(([x,E],A)=>{E&&(E(),c.set(A,[x]))})});let f=!0;const p=rBe(()=>f,l,u,s),m=eBe(t,p);FC.set(t,m);const y=[t,o,d];return d0.set(m,y),Reflect.ownKeys(t).forEach(b=>{const v=Object.getOwnPropertyDescriptor(t,b);"value"in v&&v.writable&&(m[b]=t[b])}),f=!1,m}function Gs(t,e,n){const r=d0.get(t);(mT?"production":void 0)!=="production"&&!r&&console.warn("Please use proxy object");let s;const i=[],o=r[2];let a=!1;const l=o(u=>{i.push(u),s||(s=Promise.resolve().then(()=>{s=void 0,a&&e(i.splice(0))}))});return a=!0,()=>{a=!1,l()}}function py(t){const e=d0.get(t);(mT?"production":void 0)!=="production"&&!e&&console.warn("Please use proxy object");const[n,r]=e;return nBe(n,r())}function gy(t){return YS.add(t),t}function sBe(){return{proxyStateMap:d0,refSet:YS,snapCache:JL,versionHolder:F2,proxyCache:FC}}function ai(t,e,n,r){let s=t[e];return Gs(t,()=>{const i=t[e];Object.is(s,i)||n(s=i)})}const{proxyStateMap:iBe,snapCache:oBe}=sBe(),mA=t=>iBe.has(t);function aBe(t){const e=[];let n=0;const r=new Map,s=new WeakMap,i=()=>{const l=oBe.get(a),u=l?.[1];if(u&&!s.has(u)){const d=new Map(r);s.set(u,d)}},o=l=>s.get(l)||r,a={data:e,index:n,epoch:0,get size(){return mA(this)||i(),o(this).size},get(l){const d=o(this).get(l);if(d===void 0){this.epoch;return}return this.data[d]},has(l){const u=o(this);return this.epoch,u.has(l)},set(l,u){if(!mA(this))throw new Error("Cannot perform mutations on a snapshot");const d=r.get(l);return d===void 0?(r.set(l,this.index),this.data[this.index++]=u):this.data[d]=u,this.epoch++,this},delete(l){if(!mA(this))throw new Error("Cannot perform mutations on a snapshot");const u=r.get(l);return u===void 0?!1:(delete this.data[u],r.delete(l),this.epoch++,!0)},clear(){if(!mA(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,r.clear()},forEach(l){this.epoch,o(this).forEach((d,f)=>{l(this.data[d],f,this)})},*entries(){this.epoch;const l=o(this);for(const[u,d]of l)yield[u,this.data[d]]},*keys(){this.epoch;const l=o(this);for(const u of l.keys())yield u},*values(){this.epoch;const l=o(this);for(const u of l.values())yield this.data[u]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=Br(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}var Bde={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(kr,function(){var n=1e3,r=6e4,s=36e5,i="millisecond",o="second",a="minute",c="hour",l="day",u="week",d="month",f="quarter",p="year",m="date",y="Invalid Date",b=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,v=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,x={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(z){var N=["th","st","nd","rd"],T=z%100;return"["+z+(N[(T-20)%10]||N[T]||N[0])+"]"}},E=function(z,N,T){var U=String(z);return!U||U.length>=N?z:""+Array(N+1-U.length).join(T)+z},A={s:E,z:function(z){var N=-z.utcOffset(),T=Math.abs(N),U=Math.floor(T/60),L=T%60;return(N<=0?"+":"-")+E(U,2,"0")+":"+E(L,2,"0")},m:function z(N,T){if(N.date()1)return z(H[0])}else{var Y=N.name;k[Y]=N,L=Y}return!U&&L&&(_=L),L||!U&&_},$=function(z,N){if(W(z))return z.clone();var T=typeof N=="object"?N:{};return T.date=z,T.args=arguments,new M(T)},R=A;R.l=S,R.i=W,R.w=function(z,N){return $(z,{locale:N.$L,utc:N.$u,x:N.$x,$offset:N.$offset})};var M=function(){function z(T){this.$L=S(T.locale,null,!0),this.parse(T),this.$x=this.$x||T.x||{},this[B]=!0}var N=z.prototype;return N.parse=function(T){this.$d=function(U){var L=U.date,P=U.utc;if(L===null)return new Date(NaN);if(R.u(L))return new Date;if(L instanceof Date)return new Date(L);if(typeof L=="string"&&!/Z$/i.test(L)){var H=L.match(b);if(H){var Y=H[2]-1||0,re=(H[7]||"0").substring(0,3);return P?new Date(Date.UTC(H[1],Y,H[3]||1,H[4]||0,H[5]||0,H[6]||0,re)):new Date(H[1],Y,H[3]||1,H[4]||0,H[5]||0,H[6]||0,re)}}return new Date(L)}(T),this.init()},N.init=function(){var T=this.$d;this.$y=T.getFullYear(),this.$M=T.getMonth(),this.$D=T.getDate(),this.$W=T.getDay(),this.$H=T.getHours(),this.$m=T.getMinutes(),this.$s=T.getSeconds(),this.$ms=T.getMilliseconds()},N.$utils=function(){return R},N.isValid=function(){return this.$d.toString()!==y},N.isSame=function(T,U){var L=$(T);return this.startOf(U)<=L&&L<=this.endOf(U)},N.isAfter=function(T,U){return $(T)0,k<=_.r||!_.r){k<=1&&A>0&&(_=x[A-1]);var B=v[_.l];p&&(k=p(""+k)),y=typeof B=="string"?B.replace("%d",k):B(k,u,_.l,b);break}}if(u)return y;var W=b?v.future:v.past;return typeof W=="function"?W(y):W.replace("%s",y)},i.to=function(l,u){return a(l,u,this,!0)},i.from=function(l,u){return a(l,u,this)};var c=function(l){return l.$u?s.utc():s()};i.toNow=function(l){return this.to(c(this),l)},i.fromNow=function(l){return this.from(c(this),l)}}})})(Fde);var dBe=Fde.exports;const fBe=Zi(dBe);var jde={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(kr,function(){return function(n,r,s){s.updateLocale=function(i,o){var a=s.Ls[i];if(a)return(o?Object.keys(o):[]).forEach(function(c){a[c]=o[c]}),a}}})})(jde);var hBe=jde.exports;const pBe=Zi(hBe);lv.extend(fBe);lv.extend(pBe);const gBe={...uBe,name:"en-web3-modal",relativeTime:{future:"in %s",past:"%s ago",s:"%d sec",m:"1 min",mm:"%d min",h:"1 hr",hh:"%d hrs",d:"1 d",dd:"%d d",M:"1 mo",MM:"%d mo",y:"1 yr",yy:"%d yr"}},mBe=["January","February","March","April","May","June","July","August","September","October","November","December"];lv.locale("en-web3-modal",gBe);const e7={getMonthNameByIndex(t){return mBe[t]},getYear(t=new Date().toISOString()){return lv(t).year()},getRelativeDateFromNow(t){return lv(t).locale("en-web3-modal").fromNow(!0)},formatDate(t,e="DD MMM"){return lv(t).format(e)}};var hX={};const ye={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof hX<"u"?hX.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}}}},jC={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return t?.filter(n=>n.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){if(!e)return;const n=t.find(s=>s.caipNetworkId===e);if(n)return n.name;const[r]=e.split(":");return ye.CHAIN_NAME_MAP?.[r]||void 0}},zde=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var yBe=20,wBe=1,my=1e6,pX=1e6,bBe=-7,vBe=21,xBe=!1,XS="[big.js] ",ew=XS+"Invalid ",qP=ew+"decimal places",EBe=ew+"rounding mode",Wde=XS+"Division by zero",Lr={},Qd=void 0,CBe=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Vde(){function t(e){var n=this;if(!(n instanceof t))return e===Qd?Vde():new t(e);if(e instanceof t)n.s=e.s,n.e=e.e,n.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(ew+"value");e=e===0&&1/e<0?"-0":String(e)}_Be(n,e)}n.constructor=t}return t.prototype=Lr,t.DP=yBe,t.RM=wBe,t.NE=bBe,t.PE=vBe,t.strict=xBe,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function _Be(t,e){var n,r,s;if(!CBe.test(e))throw Error(ew+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(n=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(n<0&&(n=r),n+=+e.slice(r+1),e=e.substring(0,r)):n<0&&(n=e.length),s=e.length,r=0;r0&&e.charAt(--s)=="0";);for(t.e=n-r-1,t.c=[],n=0;r<=s;)t.c[n++]=+e.charAt(r++)}return t}function tw(t,e,n,r){var s=t.c;if(n===Qd&&(n=t.constructor.RM),n!==0&&n!==1&&n!==2&&n!==3)throw Error(EBe);if(e<1)r=n===3&&(r||!!s[0])||e===0&&(n===1&&s[0]>=5||n===2&&(s[0]>5||s[0]===5&&(r||s[1]!==Qd))),s.length=1,r?(t.e=t.e-e+1,s[0]=1):s[0]=t.e=0;else if(e=5||n===2&&(s[e]>5||s[e]===5&&(r||s[e+1]!==Qd||s[e-1]&1))||n===3&&(r||!!s[0]),s.length=e,r){for(;++s[--e]>9;)if(s[e]=0,e===0){++t.e,s.unshift(1);break}}for(e=s.length;!s[--e];)s.pop()}return t}function nw(t,e,n){var r=t.e,s=t.c.join(""),i=s.length;if(e)s=s.charAt(0)+(i>1?"."+s.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)s="0"+s;s="0."+s}else if(r>0)if(++r>i)for(r-=i;r--;)s+="0";else r1&&(s=s.charAt(0)+"."+s.slice(1));return t.s<0&&n?"-"+s:s}Lr.abs=function(){var t=new this.constructor(this);return t.s=1,t};Lr.cmp=function(t){var e,n=this,r=n.c,s=(t=new n.constructor(t)).c,i=n.s,o=t.s,a=n.e,c=t.e;if(!r[0]||!s[0])return r[0]?i:s[0]?-o:0;if(i!=o)return i;if(e=i<0,a!=c)return a>c^e?1:-1;for(o=(a=r.length)<(c=s.length)?a:c,i=-1;++is[i]^e?1:-1;return a==c?0:a>c^e?1:-1};Lr.div=function(t){var e=this,n=e.constructor,r=e.c,s=(t=new n(t)).c,i=e.s==t.s?1:-1,o=n.DP;if(o!==~~o||o<0||o>my)throw Error(qP);if(!s[0])throw Error(Wde);if(!r[0])return t.s=i,t.c=[t.e=0],t;var a,c,l,u,d,f=s.slice(),p=a=s.length,m=r.length,y=r.slice(0,a),b=y.length,v=t,x=v.c=[],E=0,A=o+(v.e=e.e-t.e)+1;for(v.s=i,i=A<0?0:A,f.unshift(0);b++b?1:-1;else for(d=-1,u=0;++dy[d]?1:-1;break}if(u<0){for(c=b==a?s:f;b;){if(y[--b]A&&tw(v,A,n.RM,y[0]!==Qd),v};Lr.eq=function(t){return this.cmp(t)===0};Lr.gt=function(t){return this.cmp(t)>0};Lr.gte=function(t){return this.cmp(t)>-1};Lr.lt=function(t){return this.cmp(t)<0};Lr.lte=function(t){return this.cmp(t)<1};Lr.minus=Lr.sub=function(t){var e,n,r,s,i=this,o=i.constructor,a=i.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,i.plus(t);var l=i.c.slice(),u=i.e,d=t.c,f=t.e;if(!l[0]||!d[0])return d[0]?t.s=-c:l[0]?t=new o(i):t.s=1,t;if(a=u-f){for((s=a<0)?(a=-a,r=l):(f=u,r=d),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(n=((s=l.length0)for(;c--;)l[e++]=0;for(c=e;n>a;){if(l[--n]0?(c=o,r=l):(e=-e,r=a),r.reverse();e--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),e=l.length,n=0;e;a[e]%=10)n=(a[--e]=a[e]+l[e]+n)/10|0;for(n&&(a.unshift(n),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t};Lr.pow=function(t){var e=this,n=new e.constructor("1"),r=n,s=t<0;if(t!==~~t||t<-pX||t>pX)throw Error(ew+"exponent");for(s&&(t=-t);t&1&&(r=r.times(e)),t>>=1,!!t;)e=e.times(e);return s?n.div(r):r};Lr.prec=function(t,e){if(t!==~~t||t<1||t>my)throw Error(ew+"precision");return tw(new this.constructor(this),t,e)};Lr.round=function(t,e){if(t===Qd)t=0;else if(t!==~~t||t<-my||t>my)throw Error(qP);return tw(new this.constructor(this),t+this.e+1,e)};Lr.sqrt=function(){var t,e,n,r=this,s=r.constructor,i=r.s,o=r.e,a=new s("0.5");if(!r.c[0])return new s(r);if(i<0)throw Error(XS+"No square root");i=Math.sqrt(+nw(r,!0,!0)),i===0||i===1/0?(e=r.c.join(""),e.length+o&1||(e+="0"),i=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new s((i==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+o)):t=new s(i+""),o=t.e+(s.DP+=4);do n=t,t=a.times(n.plus(r.div(n)));while(n.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return tw(t,(s.DP-=4)+t.e+1,s.RM)};Lr.times=Lr.mul=function(t){var e,n=this,r=n.constructor,s=n.c,i=(t=new r(t)).c,o=s.length,a=i.length,c=n.e,l=t.e;if(t.s=n.s==t.s?1:-1,!s[0]||!i[0])return t.c=[t.e=0],t;for(t.e=c+l,oc;)a=e[l]+i[c]*s[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t};Lr.toExponential=function(t,e){var n=this,r=n.c[0];if(t!==Qd){if(t!==~~t||t<0||t>my)throw Error(qP);for(n=tw(new n.constructor(n),++t,e);n.c.lengthmy)throw Error(qP);for(n=tw(new n.constructor(n),t+n.e+1,e),t=t+n.e+1;n.c.length=e.PE,!!t.c[0])};Lr.toNumber=function(){var t=+nw(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(XS+"Imprecise conversion");return t};Lr.toPrecision=function(t,e){var n=this,r=n.constructor,s=n.c[0];if(t!==Qd){if(t!==~~t||t<1||t>my)throw Error(ew+"precision");for(n=tw(new r(n),t,e);n.c.length=r.PE,!!s)};Lr.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(XS+"valueOf disallowed");return nw(t,t.e<=e.NE||t.e>=e.PE,!0)};var Jx=Vde();const SBe={bigNumber(t){return t?new Jx(t):new Jx(0)},multiply(t,e){if(t===void 0||e===void 0)return new Jx(0);const n=new Jx(t),r=new Jx(e);return n.times(r)},formatNumberToLocalString(t,e=2){return t===void 0?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(t){return t===void 0?0:parseFloat(t.replace(/,/gu,""))}},ABe=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],IBe=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],TBe=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],NBe={getERC20Abi:t=>ye.USDT_CONTRACT_ADDRESSES.includes(t)?TBe:ABe,getSwapAbi:()=>IBe},PBe={URLS:{FAQ:"https://walletconnect.com/faq"}},Yo={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[n,r,s]=e;if(!n||!r||!s)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:n,chainId:r,address:s}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[n,r]=e;if(!n||!r)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:n,chainId:r}}},Gt={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails"};function b$(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Vt={setItem(t,e){Ub()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(Ub())return localStorage.getItem(t)||void 0},removeItem(t){Ub()&&localStorage.removeItem(t)},clear(){Ub()&&localStorage.clear()}};function Ub(){return typeof window<"u"&&typeof localStorage<"u"}function bh(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}var gX={};const v$=(typeof process<"u"&&typeof gX<"u"?gX.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Hde=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],kBe="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",wn={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:v$,SECURE_SITE_DASHBOARD:`${v$}/dashboard`,SECURE_SITE_FAVICON:`${v$}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:[ye.CHAIN.EVM,ye.CHAIN.SOLANA],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[ye.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[ye.CHAIN.EVM,ye.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[ye.CHAIN.EVM],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[ye.CHAIN.EVM,ye.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0}},Ge={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=Ge.getActiveNamespace(),e=Ge.getActiveCaipNetworkId(),n=e?e.split(":")[1]:void 0,r=n?isNaN(Number(n))?n:Number(n):void 0;return{namespace:t,caipNetworkId:e,chainId:r}},setWalletConnectDeepLink({name:t,href:e}){try{Vt.setItem(Gt.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Vt.getItem(Gt.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Vt.removeItem(Gt.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Vt.setItem(Gt.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Vt.setItem(Gt.ACTIVE_CAIP_NETWORK_ID,t),Ge.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Vt.getItem(Gt.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Vt.removeItem(Gt.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=b$(t);Vt.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=Ge.getRecentWallets();e.find(r=>r.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Vt.setItem(Gt.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Vt.getItem(Gt.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(t,e){try{const n=b$(t);Vt.setItem(n,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Vt.getItem(Gt.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=b$(t);return Vt.getItem(e)}catch{console.info("Unable to get connected connector id in namespace",t)}},setConnectedSocialProvider(t){try{Vt.setItem(Gt.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Vt.getItem(Gt.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Vt.removeItem(Gt.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Vt.getItem(Gt.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Vt.getItem(Gt.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{Vt.setItem(Gt.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Vt.getItem(Gt.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Vt.getItem(Gt.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Vt.setItem(Gt.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=Ge.getConnectedNamespaces();e.includes(t)||(e.push(t),Ge.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=Ge.getConnectedNamespaces(),n=e.indexOf(t);n>-1&&(e.splice(n,1),Ge.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Vt.getItem(Gt.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Vt.setItem(Gt.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Vt.removeItem(Gt.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Vt.getItem(Gt.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=Ge.getBalanceCache();Vt.setItem(Gt.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const n=Ge.getBalanceCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.portfolio))return n.balance;Ge.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=Ge.getBalanceCache();e[t.caipAddress]=t,Vt.setItem(Gt.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Vt.getItem(Gt.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=Ge.getBalanceCache();Vt.setItem(Gt.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const n=Ge.getNativeBalanceCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.nativeBalance))return n;console.info("Discarding cache for address",t),Ge.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=Ge.getNativeBalanceCache();e[t.caipAddress]=t,Vt.setItem(Gt.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Vt.getItem(Gt.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const n=Ge.getEnsCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.ens))return n.ens;Ge.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=Ge.getEnsCache();e[t.address]=t,Vt.setItem(Gt.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=Ge.getEnsCache();Vt.setItem(Gt.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Vt.getItem(Gt.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const n=Ge.getIdentityCache()[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.identity))return n.identity;Ge.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=Ge.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Vt.setItem(Gt.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=Ge.getIdentityCache();Vt.setItem(Gt.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Vt.removeItem(Gt.PORTFOLIO_CACHE),Vt.removeItem(Gt.NATIVE_BALANCE_CACHE),Vt.removeItem(Gt.ENS_CACHE),Vt.removeItem(Gt.IDENTITY_CACHE),Vt.removeItem(Gt.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Vt.setItem(Gt.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Vt.getItem(Gt.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const n=Ge.getConnections(),r=n[e]??[],s=new Map;for(const o of r)s.set(o.connectorId,{...o});for(const o of t){const a=s.get(o.connectorId),c=o.connectorId===ye.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(d=>d.address.toLowerCase())),u=o.accounts.filter(d=>!l.has(d.address.toLowerCase()));a.accounts.push(...u)}else s.set(o.connectorId,{...o})}const i={...n,[e]:Array.from(s.values())};Vt.setItem(Gt.CONNECTIONS,JSON.stringify(i))}catch(n){console.error("Unable to sync connections to storage",n)}},getConnections(){try{const t=Vt.getItem(Gt.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}},deleteAddressFromConnection({connectorId:t,address:e,namespace:n}){try{const r=Ge.getConnections(),s=r[n]??[],i=new Map(s.map(a=>[a.connectorId,a])),o=i.get(t);o&&(o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase()).length===0?i.delete(t):i.set(t,{...o,accounts:o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase())})),Vt.setItem(Gt.CONNECTIONS,JSON.stringify({...r,[n]:Array.from(i.values())}))}catch{console.error(`Unable to remove address "${e}" from connector "${t}" in namespace "${n}"`)}},getDisconnectedConnectorIds(){try{const t=Vt.getItem(Gt.DISCONNECTED_CONNECTOR_IDS);return t?JSON.parse(t):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(t,e){try{const n=Ge.getDisconnectedConnectorIds(),r=n[e]??[];r.push(t),Vt.setItem(Gt.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...n,[e]:Array.from(new Set(r))}))}catch{console.error(`Unable to set disconnected connector id "${t}" for namespace "${e}"`)}},removeDisconnectedConnectorId(t,e){try{const n=Ge.getDisconnectedConnectorIds();let r=n[e]??[];r=r.filter(s=>s.toLowerCase()!==t.toLowerCase()),Vt.setItem(Gt.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...n,[e]:Array.from(new Set(r))}))}catch{console.error(`Unable to remove disconnected connector id "${t}" for namespace "${e}"`)}},isConnectorDisconnected(t,e){try{return(Ge.getDisconnectedConnectorIds()[e]??[]).some(s=>s.toLowerCase()===t.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${t}" for namespace "${e}"`)}return!1},getTransactionsCache(){try{const t=Vt.getItem(Gt.HISTORY_TRANSACTIONS_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:t,chainId:e=""}){try{const r=Ge.getTransactionsCache()[t]?.[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;Ge.removeTransactionsCache({address:t,chainId:e})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:t,chainId:e="",timestamp:n,transactions:r}){try{const s=Ge.getTransactionsCache();s[t]={...s[t],[e]:{timestamp:n,transactions:r}},Vt.setItem(Gt.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(s))}catch{console.info("Unable to update transactions cache",{address:t,chainId:e,timestamp:n,transactions:r})}},removeTransactionsCache({address:t,chainId:e}){try{const n=Ge.getTransactionsCache(),r=n?.[t]||{},{[e]:s,...i}=r;Vt.setItem(Gt.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...n,[t]:i}))}catch{console.info("Unable to remove transactions cache",{address:t,chainId:e})}},getTokenPriceCache(){try{const t=Vt.getItem(Gt.TOKEN_PRICE_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(t){try{const n=Ge.getTokenPriceCache()[t.join(",")];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.tokenPrice))return n.tokenPrice;Ge.removeTokenPriceCache(t)}catch{console.info("Unable to get token price cache for addresses",t)}},updateTokenPriceCache(t){try{const e=Ge.getTokenPriceCache();e[t.addresses.join(",")]={timestamp:t.timestamp,tokenPrice:t.tokenPrice},Vt.setItem(Gt.TOKEN_PRICE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update token price cache",t)}},removeTokenPriceCache(t){try{const e=Ge.getTokenPriceCache();Vt.setItem(Gt.TOKEN_PRICE_CACHE,JSON.stringify({...e,[t.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",t)}}},De={isMobile(){return this.isClient()?!!(window?.matchMedia&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return De.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=wn.TEN_SEC_MS:!0},isAllowedRetry(t,e=wn.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(De.isClient()&&window.self!==window.top)try{const t=window?.location?.ancestorOrigins?.[0],e="https://app.safe.global";if(t){const n=new URL(t),r=new URL(e);return n.hostname===r.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+wn.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let n;return(...r)=>{function s(){t(...r)}n&&clearTimeout(n),n=setTimeout(s,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,n=null){if(De.isHttpUrl(t))return this.formatUniversalUrl(t,e);let r=t,s=n;r.includes("://")||(r=t.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),s&&!s?.endsWith("/")&&(s=`${s}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const i=encodeURIComponent(e);return{redirect:`${r}wc?uri=${i}`,redirectUniversalLink:s?`${s}wc?uri=${i}`:void 0,href:r}},formatUniversalUrl(t,e){if(!De.isHttpUrl(t))return this.formatNativeUrl(t,e);let n=t;n.endsWith("/")||(n=`${n}/`);const r=encodeURIComponent(e);return{redirect:`${n}wc?uri=${r}`,href:n}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?Ge.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,n){window?.open(t,this.getOpenTargetForPlatform(e),n||"noreferrer noopener")},returnOpenHref(t,e,n){return window?.open(t,this.getOpenTargetForPlatform(e),n||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const t=window?.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(display-mode: standalone)")?.matches:!1,e=window?.navigator?.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((n,r)=>{const s=new Image;s.onload=n,s.onerror=r,s.crossOrigin="anonymous",s.src=t});return Promise.race([e,De.wait(2e3)])},formatBalance(t,e){let n="0.000";if(typeof t=="string"){const r=Number(t);if(r){const s=Math.floor(r*1e3)/1e3;s&&(n=s.toString())}}return`${n}${e?` ${e}`:""}`},formatBalance2(t,e){let n;if(t==="0")n="0";else if(typeof t=="string"){const r=Number(t);r&&(n=r.toString().match(/^-?\d+(?:\.\d{0,3})?/u)?.[0])}return{value:n??"0",rest:n==="0"?"000":"",symbol:e}},getApiUrl(){return ye.W3M_API_URL},getBlockchainApiUrl(){return ye.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return ye.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const n={};return e&&t&&(t.forEach((r,s)=>{n[r]=s}),e.sort((r,s)=>{const i=n[r.id],o=n[s.id];return i!==void 0&&o!==void 0?i-o:i!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const n of t)e+=n.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[n,r]=e.split(".");return{dollars:n,pennies:r}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const n=new Set;return t.filter(r=>{const s=r[e];return n.has(s)?!1:(n.add(s),!0)})},generateSdkVersion(t,e,n){const s=t.length===0?wn.ADAPTER_TYPES.UNIVERSAL:t.map(i=>i.adapterType).join(",");return`${e}-${s}-${n}`},createAccount(t,e,n,r,s){return{namespace:t,address:e,type:n,publicKey:r,path:s}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),n=e[0];return e.filter(Boolean).length===3&&n in ye.CHAIN_NAME_MAP},getAccount(t){return t?typeof t=="string"?{address:t,chainId:void 0}:{address:t.address,chainId:t.chainId}:{address:void 0,chainId:void 0}},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,n="state=";if(new URL(t).host==="auth.magic.link"){const s="provider_authorization_url=",i=t.substring(t.indexOf(s)+s.length),o=this.injectIntoUrl(decodeURIComponent(i),n,e);return t.replace(i,encodeURIComponent(o))}return this.injectIntoUrl(t,n,e)},injectIntoUrl(t,e,n){const r=t.indexOf(e);if(r===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const s=t.indexOf("&",r),i=e.length,o=s!==-1?s:t.length,a=t.substring(0,r+i),c=t.substring(r+i,o),l=t.substring(s),u=c+n;return a+u+l}};async function e2(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class QS{constructor({baseUrl:e,clientId:n}){this.baseUrl=e,this.clientId=n}async get({headers:e,signal:n,cache:r,...s}){const i=this.createUrl(s);return(await e2(i,{method:"GET",headers:e,signal:n,cache:r})).json()}async getBlob({headers:e,signal:n,...r}){const s=this.createUrl(r);return(await e2(s,{method:"GET",headers:e,signal:n})).blob()}async post({body:e,headers:n,signal:r,...s}){const i=this.createUrl(s);return(await e2(i,{method:"POST",headers:n,body:e?JSON.stringify(e):void 0,signal:r})).json()}async put({body:e,headers:n,signal:r,...s}){const i=this.createUrl(s);return(await e2(i,{method:"PUT",headers:n,body:e?JSON.stringify(e):void 0,signal:r})).json()}async delete({body:e,headers:n,signal:r,...s}){const i=this.createUrl(s);return(await e2(i,{method:"DELETE",headers:n,body:e?JSON.stringify(e):void 0,signal:r})).json()}createUrl({path:e,params:n}){const r=new URL(e,this.baseUrl);return n&&Object.entries(n).forEach(([s,i])=>{i&&r.searchParams.append(s,i)}),this.clientId&&r.searchParams.append("clientId",this.clientId),r}}const RBe={getFeatureValue(t,e){const n=e?.[t];return n===void 0?wn.DEFAULT_FEATURES[t]:n},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(De.isTelegram()){if(De.isIos())return t.filter(e=>e!=="google");if(De.isMac())return t.filter(e=>e!=="x");if(De.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t}},jt=Br({features:wn.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:wn.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),_e={state:jt,subscribeKey(t,e){return ai(jt,t,e)},setOptions(t){Object.assign(jt,t)},setRemoteFeatures(t){if(!t)return;const e={...jt.remoteFeatures,...t};jt.remoteFeatures=e,jt.remoteFeatures?.socials&&(jt.remoteFeatures.socials=RBe.filterSocialsByPlatform(jt.remoteFeatures.socials)),jt.features?.pay&&(jt.remoteFeatures.email=!1,jt.remoteFeatures.socials=!1)},setFeatures(t){if(!t)return;jt.features||(jt.features=wn.DEFAULT_FEATURES);const e={...jt.features,...t};jt.features=e,jt.features?.pay&&jt.remoteFeatures&&(jt.remoteFeatures.email=!1,jt.remoteFeatures.socials=!1)},setProjectId(t){jt.projectId=t},setCustomRpcUrls(t){jt.customRpcUrls=t},setAllWallets(t){jt.allWallets=t},setIncludeWalletIds(t){jt.includeWalletIds=t},setExcludeWalletIds(t){jt.excludeWalletIds=t},setFeaturedWalletIds(t){jt.featuredWalletIds=t},setTokens(t){jt.tokens=t},setTermsConditionsUrl(t){jt.termsConditionsUrl=t},setPrivacyPolicyUrl(t){jt.privacyPolicyUrl=t},setCustomWallets(t){jt.customWallets=t},setIsSiweEnabled(t){jt.isSiweEnabled=t},setIsUniversalProvider(t){jt.isUniversalProvider=t},setSdkVersion(t){jt.sdkVersion=t},setMetadata(t){jt.metadata=t},setDisableAppend(t){jt.disableAppend=t},setEIP6963Enabled(t){jt.enableEIP6963=t},setDebug(t){jt.debug=t},setEnableWalletConnect(t){jt.enableWalletConnect=t},setEnableWalletGuide(t){jt.enableWalletGuide=t},setEnableAuthLogger(t){jt.enableAuthLogger=t},setEnableWallets(t){jt.enableWallets=t},setPreferUniversalLinks(t){jt.experimental_preferUniversalLinks=t},setSIWX(t){if(t)for(const[e,n]of Object.entries(wn.SIWX_DEFAULTS))t[e]??=n;jt.siwx=t},setConnectMethodsOrder(t){jt.features={...jt.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){jt.features={...jt.features,walletFeaturesOrder:t}},setSocialsOrder(t){jt.remoteFeatures={...jt.remoteFeatures,socials:t}},setCollapseWallets(t){jt.features={...jt.features,collapseWallets:t}},setEnableEmbedded(t){jt.enableEmbedded=t},setAllowUnsupportedChain(t){jt.allowUnsupportedChain=t},setManualWCControl(t){jt.manualWCControl=t},setEnableNetworkSwitch(t){jt.enableNetworkSwitch=t},setEnableReconnect(t){jt.enableReconnect=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,n])=>{n&&(jt.defaultAccountTypes[e]=n)})},setUniversalProviderConfigOverride(t){jt.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return jt.universalProviderConfigOverride},getSnapshot(){return py(jt)}},OBe=Object.freeze({enabled:!0,events:[]}),$Be=new QS({baseUrl:De.getAnalyticsUrl(),clientId:null}),DBe=5,MBe=60*1e3,Wp=Br({...OBe}),LBe={state:Wp,subscribeKey(t,e){return ai(Wp,t,e)},async sendError(t,e){if(!Wp.enabled)return;const n=Date.now();if(Wp.events.filter(i=>{const o=new Date(i.properties.timestamp||"").getTime();return n-o=DBe)return;const s={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};Wp.events.push(s);try{if(typeof window>"u")return;const{projectId:i,sdkType:o,sdkVersion:a}=_e.state;await $Be.post({path:"/e",params:{projectId:i,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:De.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){Wp.enabled=!0},disable(){Wp.enabled=!1},clearEvents(){Wp.events=[]}};class jv extends Error{constructor(e,n,r){super(e),this.name="AppKitError",this.category=n,this.originalError=r,Object.setPrototypeOf(this,jv.prototype);let s=!1;if(r instanceof Error&&typeof r.stack=="string"&&r.stack){const i=r.stack,o=i.indexOf(` +`);if(o>-1){const a=i.substring(o+1);this.stack=`${this.name}: ${this.message} +${a}`,s=!0}}s||(Error.captureStackTrace?Error.captureStackTrace(this,jv):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function mX(t,e){const n=t instanceof jv?t:new jv(t instanceof Error?t.message:String(t),e,t);throw LBe.sendError(n,n.category),n}function rc(t,e="INTERNAL_SDK_ERROR"){const n={};return Object.keys(t).forEach(r=>{const s=t[r];if(typeof s=="function"){let i=s;s.constructor.name==="AsyncFunction"?i=async(...o)=>{try{return await s(...o)}catch(a){return mX(a,e)}}:i=(...o)=>{try{return s(...o)}catch(a){return mX(a,e)}},n[r]=i}else n[r]=s}),n}var zv={};const BBe="https://secure.walletconnect.org/sdk",UBe=(typeof process<"u"&&typeof zv<"u"?zv.NEXT_PUBLIC_SECURE_SITE_SDK_URL:void 0)||BBe,FBe=(typeof process<"u"&&typeof zv<"u"?zv.NEXT_PUBLIC_DEFAULT_LOG_LEVEL:void 0)||"error",jBe=(typeof process<"u"&&typeof zv<"u"?zv.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION:void 0)||"4",$t={APP_EVENT_KEY:"@w3m-app/",FRAME_EVENT_KEY:"@w3m-frame/",RPC_METHOD_KEY:"RPC_",STORAGE_KEY:"@appkit-wallet/",SESSION_TOKEN_KEY:"SESSION_TOKEN_KEY",EMAIL_LOGIN_USED_KEY:"EMAIL_LOGIN_USED_KEY",LAST_USED_CHAIN_KEY:"LAST_USED_CHAIN_KEY",LAST_EMAIL_LOGIN_TIME:"LAST_EMAIL_LOGIN_TIME",EMAIL:"EMAIL",PREFERRED_ACCOUNT_TYPE:"PREFERRED_ACCOUNT_TYPE",SMART_ACCOUNT_ENABLED:"SMART_ACCOUNT_ENABLED",SMART_ACCOUNT_ENABLED_NETWORKS:"SMART_ACCOUNT_ENABLED_NETWORKS",SOCIAL_USERNAME:"SOCIAL_USERNAME",APP_SWITCH_NETWORK:"@w3m-app/SWITCH_NETWORK",APP_CONNECT_EMAIL:"@w3m-app/CONNECT_EMAIL",APP_CONNECT_DEVICE:"@w3m-app/CONNECT_DEVICE",APP_CONNECT_OTP:"@w3m-app/CONNECT_OTP",APP_CONNECT_SOCIAL:"@w3m-app/CONNECT_SOCIAL",APP_GET_SOCIAL_REDIRECT_URI:"@w3m-app/GET_SOCIAL_REDIRECT_URI",APP_GET_USER:"@w3m-app/GET_USER",APP_SIGN_OUT:"@w3m-app/SIGN_OUT",APP_IS_CONNECTED:"@w3m-app/IS_CONNECTED",APP_GET_CHAIN_ID:"@w3m-app/GET_CHAIN_ID",APP_RPC_REQUEST:"@w3m-app/RPC_REQUEST",APP_UPDATE_EMAIL:"@w3m-app/UPDATE_EMAIL",APP_UPDATE_EMAIL_PRIMARY_OTP:"@w3m-app/UPDATE_EMAIL_PRIMARY_OTP",APP_UPDATE_EMAIL_SECONDARY_OTP:"@w3m-app/UPDATE_EMAIL_SECONDARY_OTP",APP_AWAIT_UPDATE_EMAIL:"@w3m-app/AWAIT_UPDATE_EMAIL",APP_SYNC_THEME:"@w3m-app/SYNC_THEME",APP_SYNC_DAPP_DATA:"@w3m-app/SYNC_DAPP_DATA",APP_GET_SMART_ACCOUNT_ENABLED_NETWORKS:"@w3m-app/GET_SMART_ACCOUNT_ENABLED_NETWORKS",APP_INIT_SMART_ACCOUNT:"@w3m-app/INIT_SMART_ACCOUNT",APP_SET_PREFERRED_ACCOUNT:"@w3m-app/SET_PREFERRED_ACCOUNT",APP_CONNECT_FARCASTER:"@w3m-app/CONNECT_FARCASTER",APP_GET_FARCASTER_URI:"@w3m-app/GET_FARCASTER_URI",APP_RELOAD:"@w3m-app/RELOAD",APP_RPC_ABORT:"@w3m-app/RPC_ABORT",FRAME_SWITCH_NETWORK_ERROR:"@w3m-frame/SWITCH_NETWORK_ERROR",FRAME_SWITCH_NETWORK_SUCCESS:"@w3m-frame/SWITCH_NETWORK_SUCCESS",FRAME_CONNECT_EMAIL_ERROR:"@w3m-frame/CONNECT_EMAIL_ERROR",FRAME_CONNECT_EMAIL_SUCCESS:"@w3m-frame/CONNECT_EMAIL_SUCCESS",FRAME_CONNECT_DEVICE_ERROR:"@w3m-frame/CONNECT_DEVICE_ERROR",FRAME_CONNECT_DEVICE_SUCCESS:"@w3m-frame/CONNECT_DEVICE_SUCCESS",FRAME_CONNECT_OTP_SUCCESS:"@w3m-frame/CONNECT_OTP_SUCCESS",FRAME_CONNECT_OTP_ERROR:"@w3m-frame/CONNECT_OTP_ERROR",FRAME_CONNECT_SOCIAL_SUCCESS:"@w3m-frame/CONNECT_SOCIAL_SUCCESS",FRAME_CONNECT_SOCIAL_ERROR:"@w3m-frame/CONNECT_SOCIAL_ERROR",FRAME_CONNECT_FARCASTER_SUCCESS:"@w3m-frame/CONNECT_FARCASTER_SUCCESS",FRAME_CONNECT_FARCASTER_ERROR:"@w3m-frame/CONNECT_FARCASTER_ERROR",FRAME_GET_FARCASTER_URI_SUCCESS:"@w3m-frame/GET_FARCASTER_URI_SUCCESS",FRAME_GET_FARCASTER_URI_ERROR:"@w3m-frame/GET_FARCASTER_URI_ERROR",FRAME_GET_SOCIAL_REDIRECT_URI_SUCCESS:"@w3m-frame/GET_SOCIAL_REDIRECT_URI_SUCCESS",FRAME_GET_SOCIAL_REDIRECT_URI_ERROR:"@w3m-frame/GET_SOCIAL_REDIRECT_URI_ERROR",FRAME_GET_USER_SUCCESS:"@w3m-frame/GET_USER_SUCCESS",FRAME_GET_USER_ERROR:"@w3m-frame/GET_USER_ERROR",FRAME_SIGN_OUT_SUCCESS:"@w3m-frame/SIGN_OUT_SUCCESS",FRAME_SIGN_OUT_ERROR:"@w3m-frame/SIGN_OUT_ERROR",FRAME_IS_CONNECTED_SUCCESS:"@w3m-frame/IS_CONNECTED_SUCCESS",FRAME_IS_CONNECTED_ERROR:"@w3m-frame/IS_CONNECTED_ERROR",FRAME_GET_CHAIN_ID_SUCCESS:"@w3m-frame/GET_CHAIN_ID_SUCCESS",FRAME_GET_CHAIN_ID_ERROR:"@w3m-frame/GET_CHAIN_ID_ERROR",FRAME_RPC_REQUEST_SUCCESS:"@w3m-frame/RPC_REQUEST_SUCCESS",FRAME_RPC_REQUEST_ERROR:"@w3m-frame/RPC_REQUEST_ERROR",FRAME_SESSION_UPDATE:"@w3m-frame/SESSION_UPDATE",FRAME_UPDATE_EMAIL_SUCCESS:"@w3m-frame/UPDATE_EMAIL_SUCCESS",FRAME_UPDATE_EMAIL_ERROR:"@w3m-frame/UPDATE_EMAIL_ERROR",FRAME_UPDATE_EMAIL_PRIMARY_OTP_SUCCESS:"@w3m-frame/UPDATE_EMAIL_PRIMARY_OTP_SUCCESS",FRAME_UPDATE_EMAIL_PRIMARY_OTP_ERROR:"@w3m-frame/UPDATE_EMAIL_PRIMARY_OTP_ERROR",FRAME_UPDATE_EMAIL_SECONDARY_OTP_SUCCESS:"@w3m-frame/UPDATE_EMAIL_SECONDARY_OTP_SUCCESS",FRAME_UPDATE_EMAIL_SECONDARY_OTP_ERROR:"@w3m-frame/UPDATE_EMAIL_SECONDARY_OTP_ERROR",FRAME_SYNC_THEME_SUCCESS:"@w3m-frame/SYNC_THEME_SUCCESS",FRAME_SYNC_THEME_ERROR:"@w3m-frame/SYNC_THEME_ERROR",FRAME_SYNC_DAPP_DATA_SUCCESS:"@w3m-frame/SYNC_DAPP_DATA_SUCCESS",FRAME_SYNC_DAPP_DATA_ERROR:"@w3m-frame/SYNC_DAPP_DATA_ERROR",FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS:"@w3m-frame/GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS",FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR:"@w3m-frame/GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR",FRAME_INIT_SMART_ACCOUNT_SUCCESS:"@w3m-frame/INIT_SMART_ACCOUNT_SUCCESS",FRAME_INIT_SMART_ACCOUNT_ERROR:"@w3m-frame/INIT_SMART_ACCOUNT_ERROR",FRAME_SET_PREFERRED_ACCOUNT_SUCCESS:"@w3m-frame/SET_PREFERRED_ACCOUNT_SUCCESS",FRAME_SET_PREFERRED_ACCOUNT_ERROR:"@w3m-frame/SET_PREFERRED_ACCOUNT_ERROR",FRAME_READY:"@w3m-frame/READY",FRAME_RELOAD_SUCCESS:"@w3m-frame/RELOAD_SUCCESS",FRAME_RELOAD_ERROR:"@w3m-frame/RELOAD_ERROR",FRAME_RPC_ABORT_SUCCESS:"@w3m-frame/RPC_ABORT_SUCCESS",FRAME_RPC_ABORT_ERROR:"@w3m-frame/RPC_ABORT_ERROR",RPC_RESPONSE_TYPE_ERROR:"RPC_RESPONSE_ERROR",RPC_RESPONSE_TYPE_TX:"RPC_RESPONSE_TRANSACTION_HASH",RPC_RESPONSE_TYPE_OBJECT:"RPC_RESPONSE_OBJECT"},_r={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}},Fd={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},zBe={handleMobileDeeplinkRedirect(t,e){const n=window.location.href,r=encodeURIComponent(n);if(t===Fd.PHANTOM.id&&!("phantom"in window)){const s=n.startsWith("https")?"https":"http",i=n.split("/")[2],o=encodeURIComponent(`${s}://${i}`);window.location.href=`${Fd.PHANTOM.url}/ul/browse/${r}?ref=${o}`}t===Fd.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Fd.SOLFLARE.url}/ul/v1/browse/${r}?ref=${r}`),e===ye.CHAIN.SOLANA&&t===Fd.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Fd.COINBASE.url}/dapp?cb_url=${r}`)}},wc=Br({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),WBe={state:wc,subscribeNetworkImages(t){return Gs(wc.networkImages,()=>t(wc.networkImages))},subscribeKey(t,e){return ai(wc,t,e)},subscribe(t){return Gs(wc,()=>t(wc))},setWalletImage(t,e){wc.walletImages[t]=e},setNetworkImage(t,e){wc.networkImages[t]=e},setChainImage(t,e){wc.chainImages[t]=e},setConnectorImage(t,e){wc.connectorImages={...wc.connectorImages,[t]:e}},setTokenImage(t,e){wc.tokenImages[t]=e},setCurrencyImage(t,e){wc.currencyImages[t]=e}},mi=rc(WBe),VBe={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:""},x$=Br({networkImagePromises:{}}),nr={async fetchWalletImage(t){if(t)return await mt._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(x$.networkImagePromises[t]||(x$.networkImagePromises[t]=mt._fetchNetworkImage(t)),await x$.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return mi.state.walletImages[t]},getWalletImage(t){if(t?.image_url)return t?.image_url;if(t?.image_id)return mi.state.walletImages[t.image_id]},getNetworkImage(t){if(t?.assets?.imageUrl)return t?.assets?.imageUrl;if(t?.assets?.imageId)return mi.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return mi.state.networkImages[t]},getConnectorImage(t){if(t?.imageUrl)return t.imageUrl;if(t?.info?.icon)return t.info.icon;if(t?.imageId)return mi.state.connectorImages[t.imageId]},getChainImage(t){return mi.state.networkImages[VBe[t]]}},Vp=Br({message:"",variant:"info",open:!1}),HBe={state:Vp,subscribeKey(t,e){return ai(Vp,t,e)},open(t,e){const{debug:n}=_e.state,{code:r,displayMessage:s,debugMessage:i}=t;s&&n&&(Vp.message=s,Vp.variant=e,Vp.open=!0),i&&console.error(typeof i=="function"?i():i,r?{code:r}:void 0)},close(){Vp.open=!1,Vp.message="",Vp.variant="info"}},Xr=rc(HBe),qBe=De.getAnalyticsUrl(),KBe=new QS({baseUrl:qBe,clientId:null}),GBe=["MODAL_CREATED"],Kf=Br({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),Lt={state:Kf,subscribe(t){return Gs(Kf,()=>t(Kf))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:n}=_e.state;return{projectId:t,st:e,sv:n||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(t){try{const e=nt.state.address;if(GBe.includes(t.data.event)||typeof window>"u")return;await KBe.post({path:"/e",params:Lt.getSdkProperties(),body:{eventId:De.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e}}}),Kf.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===ye.HTTP_STATUS_CODES.FORBIDDEN&&!Kf.reportedErrors.FORBIDDEN&&(Xr.open({displayMessage:"Invalid App Configuration",debugMessage:`Origin ${Ub()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),Kf.reportedErrors.FORBIDDEN=!0)}},sendEvent(t){Kf.timestamp=Date.now(),Kf.data=t,(_e.state.features?.analytics||t.event==="INITIALIZE")&&Lt._sendAnalyticsEvent(Kf)}},ZBe=De.getApiUrl(),wa=new QS({baseUrl:ZBe,clientId:null}),YBe=40,yX=4,XBe=20,An=Br({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),mt={state:An,subscribeKey(t,e){return ai(An,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:n}=_e.state;return{projectId:t,st:e||"appkit",sv:n||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return _e.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${wa.baseUrl}/getWalletImage/${t}`,n=await wa.getBlob({path:e,params:mt._getSdkProperties()});mi.setWalletImage(t,URL.createObjectURL(n))},async _fetchNetworkImage(t){const e=`${wa.baseUrl}/public/getAssetImage/${t}`,n=await wa.getBlob({path:e,params:mt._getSdkProperties()});mi.setNetworkImage(t,URL.createObjectURL(n))},async _fetchConnectorImage(t){const e=`${wa.baseUrl}/public/getAssetImage/${t}`,n=await wa.getBlob({path:e,params:mt._getSdkProperties()});mi.setConnectorImage(t,URL.createObjectURL(n))},async _fetchCurrencyImage(t){const e=`${wa.baseUrl}/public/getCurrencyImage/${t}`,n=await wa.getBlob({path:e,params:mt._getSdkProperties()});mi.setCurrencyImage(t,URL.createObjectURL(n))},async _fetchTokenImage(t){const e=`${wa.baseUrl}/public/getTokenImage/${t}`,n=await wa.getBlob({path:e,params:mt._getSdkProperties()});mi.setTokenImage(t,URL.createObjectURL(n))},_filterWalletsByPlatform(t){return De.isMobile()?t?.filter(n=>n.mobile_link||n.id===Fd.COINBASE.id?!0:G.state.activeChain==="solana"&&(n.id===Fd.SOLFLARE.id||n.id===Fd.PHANTOM.id)):t},async fetchProjectConfig(){return(await wa.get({path:"/appkit/v1/config",params:mt._getSdkProperties()})).features},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await wa.get({path:"/projects/v1/origins",params:mt._getSdkProperties()});return t}catch(t){if(t instanceof Error&&t.cause instanceof Response){const e=t.cause.status;if(e===ye.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:t});if(e>=ye.HTTP_STATUS_CODES.SERVER_ERROR&&e<600)throw new Error("SERVER_ERROR",{cause:t});return[]}return[]}},async fetchNetworkImages(){const e=G.getAllRequestedCaipNetworks()?.map(({assets:n})=>n?.imageId).filter(Boolean).filter(n=>!nr.getNetworkImageById(n));e&&await Promise.allSettled(e.map(n=>mt._fetchNetworkImage(n)))},async fetchConnectorImages(){const{connectors:t}=ke.state,e=t.map(({imageId:n})=>n).filter(Boolean);await Promise.allSettled(e.map(n=>mt._fetchConnectorImage(n)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>mt._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>mt._fetchTokenImage(e)))},async fetchWallets(t){const e=t.exclude??[];mt._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Fd).map(i=>i.id));const r=await wa.get({path:"/getWallets",params:{...mt._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:t.include?.join(","),exclude:e.join(",")}});return{data:mt._filterWalletsByPlatform(r?.data)||[],count:r?.count}},async fetchFeaturedWallets(){const{featuredWalletIds:t}=_e.state;if(t?.length){const e={...mt._getSdkProperties(),page:1,entries:t?.length??yX,include:t},{data:n}=await mt.fetchWallets(e),r=[...n].sort((i,o)=>t.indexOf(i.id)-t.indexOf(o.id)),s=r.map(i=>i.image_id).filter(Boolean);await Promise.allSettled(s.map(i=>mt._fetchWalletImage(i))),An.featured=r,An.allFeatured=r}},async fetchRecommendedWallets(){try{An.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:n}=_e.state,r=[...e??[],...n??[]].filter(Boolean),s=G.getRequestedCaipNetworkIds().join(","),i={page:1,entries:yX,include:t,exclude:r,chains:s},{data:o,count:a}=await mt.fetchWallets(i),c=Ge.getRecentWallets(),l=o.map(d=>d.image_id).filter(Boolean),u=c.map(d=>d.image_id).filter(Boolean);await Promise.allSettled([...l,...u].map(d=>mt._fetchWalletImage(d))),An.recommended=o,An.allRecommended=o,An.count=a??0}catch{}finally{An.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:n,featuredWalletIds:r}=_e.state,s=G.getRequestedCaipNetworkIds().join(","),i=[...An.recommended.map(({id:u})=>u),...n??[],...r??[]].filter(Boolean),o={page:t,entries:YBe,include:e,exclude:i,chains:s},{data:a,count:c}=await mt.fetchWallets(o),l=a.slice(0,XBe).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(l.map(u=>mt._fetchWalletImage(u))),An.wallets=De.uniqueBy([...An.wallets,...mt._filterOutExtensions(a)],"id").filter(u=>u.chains?.some(d=>s.includes(d))),An.count=c>An.count?c:An.count,An.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:n}=await mt.fetchWallets(e);n&&n.forEach(r=>{An.excludedWallets.push({rdns:r.rdns,name:r.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:n,excludeWalletIds:r}=_e.state,s=G.getRequestedCaipNetworkIds().join(",");An.search=[];const i={page:1,entries:100,search:t?.trim(),badge_type:e,include:n,exclude:r,chains:s},{data:o}=await mt.fetchWallets(i);Lt.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:t??""}});const a=o.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>mt._fetchWalletImage(c)),De.wait(300)]),An.search=mt._filterOutExtensions(o)},initPromise(t,e){const n=An.promises[t];return n||(An.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:n=!0,fetchNetworkImages:r=!0}={}){const s=[t&&mt.initPromise("connectorImages",mt.fetchConnectorImages),e&&mt.initPromise("featuredWallets",mt.fetchFeaturedWallets),n&&mt.initPromise("recommendedWallets",mt.fetchRecommendedWallets),r&&mt.initPromise("networkImages",mt.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(s)},prefetchAnalyticsConfig(){_e.state.features?.analytics&&mt.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await wa.get({path:"/getAnalyticsConfig",params:mt._getSdkProperties()});_e.setFeatures({analytics:t})}catch{_e.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!t?.length){An.featured=An.allFeatured,An.recommended=An.allRecommended;return}const e=G.getRequestedCaipNetworkIds().join(",");An.featured=An.allFeatured.filter(n=>n.chains?.some(r=>e.includes(r))),An.recommended=An.allRecommended.filter(n=>n.chains?.some(r=>e.includes(r))),An.filteredWallets=An.wallets.filter(n=>n.chains?.some(r=>e.includes(r)))},clearFilterByNamespaces(){An.filteredWallets=[]},setFilterByNamespace(t){if(!t){An.featured=An.allFeatured,An.recommended=An.allRecommended;return}const e=G.getRequestedCaipNetworkIds().join(",");An.featured=An.allFeatured.filter(n=>n.chains?.some(r=>e.includes(r))),An.recommended=An.allRecommended.filter(n=>n.chains?.some(r=>e.includes(r))),An.filteredWallets=An.wallets.filter(n=>n.chains?.some(r=>e.includes(r)))}},Ur=Br({view:"Connect",history:["Connect"],transactionStack:[]}),QBe={state:Ur,subscribeKey(t,e){return ai(Ur,t,e)},pushTransactionStack(t){Ur.transactionStack.push(t)},popTransactionStack(t){const e=Ur.transactionStack.pop();if(!e)return;const{onSuccess:n,onError:r,onCancel:s}=e;switch(t){case"success":n?.();break;case"error":r?.(),ze.goBack();break;case"cancel":s?.(),ze.goBack();break}},push(t,e){t!==Ur.view&&(Ur.view=t,Ur.history.push(t),Ur.data=e)},reset(t,e){Ur.view=t,Ur.history=[t],Ur.data=e},replace(t,e){Ur.history.at(-1)===t||(Ur.view=t,Ur.history[Ur.history.length-1]=t,Ur.data=e)},goBack(){const t=G.state.activeCaipAddress,e=ze.state.view==="ConnectingFarcaster",n=!t&&e;if(Ur.history.length>1){Ur.history.pop();const[r]=Ur.history.slice(-1);r&&(t&&r==="Connect"?Ur.view="Account":Ur.view=r)}else tn.close();Ur.data?.wallet&&(Ur.data.wallet=void 0),setTimeout(()=>{if(n){nt.setFarcasterUrl(void 0,G.state.activeChain);const r=ke.getAuthConnector();r?.provider?.reload();const s=py(_e.state);r?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,projectId:s.projectId,sdkType:s.sdkType})}},100)},goBackToIndex(t){if(Ur.history.length>1){Ur.history=Ur.history.slice(0,t+1);const[e]=Ur.history.slice(-1);e&&(Ur.view=e)}},goBackOrCloseModal(){ze.state.history.length>1?ze.goBack():tn.close()}},ze=rc(QBe),Gf=Br({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),t7={state:Gf,subscribe(t){return Gs(Gf,()=>t(Gf))},setThemeMode(t){Gf.themeMode=t;try{const e=ke.getAuthConnector();if(e){const n=t7.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:n,w3mThemeVariables:bh(n,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){Gf.themeVariables={...Gf.themeVariables,...t};try{const e=ke.getAuthConnector();if(e){const n=t7.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:n,w3mThemeVariables:bh(Gf.themeVariables,Gf.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return py(Gf)}},Bi=rc(t7),qde=Object.fromEntries(zde.map(t=>[t,void 0])),JBe=Object.fromEntries(zde.map(t=>[t,!0])),ur=Br({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:qde,filterByNamespaceMap:JBe}),eUe={state:ur,subscribe(t){return Gs(ur,()=>{t(ur)})},subscribeKey(t,e){return ai(ur,t,e)},initialize(t){t.forEach(e=>{const n=Ge.getConnectedConnectorId(e);n&&ke.setConnectorId(n,e)})},setActiveConnector(t){t&&(ur.activeConnector=gy(t))},setConnectors(t){t.filter(s=>!ur.allConnectors.some(i=>i.id===s.id&&ke.getConnectorName(i.name)===ke.getConnectorName(s.name)&&i.chain===s.chain)).forEach(s=>{s.type!=="MULTI_CHAIN"&&ur.allConnectors.push(gy(s))});const n=ke.getEnabledNamespaces(),r=ke.getEnabledConnectors(n);ur.connectors=ke.mergeMultiChainConnectors(r)},filterByNamespaces(t){Object.keys(ur.filterByNamespaceMap).forEach(e=>{ur.filterByNamespaceMap[e]=!1}),t.forEach(e=>{ur.filterByNamespaceMap[e]=!0}),ke.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){ur.filterByNamespaceMap[t]=e,ke.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=ke.getEnabledNamespaces(),e=ke.getEnabledConnectors(t),n=ke.areAllNamespacesEnabled();ur.connectors=ke.mergeMultiChainConnectors(e),n?mt.clearFilterByNamespaces():mt.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(ur.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return ur.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(ur.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=ke.generateConnectorMapByName(t),n=[];return e.forEach(r=>{const s=r[0],i=s?.id===ye.CONNECTOR_ID.AUTH;r.length>1&&s?n.push({name:s.name,imageUrl:s.imageUrl,imageId:s.imageId,connectors:[...r],type:i?"AUTH":"MULTI_CHAIN",chain:"eip155",id:s?.id||""}):s&&n.push(s)}),n},generateConnectorMapByName(t){const e=new Map;return t.forEach(n=>{const{name:r}=n,s=ke.getConnectorName(r);if(!s)return;const i=e.get(s)||[];i.find(a=>a.chain===n.chain)||i.push(n),e.set(s,i)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(n=>{e.find(r=>r.chain===n.chain)||e.push(n)}),e},addConnector(t){if(t.id===ye.CONNECTOR_ID.AUTH){const e=t,n=py(_e.state),r=Bi.getSnapshot().themeMode,s=Bi.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:n.metadata,sdkVersion:n.sdkVersion,projectId:n.projectId,sdkType:n.sdkType}),e?.provider?.syncTheme({themeMode:r,themeVariables:s,w3mThemeVariables:bh(s,r)}),ke.setConnectors([t])}else ke.setConnectors([t])},getAuthConnector(t){const e=t||G.state.activeChain,n=ur.connectors.find(r=>r.id===ye.CONNECTOR_ID.AUTH);if(n)return n?.connectors?.length?n.connectors.find(s=>s.chain===e):n},getAnnouncedConnectorRdns(){return ur.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>t.info?.rdns)},getConnectorById(t){return ur.allConnectors.find(e=>e.id===t)},getConnector({id:t,rdns:e,namespace:n}){const r=n||G.state.activeChain;return ur.allConnectors.filter(i=>i.chain===r).find(i=>i.explorerId===t||i.info?.rdns===e)},syncIfAuthConnector(t){if(t.id!=="ID_AUTH")return;const e=t,n=py(_e.state),r=Bi.getSnapshot().themeMode,s=Bi.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:n.metadata,sdkVersion:n.sdkVersion,sdkType:n.sdkType,projectId:n.projectId}),e.provider.syncTheme({themeMode:r,themeVariables:s,w3mThemeVariables:bh(s,r)})},getConnectorsByNamespace(t){const e=ur.allConnectors.filter(n=>n.chain===t);return ke.mergeMultiChainConnectors(e)},canSwitchToSmartAccount(t){return G.checkIfSmartAccountEnabled()&&Ss(t)===_r.ACCOUNT_TYPES.EOA},selectWalletConnector(t){const e=ke.getConnector({id:t.id,rdns:t.rdns});zBe.handleMobileDeeplinkRedirect(e?.explorerId||t.id,G.state.activeChain),e?ze.push("ConnectingExternal",{connector:e,wallet:t}):ze.push("ConnectingWalletConnect",{wallet:t})},getConnectors(t){return t?ke.getConnectorsByNamespace(t):ke.mergeMultiChainConnectors(ur.allConnectors)},setFilterByNamespace(t){ur.filterByNamespace=t,ur.connectors=ke.getConnectors(t),mt.setFilterByNamespace(t)},setConnectorId(t,e){t&&(ur.activeConnectorIds={...ur.activeConnectorIds,[e]:t},Ge.setConnectedConnectorId(e,t))},removeConnectorId(t){ur.activeConnectorIds={...ur.activeConnectorIds,[t]:void 0},Ge.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return ur.activeConnectorIds[t]},isConnected(t){return t?!!ur.activeConnectorIds[t]:Object.values(ur.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){ur.activeConnectorIds={...qde}}},ke=rc(eUe),tUe=1e3,t2={checkNamespaceConnectorId(t,e){return ke.getConnectorId(t)===e},isSocialProvider(t){return wn.DEFAULT_REMOTE_FEATURES.socials.includes(t)},connectWalletConnect({walletConnect:t,connector:e,closeModalOnConnect:n=!0,redirectViewOnModalClose:r="Connect",onOpen:s,onConnect:i}){return new Promise((o,a)=>{if(t&&ke.setActiveConnector(e),s?.(De.isMobile()&&t),r){const l=tn.subscribeKey("open",u=>{u||(ze.state.view!==r&&ze.replace(r),l(),a(new Error("Modal closed")))})}const c=G.subscribeKey("activeCaipAddress",l=>{l&&(i?.(),n&&tn.close(),c(),o(Yo.parseCaipAddress(l)))})})},connectExternal(t){return new Promise((e,n)=>{const r=G.subscribeKey("activeCaipAddress",s=>{s&&(tn.close(),r(),e(Yo.parseCaipAddress(s)))});Ue.connectExternal(t,t.chain).catch(()=>{r(),n(new Error("Connection rejected"))})})},connectSocial({social:t,namespace:e,closeModalOnConnect:n=!0,onOpenFarcaster:r,onConnect:s}){let i=nt.state.socialWindow,o=nt.state.socialProvider,a=!1,c=null;const l=e||G.state.activeChain,u=G.subscribeKey("activeCaipAddress",d=>{d&&(n&&tn.close(),u())});return new Promise((d,f)=>{async function p(y){if(y.data?.resultUri)if(y.origin===ye.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",p,!1);try{const b=ke.getAuthConnector(l);if(b&&!a){i&&(i.close(),nt.setSocialWindow(void 0,l),i=nt.state.socialWindow),a=!0;const v=y.data.resultUri;if(o&&Lt.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:o}}),o){Ge.setConnectedSocialProvider(o),await Ue.connectExternal({id:b.id,type:b.type,socialUri:v},b.chain);const x=G.state.activeCaipAddress;if(!x){f(new Error("Failed to connect"));return}d(Yo.parseCaipAddress(x)),Lt.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:o,caipNetworkId:G.getActiveCaipNetwork()?.caipNetworkId}})}}}catch{o&&Lt.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:o}}),f(new Error("Failed to connect"))}}else o&&Lt.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:o}})}async function m(){if(t&&(nt.setSocialProvider(t,l),o=nt.state.socialProvider,Lt.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:o}})),o==="farcaster"){r?.();const y=tn.subscribeKey("open",v=>{!v&&t==="farcaster"&&(f(new Error("Popup closed")),s?.(),y())}),b=ke.getAuthConnector();if(b&&!nt.state.farcasterUrl)try{const{url:v}=await b.provider.getFarcasterUri();nt.setFarcasterUrl(v,l)}catch{f(new Error("Failed to connect to farcaster"))}}else{const y=ke.getAuthConnector();c=De.returnOpenHref(`${ye.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(y&&o){const{uri:b}=await y.provider.getSocialRedirectUri({provider:o});if(c&&b){nt.setSocialWindow(c,l),i=nt.state.socialWindow,c.location.href=b;const v=setInterval(()=>{i?.closed&&!a&&(f(new Error("Popup closed")),clearInterval(v))},1e3);window.addEventListener("message",p,!1)}else c?.close(),f(new Error("Failed to initiate social connection"))}}catch{f(new Error("Failed to initiate social connection")),c?.close()}}}m()})},connectEmail({closeModalOnConnect:t=!0,redirectViewOnModalClose:e="Connect",onOpen:n,onConnect:r}){return new Promise((s,i)=>{if(n?.(),e){const a=tn.subscribeKey("open",c=>{c||(ze.state.view!==e&&ze.replace(e),a(),i(new Error("Modal closed")))})}const o=G.subscribeKey("activeCaipAddress",a=>{a&&(r?.(),t&&tn.close(),o(),s(Yo.parseCaipAddress(a)))})})},async updateEmail(){const t=Ge.getConnectedConnectorId(G.state.activeChain),e=ke.getAuthConnector();if(!e)throw new Error("No auth connector found");if(t!==ye.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");const n=e.provider.getEmail()??"";return await tn.open({view:"UpdateEmailWallet",data:{email:n,redirectView:void 0}}),new Promise((r,s)=>{const i=setInterval(()=>{const a=e.provider.getEmail()??"";a!==n&&(tn.close(),clearInterval(i),o(),r({email:a}))},tUe),o=tn.subscribeKey("open",a=>{a||(ze.state.view!=="Connect"&&ze.push("Connect"),clearInterval(i),o(),s(new Error("Modal closed")))})})},canSwitchToSmartAccount(t){return G.checkIfSmartAccountEnabled()&&Ss(t)===_r.ACCOUNT_TYPES.EOA}};function Kde(){const t=G.state.activeCaipNetwork?.chainNamespace||"eip155",e=G.state.activeCaipNetwork?.id||1,n=wn.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${n}`}function Ss(t){return G.getAccountData(t)?.preferredAccountType}function vm(t){return t?G.state.chains.get(t)?.networkState?.caipNetwork:G.state.activeCaipNetwork}const Sl={getConnectionStatus(t,e){const n=ke.state.activeConnectorIds[e],r=Ue.getConnections(e);return!!n&&t.connectorId===n?"connected":r.some(o=>o.connectorId.toLowerCase()===t.connectorId.toLowerCase())?"active":"disconnected"},excludeConnectorAddressFromConnections({connections:t,connectorId:e,addresses:n}){return t.map(r=>{if((e?r.connectorId.toLowerCase()===e.toLowerCase():!1)&&n){const i=r.accounts.filter(o=>!n.some(c=>c.toLowerCase()===o.address.toLowerCase()));return{...r,accounts:i}}return r})},excludeExistingConnections(t,e){const n=new Set(t);return e.filter(r=>!n.has(r.connectorId))},getConnectionsByConnectorId(t,e){return t.filter(n=>n.connectorId.toLowerCase()===e.toLowerCase())},getConnectionsData(t){const e=!!_e.state.remoteFeatures?.multiWallet,n=ke.state.activeConnectorIds[t],r=Ue.getConnections(t),i=(Ue.state.recentConnections.get(t)??[]).filter(a=>ke.getConnectorById(a.connectorId)),o=Sl.excludeExistingConnections([...r.map(a=>a.connectorId),...n?[n]:[]],i);return e?{connections:r,recentConnections:o}:{connections:r.filter(a=>a.connectorId.toLowerCase()===n?.toLowerCase()),recentConnections:[]}}},om=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),Xs=Br({...om}),nUe={state:Xs,subscribeKey(t,e){return ai(Xs,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=De.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){Xs.message=om.message,Xs.variant=om.variant,Xs.svg=om.svg,Xs.open=om.open,Xs.autoClose=om.autoClose},_showMessage({message:t,svg:e,variant:n="success",autoClose:r=om.autoClose}){Xs.open?(Xs.open=!1,setTimeout(()=>{Xs.message=t,Xs.variant=n,Xs.svg=e,Xs.open=!0,Xs.autoClose=r},150)):(Xs.message=t,Xs.variant=n,Xs.svg=e,Xs.open=!0,Xs.autoClose=r)}},Wn=nUe,ls=Br({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),rUe={state:ls,subscribe(t){return Gs(ls,()=>t(ls))},setLastNetworkInView(t){ls.lastNetworkInView=t},async fetchTransactions(t){if(!t)throw new Error("Transactions can't be fetched without an accountAddress");ls.loading=!0;try{const e=await Qt.fetchTransactions({account:t,cursor:ls.next,chainId:G.state.activeCaipNetwork?.caipNetworkId}),n=Vo.filterSpamTransactions(e.data),r=Vo.filterByConnectedChain(n),s=[...ls.transactions,...r];ls.loading=!1,ls.transactions=s,ls.transactionsByYear=Vo.groupTransactionsByYearAndMonth(ls.transactionsByYear,r),ls.empty=s.length===0,ls.next=e.next?e.next:void 0}catch{const n=G.state.activeChain;Lt.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:_e.state.projectId,cursor:ls.next,isSmartAccount:Ss(n)===_r.ACCOUNT_TYPES.SMART_ACCOUNT}}),Wn.showError("Failed to fetch transactions"),ls.loading=!1,ls.empty=!0,ls.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const n=t;return e.forEach(r=>{const s=new Date(r.metadata.minedAt).getFullYear(),i=new Date(r.metadata.minedAt).getMonth(),o=n[s]??{},c=(o[i]??[]).filter(l=>l.id!==r.id);n[s]={...o,[i]:[...c,r].sort((l,u)=>new Date(u.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),n},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(r=>r.nft_info?.flags.is_spam===!0))},filterByConnectedChain(t){const e=G.state.activeCaipNetwork?.caipNetworkId;return t.filter(r=>r.metadata.chain===e)},clearCursor(){ls.next=void 0},resetTransactions(){ls.transactions=[],ls.transactionsByYear={},ls.lastNetworkInView=void 0,ls.loading=!1,ls.empty=!1,ls.next=void 0}},Vo=rc(rUe,"API_ERROR"),dr=Br({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,buffering:!1,status:"disconnected"});let Z0;const sUe={state:dr,subscribe(t){return Gs(dr,()=>t(dr))},subscribeKey(t,e){return ai(dr,t,e)},_getClient(){return dr._client},setClient(t){dr._client=gy(t)},initialize(t){const e=t.filter(n=>!!n.namespace).map(n=>n.namespace);Ue.syncStorageConnections(e)},syncStorageConnections(t){const e=Ge.getConnections(),n=t??Array.from(G.state.chains.keys());for(const r of n){const s=e[r]??[],i=new Map(dr.recentConnections);i.set(r,s),dr.recentConnections=i}},getConnections(t){return t?dr.connections.get(t)??[]:[]},hasAnyConnection(t){const e=Ue.state.connections;return Array.from(e.values()).flatMap(n=>n).some(({connectorId:n})=>n===t)},async connectWalletConnect(){if(De.isTelegram()||De.isSafari()&&De.isIos()){if(Z0){await Z0,Z0=void 0;return}if(!De.isPairingExpired(dr?.wcPairingExpiry)){const t=dr.wcUri;dr.wcUri=t;return}Z0=Ue._getClient()?.connectWalletConnect?.().catch(()=>{}),Ue.state.status="connecting",await Z0,Z0=void 0,dr.wcPairingExpiry=void 0,Ue.state.status="connected"}else await Ue._getClient()?.connectWalletConnect?.()},async connectExternal(t,e,n=!0){const r=await Ue._getClient()?.connectExternal?.(t);return n&&G.setActiveNamespace(e),r},async reconnectExternal(t){await Ue._getClient()?.reconnectExternal?.(t);const e=t.chain||G.state.activeChain;e&&ke.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){if(!e)return;tn.setLoading(!0,G.state.activeChain);const n=ke.getAuthConnector();n&&(nt.setPreferredAccountType(t,e),await n.provider.setPreferredAccount(t),Ge.setPreferredAccountTypes(Object.entries(G.state.chains).reduce((r,[s,i])=>{const o=s,a=Ss(o);return a!==void 0&&(r[o]=a),r},{})),await Ue.reconnectExternal(n),tn.setLoading(!1,G.state.activeChain),Lt.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:G.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(t){return Ue._getClient()?.signMessage(t)},parseUnits(t,e){return Ue._getClient()?.parseUnits(t,e)},formatUnits(t,e){return Ue._getClient()?.formatUnits(t,e)},async sendTransaction(t){return Ue._getClient()?.sendTransaction(t)},async getCapabilities(t){return Ue._getClient()?.getCapabilities(t)},async grantPermissions(t){return Ue._getClient()?.grantPermissions(t)},async walletGetAssets(t){return Ue._getClient()?.walletGetAssets(t)??{}},async estimateGas(t){return Ue._getClient()?.estimateGas(t)},async writeContract(t){return Ue._getClient()?.writeContract(t)},async getEnsAddress(t){return Ue._getClient()?.getEnsAddress(t)},async getEnsAvatar(t){return Ue._getClient()?.getEnsAvatar(t)},checkInstalled(t){return Ue._getClient()?.checkInstalled?.(t)||!1},resetWcConnection(){dr.wcUri=void 0,dr.wcPairingExpiry=void 0,dr.wcLinking=void 0,dr.recentWallet=void 0,dr.status="disconnected",Vo.resetTransactions(),Ge.deleteWalletConnectDeepLink()},resetUri(){dr.wcUri=void 0,dr.wcPairingExpiry=void 0,Z0=void 0},finalizeWcConnection(){const{wcLinking:t,recentWallet:e}=Ue.state;t&&Ge.setWalletConnectDeepLink(t),e&&Ge.setAppKitRecent(e),Lt.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:t?"mobile":"qrcode",name:ze.state.data?.wallet?.name||"Unknown",caipNetworkId:G.getActiveCaipNetwork()?.caipNetworkId}})},setWcBasic(t){dr.wcBasic=t},setUri(t){dr.wcUri=t,dr.wcPairingExpiry=De.getPairingExpiry()},setWcLinking(t){dr.wcLinking=t},setWcError(t){dr.wcError=t,dr.buffering=!1},setRecentWallet(t){dr.recentWallet=t},setBuffering(t){dr.buffering=t},setStatus(t){dr.status=t},setIsSwitchingConnection(t){dr.isSwitchingConnection=t},async disconnect({id:t,namespace:e,initialDisconnect:n}={}){try{await Ue._getClient()?.disconnect({id:t,chainNamespace:e,initialDisconnect:n})}catch(r){throw new jv("Failed to disconnect","INTERNAL_SDK_ERROR",r)}},setConnections(t,e){const n=new Map(dr.connections);n.set(e,t),dr.connections=n},async handleAuthAccountSwitch({address:t,namespace:e}){const n=nt.state.user?.accounts?.find(s=>s.type==="smartAccount"),r=n&&n.address.toLowerCase()===t.toLowerCase()&&t2.canSwitchToSmartAccount(e)?"smartAccount":"eoa";await Ue.setPreferredAccountType(r,e)},async handleActiveConnection({connection:t,namespace:e,address:n}){const r=ke.getConnectorById(t.connectorId),s=t.connectorId===ye.CONNECTOR_ID.AUTH;if(!r)throw new Error(`No connector found for connection: ${t.connectorId}`);if(s)s&&n&&await Ue.handleAuthAccountSwitch({address:n,namespace:e});else return(await Ue.connectExternal({id:r.id,type:r.type,provider:r.provider,address:n,chain:e},e))?.address;return n},async handleDisconnectedConnection({connection:t,namespace:e,address:n,closeModalOnConnect:r}){const s=ke.getConnectorById(t.connectorId),i=t.auth?.name?.toLowerCase(),o=t.connectorId===ye.CONNECTOR_ID.AUTH,a=t.connectorId===ye.CONNECTOR_ID.WALLET_CONNECT;if(!s)throw new Error(`No connector found for connection: ${t.connectorId}`);let c;if(o)if(i&&t2.isSocialProvider(i)){const{address:l}=await t2.connectSocial({social:i,closeModalOnConnect:r,onOpenFarcaster(){tn.open({view:"ConnectingFarcaster"})},onConnect(){ze.replace("ProfileWallets")}});c=l}else{const{address:l}=await t2.connectEmail({closeModalOnConnect:r,onOpen(){tn.open({view:"EmailLogin"})},onConnect(){ze.replace("ProfileWallets")}});c=l}else if(a){const{address:l}=await t2.connectWalletConnect({walletConnect:!0,connector:s,closeModalOnConnect:r,onOpen(u){tn.open({view:u?"AllWallets":"ConnectingWalletConnect"})},onConnect(){ze.replace("ProfileWallets")}});c=l}else{const l=await Ue.connectExternal({id:s.id,type:s.type,provider:s.provider,chain:e},e);l&&(c=l.address)}return o&&n&&await Ue.handleAuthAccountSwitch({address:n,namespace:e}),c},async switchConnection({connection:t,address:e,namespace:n,closeModalOnConnect:r,onChange:s}){let i;const o=nt.getCaipAddress(n);if(o){const{address:c}=Yo.parseCaipAddress(o);i=c}const a=Sl.getConnectionStatus(t,n);switch(a){case"connected":case"active":{const c=await Ue.handleActiveConnection({connection:t,namespace:n,address:e});if(i&&c){const l=c.toLowerCase()!==i.toLowerCase();s?.({address:c,namespace:n,hasSwitchedAccount:l,hasSwitchedWallet:a==="active"})}break}case"disconnected":{const c=await Ue.handleDisconnectedConnection({connection:t,namespace:n,address:e,closeModalOnConnect:r});c&&s?.({address:c,namespace:n,hasSwitchedAccount:!0,hasSwitchedWallet:!0});break}default:throw new Error(`Invalid connection status: ${a}`)}}},Ue=rc(sUe),Hw=Br({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),Lu={state:Hw,subscribe(t){return Gs(Hw,()=>t(Hw))},subscribeOpen(t){return ai(Hw,"open",t)},set(t){Object.assign(Hw,{...Hw,...t})}},iUe={async getTokenList(){const t=G.state.activeCaipNetwork;return(await Qt.fetchSwapTokens({chainId:t?.caipNetworkId}))?.tokens?.map(r=>({...r,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0}))||[]},async fetchGasPrice(){const t=G.state.activeCaipNetwork;if(!t)return null;try{switch(t.chainNamespace){case"solana":const e=(await Ue?.estimateGas({chainNamespace:"solana"}))?.toString();return{standard:e,fast:e,instant:e};case"eip155":default:return await Qt.fetchGasPrice({chainId:t.caipNetworkId})}}catch{return null}},async fetchSwapAllowance({tokenAddress:t,userAddress:e,sourceTokenAmount:n,sourceTokenDecimals:r}){const s=await Qt.fetchSwapAllowance({tokenAddress:t,userAddress:e});if(s?.allowance&&n&&r){const i=Ue.parseUnits(n,r)||0;return BigInt(s.allowance)>=i}return!1},async getMyTokensWithBalance(t){const e=await dz.getMyTokensWithBalance(t);return nt.setTokenBalance(e,G.state.activeChain),this.mapBalancesToSwapTokens(e)},mapBalancesToSwapTokens(t){return t?.map(e=>({...e,address:e?.address?e.address:Kde(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]}},Or=Br({tokenBalances:[],loading:!1}),oUe={state:Or,subscribe(t){return Gs(Or,()=>t(Or))},subscribeKey(t,e){return ai(Or,t,e)},setToken(t){t&&(Or.token=gy(t))},setTokenAmount(t){Or.sendTokenAmount=t},setReceiverAddress(t){Or.receiverAddress=t},setReceiverProfileImageUrl(t){Or.receiverProfileImageUrl=t},setReceiverProfileName(t){Or.receiverProfileName=t},setNetworkBalanceInUsd(t){Or.networkBalanceInUSD=t},setLoading(t){Or.loading=t},async sendToken(){try{switch(gr.setLoading(!0),G.state.activeCaipNetwork?.chainNamespace){case"eip155":await gr.sendEvmToken();return;case"solana":await gr.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}finally{gr.setLoading(!1)}},async sendEvmToken(){const t=G.state.activeChain;if(!t)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");const e=Ss(t);if(!gr.state.sendTokenAmount||!gr.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!gr.state.token)throw new Error("A token is required");gr.state.token?.address?(Lt.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===_r.ACCOUNT_TYPES.SMART_ACCOUNT,token:gr.state.token.address,amount:gr.state.sendTokenAmount,network:G.state.activeCaipNetwork?.caipNetworkId||""}}),await gr.sendERC20Token({receiverAddress:gr.state.receiverAddress,tokenAddress:gr.state.token.address,sendTokenAmount:gr.state.sendTokenAmount,decimals:gr.state.token.quantity.decimals})):(Lt.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===_r.ACCOUNT_TYPES.SMART_ACCOUNT,token:gr.state.token.symbol||"",amount:gr.state.sendTokenAmount,network:G.state.activeCaipNetwork?.caipNetworkId||""}}),await gr.sendNativeToken({receiverAddress:gr.state.receiverAddress,sendTokenAmount:gr.state.sendTokenAmount,decimals:gr.state.token.quantity.decimals}))},async fetchTokenBalance(t){Or.loading=!0;const e=G.state.activeCaipNetwork?.caipNetworkId,n=G.state.activeCaipNetwork?.chainNamespace,r=G.state.activeCaipAddress,s=r?De.getPlainAddress(r):void 0;if(Or.lastRetry&&!De.isAllowedRetry(Or.lastRetry,30*wn.ONE_SEC_MS))return Or.loading=!1,[];try{if(s&&e&&n){const i=await dz.getMyTokensWithBalance();return Or.tokenBalances=i,Or.lastRetry=void 0,i}}catch(i){Or.lastRetry=Date.now(),t?.(i),Wn.showError("Token Balance Unavailable")}finally{Or.loading=!1}return[]},fetchNetworkBalance(){if(Or.tokenBalances.length===0)return;const t=iUe.mapBalancesToSwapTokens(Or.tokenBalances);if(!t)return;const e=t.find(n=>n.address===Kde());e&&(Or.networkBalanceInUSD=e?SBe.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){ze.pushTransactionStack({});const e=t.receiverAddress,n=nt.state.address,r=Ue.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));await Ue.sendTransaction({chainNamespace:ye.CHAIN.EVM,to:e,address:n,data:"0x",value:r??BigInt(0)}),Lt.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Ss("eip155")===_r.ACCOUNT_TYPES.SMART_ACCOUNT,token:gr.state.token?.symbol||"",amount:t.sendTokenAmount,network:G.state.activeCaipNetwork?.caipNetworkId||""}}),Ue._getClient()?.updateBalance("eip155"),gr.resetSend()},async sendERC20Token(t){ze.pushTransactionStack({onSuccess(){ze.replace("Account")}});const e=Ue.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));if(nt.state.address&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const n=De.getPlainAddress(t.tokenAddress);if(!n)throw new Error("SendController:sendERC20Token - tokenAddress is required");await Ue.writeContract({fromAddress:nt.state.address,tokenAddress:n,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:NBe.getERC20Abi(n),chainNamespace:ye.CHAIN.EVM}),gr.resetSend()}},async sendSolanaToken(){if(!gr.state.sendTokenAmount||!gr.state.receiverAddress)throw new Error("An amount and receiver address are required");ze.pushTransactionStack({onSuccess(){ze.replace("Account")}}),await Ue.sendTransaction({chainNamespace:"solana",to:gr.state.receiverAddress,value:gr.state.sendTokenAmount}),Ue._getClient()?.updateBalance("solana"),gr.resetSend()},resetSend(){Or.token=void 0,Or.sendTokenAmount=void 0,Or.receiverAddress=void 0,Or.receiverProfileImageUrl=void 0,Or.receiverProfileName=void 0,Or.loading=!1,Or.tokenBalances=[]}},gr=rc(oUe),E$={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},yA={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},_t=Br({chains:aBe(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),aUe={state:_t,subscribe(t){return Gs(_t,()=>{t(_t)})},subscribeKey(t,e){return ai(_t,t,e)},subscribeChainProp(t,e,n){let r;return Gs(_t.chains,()=>{const s=n||_t.activeChain;if(s){const i=_t.chains.get(s)?.[t];r!==i&&(r=i,e(i))}})},initialize(t,e,n){const{chainId:r,namespace:s}=Ge.getActiveNetworkProps(),i=e?.find(u=>u.id.toString()===r?.toString()),a=t.find(u=>u?.namespace===s)||t?.[0],c=t.map(u=>u.namespace).filter(u=>u!==void 0),l=_e.state.enableEmbedded?new Set([...c]):new Set([...e?.map(u=>u.chainNamespace)??[]]);(t?.length===0||!a)&&(_t.noAdapters=!0),_t.noAdapters||(_t.activeChain=a?.namespace,_t.activeCaipNetwork=i,G.setChainNetworkData(a?.namespace,{caipNetwork:i}),_t.activeChain&&Lu.set({activeChain:a?.namespace})),l.forEach(u=>{const d=e?.filter(m=>m.chainNamespace===u),f=Ge.getPreferredAccountTypes()||{},p={..._e.state.defaultAccountTypes,...f};G.state.chains.set(u,{namespace:u,networkState:Br({...yA,caipNetwork:d?.[0]}),accountState:Br({...E$,preferredAccountType:p[u]}),caipNetworks:d??[],...n}),G.setRequestedCaipNetworks(d??[],u)})},removeAdapter(t){if(_t.activeChain===t){const e=Array.from(_t.chains.entries()).find(([n])=>n!==t);if(e){const n=e[1]?.caipNetworks?.[0];n&&G.setActiveCaipNetwork(n)}}_t.chains.delete(t)},addAdapter(t,{networkControllerClient:e,connectionControllerClient:n},r){if(!t.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");_t.chains.set(t.namespace,{namespace:t.namespace,networkState:{...yA,caipNetwork:r[0]},accountState:E$,caipNetworks:r,connectionControllerClient:n,networkControllerClient:e}),G.setRequestedCaipNetworks(r?.filter(s=>s.chainNamespace===t.namespace)??[],t.namespace)},addNetwork(t){const e=_t.chains.get(t.chainNamespace);if(e){const n=[...e.caipNetworks||[]];e.caipNetworks?.find(r=>r.id===t.id)||n.push(t),_t.chains.set(t.chainNamespace,{...e,caipNetworks:n}),G.setRequestedCaipNetworks(n,t.chainNamespace),ke.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){const n=_t.chains.get(t);if(n){const r=_t.activeCaipNetwork?.id===e,s=[...n.caipNetworks?.filter(i=>i.id!==e)||[]];r&&n?.caipNetworks?.[0]&&G.setActiveCaipNetwork(n.caipNetworks[0]),_t.chains.set(t,{...n,caipNetworks:s}),G.setRequestedCaipNetworks(s||[],t),s.length===0&&ke.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const n=_t.chains.get(t);n&&(n.networkState={...n.networkState||yA,...e},_t.chains.set(t,n))},setChainAccountData(t,e,n=!0){if(!t)throw new Error("Chain is required to update chain account data");const r=_t.chains.get(t);if(r){const s={...r.accountState||E$,...e};_t.chains.set(t,{...r,accountState:s}),(_t.chains.size===1||_t.activeChain===t)&&(e.caipAddress&&(_t.activeCaipAddress=e.caipAddress),nt.replaceState(s))}},setChainNetworkData(t,e){if(!t)return;const n=_t.chains.get(t);if(n){const r={...n.networkState||yA,...e};_t.chains.set(t,{...n,networkState:r})}},setAccountProp(t,e,n,r=!0){G.setChainAccountData(n,{[t]:e},r)},setActiveNamespace(t){_t.activeChain=t;const e=t?_t.chains.get(t):void 0,n=e?.networkState?.caipNetwork;n?.id&&t&&(_t.activeCaipAddress=e?.accountState?.caipAddress,_t.activeCaipNetwork=n,G.setChainNetworkData(t,{caipNetwork:n}),Ge.setActiveCaipNetworkId(n?.caipNetworkId),Lu.set({activeChain:t,selectedNetworkId:n?.caipNetworkId}))},setActiveCaipNetwork(t){if(!t)return;_t.activeChain!==t.chainNamespace&&G.setIsSwitchingNamespace(!0);const e=_t.chains.get(t.chainNamespace);_t.activeChain=t.chainNamespace,_t.activeCaipNetwork=t,G.setChainNetworkData(t.chainNamespace,{caipNetwork:t}),e?.accountState?.address?_t.activeCaipAddress=`${t.chainNamespace}:${t.id}:${e?.accountState?.address}`:_t.activeCaipAddress=void 0,G.setAccountProp("caipAddress",_t.activeCaipAddress,t.chainNamespace),e&&nt.replaceState(e.accountState),gr.resetSend(),Lu.set({activeChain:_t.activeChain,selectedNetworkId:_t.activeCaipNetwork?.caipNetworkId}),Ge.setActiveCaipNetworkId(t.caipNetworkId),!G.checkIfSupportedNetwork(t.chainNamespace)&&_e.state.enableNetworkSwitch&&!_e.state.allowUnsupportedChain&&!Ue.state.wcBasic&&G.showUnsupportedChainUI()},addCaipNetwork(t){if(!t)return;const e=_t.chains.get(t.chainNamespace);e&&e?.caipNetworks?.push(t)},async switchActiveNamespace(t){if(!t)return;const e=t!==G.state.activeChain,n=G.getNetworkData(t)?.caipNetwork,r=G.getCaipNetworkByNamespace(t,n?.id);e&&r&&await G.switchActiveNetwork(r)},async switchActiveNetwork(t){const e=G.state.activeChain;if(!e)throw new Error("ChainController:switchActiveNetwork - namespace is required");const r=!G.state.chains.get(e)?.caipNetworks?.some(i=>i.id===_t.activeCaipNetwork?.id),s=G.getNetworkControllerClient(t.chainNamespace);if(s){try{await s.switchCaipNetwork(t),r&&tn.close()}catch{ze.goBack()}Lt.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})}},getNetworkControllerClient(t){const e=t||_t.activeChain;if(!e)throw new Error("ChainController:getNetworkControllerClient - chain is required");const n=_t.chains.get(e);if(!n)throw new Error("Chain adapter not found");if(!n.networkControllerClient)throw new Error("NetworkController client not set");return n.networkControllerClient},getConnectionControllerClient(t){const e=t||_t.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const n=_t.chains.get(e);if(!n?.connectionControllerClient)throw new Error("ConnectionController client not set");return n.connectionControllerClient},getNetworkProp(t,e){const n=_t.chains.get(e)?.networkState;if(n)return n[t]},getRequestedCaipNetworks(t){const e=_t.chains.get(t),{approvedCaipNetworkIds:n=[],requestedCaipNetworks:r=[]}=e?.networkState||{};return De.sortRequestedNetworks(n,r).filter(o=>o?.id)},getAllRequestedCaipNetworks(){const t=[];return _t.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");const n=G.getRequestedCaipNetworks(e.namespace);t.push(...n)}),t},setRequestedCaipNetworks(t,e){G.setAdapterNetworkState(e,{requestedCaipNetworks:t});const r=G.getAllRequestedCaipNetworks().map(i=>i.chainNamespace),s=Array.from(new Set(r));ke.filterByNamespaces(s)},getAllApprovedCaipNetworkIds(){const t=[];return _t.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");const n=G.getApprovedCaipNetworkIds(e.namespace);t.push(...n)}),t},getActiveCaipNetwork(t){return t?_t.chains.get(t)?.networkState?.caipNetwork:_t.activeCaipNetwork},getActiveCaipAddress(){return _t.activeCaipAddress},getApprovedCaipNetworkIds(t){return _t.chains.get(t)?.networkState?.approvedCaipNetworkIds||[]},async setApprovedCaipNetworksData(t){const n=await G.getNetworkControllerClient()?.getApprovedCaipNetworksData();G.setAdapterNetworkState(t,{approvedCaipNetworkIds:n?.approvedCaipNetworkIds,supportsAllNetworks:n?.supportsAllNetworks})},checkIfSupportedNetwork(t,e){const n=e||_t.activeCaipNetwork?.caipNetworkId,r=G.getRequestedCaipNetworks(t);return r.length?r?.some(s=>s.caipNetworkId===n):!0},checkIfSupportedChainId(t){return _t.activeChain?G.getRequestedCaipNetworks(_t.activeChain)?.some(n=>n.id===t):!0},setSmartAccountEnabledNetworks(t,e){G.setAdapterNetworkState(e,{smartAccountEnabledNetworks:t})},checkIfSmartAccountEnabled(){const t=jC.caipNetworkIdToNumber(_t.activeCaipNetwork?.caipNetworkId),e=_t.activeChain;return!e||!t?!1:!!G.getNetworkProp("smartAccountEnabledNetworks",e)?.includes(Number(t))},showUnsupportedChainUI(){tn.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=_t.activeCaipNetwork;return!!(t?.chainNamespace&&wn.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){G.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(t){const e=t;if(!e)throw new Error("Chain is required to set account prop");const n=G.state.chains.get(e)?.accountState?.preferredAccountType,r=_e.state.defaultAccountTypes[e];_t.activeCaipAddress=void 0,G.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:r||n,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,user:void 0,status:"disconnected"}),ke.removeConnectorId(e)},setIsSwitchingNamespace(t){_t.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){const t=[];let e;if(_t.chains.forEach(n=>{ye.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(r=>r===n.namespace)&&n.namespace&&t.push(n.namespace)}),t.length>0){const n=t[0];return e=n?_t.chains.get(n)?.caipNetworks?.[0]:void 0,e}},getAccountData(t){const e=t||_t.activeChain;if(e)return G.state.chains.get(e)?.accountState},getNetworkData(t){const e=t||_t.activeChain;if(e)return G.state.chains.get(e)?.networkState},getCaipNetworkByNamespace(t,e){if(!t)return;const n=G.state.chains.get(t),r=n?.caipNetworks?.find(s=>s.id===e);return r||n?.networkState?.caipNetwork||n?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){const t=ke.state.filterByNamespace;return(t?[_t.chains.get(t)]:Array.from(_t.chains.values())).flatMap(n=>n?.caipNetworks||[]).map(n=>n.caipNetworkId)},getCaipNetworks(t){return t?G.getRequestedCaipNetworks(t):G.getAllRequestedCaipNetworks()},setLastConnectedSIWECaipNetwork(t){_t.lastConnectedSIWECaipNetwork=t},getLastConnectedSIWECaipNetwork(){return _t.lastConnectedSIWECaipNetwork}},G=rc(aUe),cUe={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},Gde=De.getBlockchainApiUrl(),ba=Br({clientId:null,api:new QS({baseUrl:Gde,clientId:null}),supportedChains:{http:[],ws:[]}}),Qt={state:ba,async get(t){const{st:e,sv:n}=Qt.getSdkProperties(),r=_e.state.projectId,s={...t.params||{},st:e,sv:n,projectId:r};return ba.api.get({...t,params:s})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=_e.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{ba.supportedChains.http.length||await Qt.getSupportedNetworks()}catch{return!1}return ba.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await Qt.get({path:"v1/supported-chains"});return ba.supportedChains=t,t}catch{return ba.supportedChains}},async fetchIdentity({address:t,caipNetworkId:e}){if(!await Qt.isNetworkSupported(e))return{avatar:"",name:""};const r=Ge.getIdentityFromCacheForAddress(t);if(r)return r;const s=await Qt.get({path:`/v1/identity/${t}`,params:{sender:G.state.activeCaipAddress?De.getPlainAddress(G.state.activeCaipAddress):void 0}});return Ge.updateIdentityCache({address:t,identity:s,timestamp:Date.now()}),s},async fetchTransactions({account:t,cursor:e,signal:n,cache:r,chainId:s}){if(!await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId))return{data:[],next:void 0};const o=Ge.getTransactionsCacheForAddress({address:t,chainId:s});if(o)return o;const a=await Qt.get({path:`/v1/account/${t}/history`,params:{cursor:e,chainId:s},signal:n,cache:r});return Ge.updateTransactionsCache({address:t,chainId:s,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:t,userAddress:e,from:n,to:r,gasPrice:s}){return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?Qt.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:n,to:r,gasPrice:s}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?Qt.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){if(!await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId))return{fungibles:[]};const n=Ge.getTokenPriceCacheForAddresses(t);if(n)return n;const r=await ba.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:_e.state.projectId},headers:{"Content-Type":"application/json"}});return Ge.updateTokenPriceCache({addresses:t,timestamp:Date.now(),tokenPrice:r}),r},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?Qt.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){const{st:e,sv:n}=Qt.getSdkProperties();if(!await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return Qt.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:n}})},async generateSwapCalldata({amount:t,from:e,to:n,userAddress:r,disableEstimate:s}){if(!await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ba.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:wn.CONVERT_SLIPPAGE_TOLERANCE},projectId:_e.state.projectId,from:e,to:n,userAddress:r,disableEstimate:s}})},async generateApproveCalldata({from:t,to:e,userAddress:n}){const{st:r,sv:s}=Qt.getSdkProperties();if(!await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return Qt.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:n,from:t,to:e,st:r,sv:s}})},async getBalance(t,e,n){const{st:r,sv:s}=Qt.getSdkProperties();if(!await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId))return Wn.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=Ge.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await Qt.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:n,st:r,sv:s}});return Ge.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?Qt.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?Qt.get({path:`/v1/profile/reverse/${t}`,params:{sender:nt.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(t){return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?Qt.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:n,signature:r}){return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?ba.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:n,signature:r},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:n,purchaseAmount:r,paymentAmount:s}){return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?(await ba.api.post({path:"/v1/generators/onrampurl",params:{projectId:_e.state.projectId},body:{destinationWallets:t,defaultNetwork:n,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:r,presetFiatAmount:s}})).url:""},async getOnrampOptions(){if(!await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await Qt.get({path:"/v1/onramp/options"})}catch{return cUe}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:n,network:r}){try{return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?await ba.api.post({path:"/v1/onramp/quote",params:{projectId:_e.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:n,network:r}}):null}catch{return{networkFee:{amount:n,currency:e.id},paymentSubtotal:{amount:n,currency:e.id},paymentTotal:{amount:n,currency:e.id},purchaseAmount:{amount:n,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?Qt.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,n){return await Qt.isNetworkSupported(G.state.activeCaipNetwork?.caipNetworkId)?ba.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:_e.state.projectId},body:{pci:e,signature:n}}):{success:!1}},setClientId(t){ba.clientId=t,ba.api=new QS({baseUrl:Gde,clientId:t})}},C$={createBalance(t,e){const n={name:t.metadata.name||"",symbol:t.metadata.symbol||"",decimals:t.metadata.decimals||0,value:t.metadata.value||0,price:t.metadata.price||0,iconUrl:t.metadata.iconUrl||""};return{name:n.name,symbol:n.symbol,chainId:e,address:t.address==="native"?void 0:this.convertAddressToCAIP10Address(t.address,e),value:n.value,price:n.price,quantity:{decimals:n.decimals.toString(),numeric:this.convertHexToBalance({hex:t.balance,decimals:n.decimals})},iconUrl:n.iconUrl}},convertHexToBalance({hex:t,decimals:e}){return tx(BigInt(t),e)},convertAddressToCAIP10Address(t,e){return`${e}:${t}`},createCAIP2ChainId(t,e){return`${e}:${parseInt(t,16)}`},getChainIdHexFromCAIP2ChainId(t){const e=t.split(":");if(e.length<2||!e[1])return"0x0";const n=e[1],r=parseInt(n,10);return isNaN(r)?"0x0":`0x${r.toString(16)}`},isWalletGetAssetsResponse(t){return typeof t!="object"||t===null?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(n=>this.isValidAsset(n)))},isValidAsset(t){return typeof t=="object"&&t!==null&&typeof t.address=="string"&&typeof t.balance=="string"&&(t.type==="ERC20"||t.type==="NATIVE")&&typeof t.metadata=="object"&&t.metadata!==null&&typeof t.metadata.name=="string"&&typeof t.metadata.symbol=="string"&&typeof t.metadata.decimals=="number"&&typeof t.metadata.price=="number"&&typeof t.metadata.iconUrl=="string"}},dz={async getMyTokensWithBalance(t){const e=nt.state.address,n=G.state.activeCaipNetwork,r=ke.getConnectorId("eip155")===ye.CONNECTOR_ID.AUTH;if(!e||!n)return[];const s=`${n.caipNetworkId}:${e}`,i=Ge.getBalanceCacheForCaipAddress(s);if(i)return i.balances;if(n.chainNamespace===ye.CHAIN.EVM&&r){const a=await this.getEIP155Balances(e,n);if(a)return this.filterLowQualityTokens(a)}const o=await Qt.getBalance(e,n.caipNetworkId,t);return this.filterLowQualityTokens(o.balances)},async getEIP155Balances(t,e){try{const n=C$.getChainIdHexFromCAIP2ChainId(e.caipNetworkId);if(!(await Ue.getCapabilities(t))?.[n]?.assetDiscovery?.supported)return null;const s=await Ue.walletGetAssets({account:t,chainFilter:[n]});if(!C$.isWalletGetAssetsResponse(s))return null;const o=(s[n]||[]).map(a=>C$.createBalance(a,e.caipNetworkId));return Ge.updateBalanceCache({caipAddress:`${e.caipNetworkId}:${t}`,balance:{balances:o},timestamp:Date.now()}),o}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")}},Sd=Br({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map}),lUe={state:Sd,replaceState(t){t&&Object.assign(Sd,gy(t))},subscribe(t){return G.subscribeChainProp("accountState",e=>{if(e)return t(e)})},subscribeKey(t,e,n){let r;return G.subscribeChainProp("accountState",s=>{if(s){const i=s[t];r!==i&&(r=i,e(i))}},n)},setStatus(t,e){G.setAccountProp("status",t,e)},getCaipAddress(t){if(t)return G.state.chains.get(t)?.accountState?.caipAddress},setCaipAddress(t,e){const n=t?De.getPlainAddress(t):void 0;e===G.state.activeChain&&(G.state.activeCaipAddress=t),G.setAccountProp("caipAddress",t,e),G.setAccountProp("address",n,e)},setBalance(t,e,n){G.setAccountProp("balance",t,n),G.setAccountProp("balanceSymbol",e,n)},setProfileName(t,e){G.setAccountProp("profileName",t,e)},setProfileImage(t,e){G.setAccountProp("profileImage",t,e)},setUser(t,e){G.setAccountProp("user",t,e)},setAddressExplorerUrl(t,e){G.setAccountProp("addressExplorerUrl",t,e)},setSmartAccountDeployed(t,e){G.setAccountProp("smartAccountDeployed",t,e)},setCurrentTab(t){G.setAccountProp("currentTab",t,G.state.activeChain)},setTokenBalance(t,e){t&&G.setAccountProp("tokenBalance",t,e)},setShouldUpdateToAddress(t,e){G.setAccountProp("shouldUpdateToAddress",t,e)},addAddressLabel(t,e,n){if(!n)return;const r=G.state.chains.get(n)?.accountState?.addressLabels||new Map;r.set(t,e),G.setAccountProp("addressLabels",r,n)},removeAddressLabel(t,e){if(!e)return;const n=G.state.chains.get(e)?.accountState?.addressLabels||new Map;n.delete(t),G.setAccountProp("addressLabels",n,e)},setConnectedWalletInfo(t,e){G.setAccountProp("connectedWalletInfo",t,e,!1)},setPreferredAccountType(t,e){G.setAccountProp("preferredAccountType",t,e)},setSocialProvider(t,e){t&&G.setAccountProp("socialProvider",t,e)},setSocialWindow(t,e){G.setAccountProp("socialWindow",t?gy(t):void 0,e)},setFarcasterUrl(t,e){G.setAccountProp("farcasterUrl",t,e)},async fetchTokenBalance(t){Sd.balanceLoading=!0;const e=G.state.activeCaipNetwork?.caipNetworkId,n=G.state.activeCaipNetwork?.chainNamespace,r=G.state.activeCaipAddress,s=r?De.getPlainAddress(r):void 0;if(Sd.lastRetry&&!De.isAllowedRetry(Sd.lastRetry,30*wn.ONE_SEC_MS))return Sd.balanceLoading=!1,[];try{if(s&&e&&n){const i=await dz.getMyTokensWithBalance();return nt.setTokenBalance(i,n),Sd.lastRetry=void 0,Sd.balanceLoading=!1,i}}catch(i){Sd.lastRetry=Date.now(),t?.(i),Wn.showError("Token Balance Unavailable")}finally{Sd.balanceLoading=!1}return[]},resetAccount(t){G.resetAccount(t)}},nt=rc(lUe),Zde={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){const n=G.state.activeCaipNetwork,r=ze.state.data;if(t.id===n?.id)return;const i=nt.getCaipAddress(G.state.activeChain),o=t.chainNamespace!==G.state.activeChain,a=nt.getCaipAddress(t.chainNamespace),l=ke.getConnectorId(G.state.activeChain)===ye.CONNECTOR_ID.AUTH,u=ye.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(d=>d===t.chainNamespace);e||l&&u?ze.push("SwitchNetwork",{...r,network:t}):i&&o&&!a?ze.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):ze.push("SwitchNetwork",{...r,network:t})}},va=Br({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),uUe={state:va,subscribe(t){return Gs(va,()=>t(va))},subscribeKey(t,e){return ai(va,t,e)},async open(t){const e=t?.namespace,n=G.state.activeChain,r=e&&e!==n,s=G.getAccountData(t?.namespace)?.caipAddress;if(Ue.state.wcBasic?mt.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await mt.prefetch(),ke.setFilterByNamespace(t?.namespace),tn.setLoading(!0,e),e&&r){const i=G.getNetworkData(e)?.caipNetwork||G.getRequestedCaipNetworks(e)[0];i&&Zde.onSwitchNetwork({network:i,ignoreSwitchConfirmation:!0})}else{const i=G.state.noAdapters;_e.state.manualWCControl||i&&!s?De.isMobile()?ze.reset("AllWallets"):ze.reset("ConnectingWalletConnectBasic"):t?.view?ze.reset(t.view,t.data):s?ze.reset("Account"):ze.reset("Connect")}va.open=!0,Lu.set({open:!0}),Lt.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!s}})},close(){const t=_e.state.enableEmbedded,e=!!G.state.activeCaipAddress;va.open&&Lt.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),va.open=!1,ze.reset("Connect"),tn.clearLoading(),t?e?ze.replace("Account"):ze.push("Connect"):Lu.set({open:!1}),Ue.resetUri()},setLoading(t,e){e&&va.loadingNamespaceMap.set(e,t),va.loading=t,Lu.set({loading:t})},clearLoading(){va.loadingNamespaceMap.clear(),va.loading=!1,Lu.set({loading:!1})},shake(){va.shake||(va.shake=!0,setTimeout(()=>{va.shake=!1},500))}},tn=rc(uUe),bE={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},n7={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},dUe={providers:Hde,selectedProvider:null,error:null,purchaseCurrency:bE,paymentCurrency:n7,purchaseCurrencies:[bE],paymentCurrencies:[],quotesLoading:!1},or=Br(dUe),fUe={state:or,subscribe(t){return Gs(or,()=>t(or))},subscribeKey(t,e){return ai(or,t,e)},setSelectedProvider(t){if(t&&t.name==="meld"){const e=G.state.activeChain,n=e===ye.CHAIN.SOLANA?"SOL":"USDC",r=e?G.state.chains.get(e)?.accountState?.address??"":"",s=new URL(t.url);s.searchParams.append("publicKey",kBe),s.searchParams.append("destinationCurrencyCode",n),s.searchParams.append("walletAddress",r),s.searchParams.append("externalCustomerId",_e.state.projectId),or.selectedProvider={...t,url:s.toString()}}else or.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,n=Hde.filter(r=>e.includes(r.name));or.providers=n}else or.providers=[]},setPurchaseCurrency(t){or.purchaseCurrency=t},setPaymentCurrency(t){or.paymentCurrency=t},setPurchaseAmount(t){r7.state.purchaseAmount=t},setPaymentAmount(t){r7.state.paymentAmount=t},async getAvailableCurrencies(){const t=await Qt.getOnrampOptions();or.purchaseCurrencies=t.purchaseCurrencies,or.paymentCurrencies=t.paymentCurrencies,or.paymentCurrency=t.paymentCurrencies[0]||n7,or.purchaseCurrency=t.purchaseCurrencies[0]||bE,await mt.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await mt.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){or.quotesLoading=!0;try{const t=await Qt.getOnrampQuote({purchaseCurrency:or.purchaseCurrency,paymentCurrency:or.paymentCurrency,amount:or.paymentAmount?.toString()||"0",network:or.purchaseCurrency?.symbol});return or.quotesLoading=!1,or.purchaseAmount=Number(t?.purchaseAmount.amount),t}catch(t){return or.error=t.message,or.quotesLoading=!1,null}finally{or.quotesLoading=!1}},resetState(){or.selectedProvider=null,or.error=null,or.purchaseCurrency=bE,or.paymentCurrency=n7,or.purchaseCurrencies=[bE],or.paymentCurrencies=[],or.paymentAmount=void 0,or.purchaseAmount=void 0,or.quotesLoading=!1}},r7=rc(fUe),hu=Br({message:"",open:!1,triggerRect:{width:0,height:0,top:0,left:0},variant:"shade"}),hUe={state:hu,subscribe(t){return Gs(hu,()=>t(hu))},subscribeKey(t,e){return ai(hu,t,e)},showTooltip({message:t,triggerRect:e,variant:n}){hu.open=!0,hu.message=t,hu.triggerRect=e,hu.variant=n},hide(){hu.open=!1,hu.message="",hu.triggerRect={width:0,height:0,top:0,left:0}}},Tc=rc(hUe),wX=2147483648,pUe={convertEVMChainIdToCoinType(t){if(t>=wX)throw new Error("Invalid chainId");return(wX|t)>>>0}},ll=Br({suggestions:[],loading:!1}),gUe={state:ll,subscribe(t){return Gs(ll,()=>t(ll))},subscribeKey(t,e){return ai(ll,t,e)},async resolveName(t){try{return await Qt.lookupEnsName(t)}catch(e){const n=e;throw new Error(n?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(t){try{return await Qt.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{ll.loading=!0,ll.suggestions=[];const e=await Qt.getEnsNameSuggestions(t);return ll.suggestions=e.suggestions.map(n=>({...n,name:n.name}))||[],ll.suggestions}catch(e){const n=vE.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(n)}finally{ll.loading=!1}},async getNamesForAddress(t){try{if(!G.state.activeCaipNetwork)return[];const n=Ge.getEnsFromCacheForAddress(t);if(n)return n;const r=await Qt.reverseLookupEnsName({address:t});return Ge.updateEnsCache({address:t,ens:r,timestamp:Date.now()}),r}catch(e){const n=vE.parseEnsApiError(e,"Error fetching names for address");throw new Error(n)}},async registerName(t){const e=G.state.activeCaipNetwork,n=nt.state.address,r=ke.getAuthConnector();if(!e)throw new Error("Network not found");if(!n||!r)throw new Error("Address or auth connector not found");ll.loading=!0;try{const s=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});ze.pushTransactionStack({onCancel(){ze.replace("RegisterAccountName")}});const i=await Ue.signMessage(s);ll.loading=!1;const o=e.id;if(!o)throw new Error("Network not found");const a=pUe.convertEVMChainIdToCoinType(Number(o));await Qt.registerEnsName({coinType:a,address:n,signature:i,message:s}),nt.setProfileName(t,e.chainNamespace),ze.replace("RegisterAccountNameSuccess")}catch(s){const i=vE.parseEnsApiError(s,`Error registering name ${t}`);throw ze.replace("RegisterAccountName"),new Error(i)}finally{ll.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){return t?.reasons?.[0]?.description||e}},vE=rc(gUe),n2=Br({isLegalCheckboxChecked:!1}),Vm={state:n2,subscribe(t){return Gs(n2,()=>t(n2))},subscribeKey(t,e){return ai(n2,t,e)},setIsLegalCheckboxChecked(t){n2.isLegalCheckboxChecked=t}};var fz={exports:{}},uv=typeof Reflect=="object"?Reflect:null,bX=uv&&typeof uv.apply=="function"?uv.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},jI;uv&&typeof uv.ownKeys=="function"?jI=uv.ownKeys:Object.getOwnPropertySymbols?jI=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:jI=function(e){return Object.getOwnPropertyNames(e)};function mUe(t){console&&console.warn&&console.warn(t)}var Yde=Number.isNaN||function(e){return e!==e};function jr(){jr.init.call(this)}fz.exports=jr;fz.exports.once=vUe;jr.EventEmitter=jr;jr.prototype._events=void 0;jr.prototype._eventsCount=0;jr.prototype._maxListeners=void 0;var vX=10;function KP(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(jr,"defaultMaxListeners",{enumerable:!0,get:function(){return vX},set:function(t){if(typeof t!="number"||t<0||Yde(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");vX=t}});jr.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};jr.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Yde(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Xde(t){return t._maxListeners===void 0?jr.defaultMaxListeners:t._maxListeners}jr.prototype.getMaxListeners=function(){return Xde(this)};jr.prototype.emit=function(e){for(var n=[],r=1;r0&&(o=n[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=i[e];if(c===void 0)return!1;if(typeof c=="function")bX(c,this,n);else for(var l=c.length,u=nfe(c,l),r=0;r0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,mUe(a)}return t}jr.prototype.addListener=function(e,n){return Qde(this,e,n,!1)};jr.prototype.on=jr.prototype.addListener;jr.prototype.prependListener=function(e,n){return Qde(this,e,n,!0)};function yUe(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Jde(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},s=yUe.bind(r);return s.listener=n,r.wrapFn=s,s}jr.prototype.once=function(e,n){return KP(n),this.on(e,Jde(this,e,n)),this};jr.prototype.prependOnceListener=function(e,n){return KP(n),this.prependListener(e,Jde(this,e,n)),this};jr.prototype.removeListener=function(e,n){var r,s,i,o,a;if(KP(n),s=this._events,s===void 0)return this;if(r=s[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===n||r[o].listener===n){a=r[o].listener,i=o;break}if(i<0)return this;i===0?r.shift():wUe(r,i),r.length===1&&(s[e]=r[0]),s.removeListener!==void 0&&this.emit("removeListener",e,a||n)}return this};jr.prototype.off=jr.prototype.removeListener;jr.prototype.removeAllListeners=function(e){var n,r,s;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var i=Object.keys(r),o;for(s=0;s=0;s--)this.removeListener(e,n[s]);return this};function efe(t,e,n){var r=t._events;if(r===void 0)return[];var s=r[e];return s===void 0?[]:typeof s=="function"?n?[s.listener||s]:[s]:n?bUe(s):nfe(s,s.length)}jr.prototype.listeners=function(e){return efe(this,e,!0)};jr.prototype.rawListeners=function(e){return efe(this,e,!1)};jr.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):tfe.call(t,e)};jr.prototype.listenerCount=tfe;function tfe(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}jr.prototype.eventNames=function(){return this._eventsCount>0?jI(this._events):[]};function nfe(t,e){for(var n=new Array(e),r=0;r=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i}function SUe(t,e){return function(n,r){e(n,r,t)}}function AUe(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function IUe(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((r=r.apply(t,e||[])).next())})}function TUe(t,e){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,s,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,s&&(i=l[0]&2?s.return:l[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,l[1])).done)return i;switch(s=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,s=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function sfe(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i}function kUe(){for(var t=[],e=0;e1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(m){d(i[0][3],m)}}function c(f){f.value instanceof zC?Promise.resolve(f.value.v).then(l,u):d(i[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function d(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function $Ue(t){var e,n;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,i){e[s]=t[s]?function(o){return(n=!n)?{value:zC(t[s](o)),done:s==="return"}:i?i(o):o}:i}}function DUe(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof o7=="function"?o7(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=t[i]&&function(o){return new Promise(function(a,c){o=t[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(l){i({value:l,done:a})},o)}}function MUe(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function LUe(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function BUe(t){return t&&t.__esModule?t:{default:t}}function UUe(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function FUe(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}const jUe=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return i7},__asyncDelegator:$Ue,__asyncGenerator:OUe,__asyncValues:DUe,__await:zC,__awaiter:IUe,__classPrivateFieldGet:UUe,__classPrivateFieldSet:FUe,__createBinding:NUe,__decorate:_Ue,__exportStar:PUe,__extends:EUe,__generator:TUe,__importDefault:BUe,__importStar:LUe,__makeTemplateObject:MUe,__metadata:AUe,__param:SUe,__read:sfe,__rest:CUe,__spread:kUe,__spreadArrays:RUe,__values:o7},Symbol.toStringTag,{value:"Module"})),GP=Zy(jUe);var _$={},r2={},xX;function zUe(){if(xX)return r2;xX=1,Object.defineProperty(r2,"__esModule",{value:!0}),r2.delay=void 0;function t(e){return new Promise(n=>{setTimeout(()=>{n(!0)},e)})}return r2.delay=t,r2}var Y0={},S$={},X0={},EX;function WUe(){return EX||(EX=1,Object.defineProperty(X0,"__esModule",{value:!0}),X0.ONE_THOUSAND=X0.ONE_HUNDRED=void 0,X0.ONE_HUNDRED=100,X0.ONE_THOUSAND=1e3),X0}var A$={},CX;function VUe(){return CX||(CX=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(A$)),A$}var _X;function ife(){return _X||(_X=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=GP;e.__exportStar(WUe(),t),e.__exportStar(VUe(),t)}(S$)),S$}var SX;function HUe(){if(SX)return Y0;SX=1,Object.defineProperty(Y0,"__esModule",{value:!0}),Y0.fromMiliseconds=Y0.toMiliseconds=void 0;const t=ife();function e(r){return r*t.ONE_THOUSAND}Y0.toMiliseconds=e;function n(r){return Math.floor(r/t.ONE_THOUSAND)}return Y0.fromMiliseconds=n,Y0}var AX;function qUe(){return AX||(AX=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=GP;e.__exportStar(zUe(),t),e.__exportStar(HUe(),t)}(_$)),_$}var qw={},IX;function KUe(){if(IX)return qw;IX=1,Object.defineProperty(qw,"__esModule",{value:!0}),qw.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(n){if(this.timestamps.has(n))throw new Error(`Watch already started for label: ${n}`);this.timestamps.set(n,{started:Date.now()})}stop(n){const r=this.get(n);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${n}`);const s=Date.now()-r.started;this.timestamps.set(n,{started:r.started,elapsed:s})}get(n){const r=this.timestamps.get(n);if(typeof r>"u")throw new Error(`No timestamp found for label: ${n}`);return r}elapsed(n){const r=this.get(n);return r.elapsed||Date.now()-r.started}}return qw.Watch=t,qw.default=t,qw}var I$={},s2={},TX;function GUe(){if(TX)return s2;TX=1,Object.defineProperty(s2,"__esModule",{value:!0}),s2.IWatch=void 0;class t{}return s2.IWatch=t,s2}var NX;function ZUe(){return NX||(NX=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),GP.__exportStar(GUe(),t)}(I$)),I$}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=GP;e.__exportStar(qUe(),t),e.__exportStar(KUe(),t),e.__exportStar(ZUe(),t),e.__exportStar(ife(),t)})(yt);class rw{}let YUe=class extends rw{constructor(e){super()}};const PX=yt.FIVE_SECONDS,sw={pulse:"heartbeat_pulse"};let XUe=class ofe extends YUe{constructor(e){super(e),this.events=new Ql.EventEmitter,this.interval=PX,this.interval=e?.interval||PX}static async init(e){const n=new ofe(e);return await n.init(),n}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),yt.toMiliseconds(this.interval))}pulse(){this.events.emit(sw.pulse)}};const QUe=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,JUe=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,eFe=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function tFe(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){nFe(t);return}return e}function nFe(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function wA(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const n=t.trim();if(n.length<=9)switch(n.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!eFe.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(QUe.test(t)||JUe.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,tFe)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function rFe(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function fi(t,...e){try{return rFe(t(...e))}catch(n){return Promise.reject(n)}}function sFe(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function iFe(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function zI(t){if(sFe(t))return String(t);if(iFe(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return zI(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const a7="base64:";function oFe(t){return typeof t=="string"?t:a7+lFe(t)}function aFe(t){return typeof t!="string"||!t.startsWith(a7)?t:cFe(t.slice(a7.length))}function cFe(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function lFe(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Sa(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function uFe(...t){return Sa(t.join(":"))}function bA(t){return t=Sa(t),t?t+":":""}function dFe(t,e){if(e===void 0)return!0;let n=0,r=t.indexOf(":");for(;r>-1;)n++,r=t.indexOf(":",r+1);return n<=e}function fFe(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const hFe="memory",pFe=()=>{const t=new Map;return{name:hFe,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,n){t.set(e,n)},setItemRaw(e,n){t.set(e,n)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function gFe(t={}){const e={mounts:{"":t.driver||pFe()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=l=>{for(const u of e.mountpoints)if(l.startsWith(u))return{base:u,relativeKey:l.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:l,driver:e.mounts[""]}},r=(l,u)=>e.mountpoints.filter(d=>d.startsWith(l)||u&&l.startsWith(d)).map(d=>({relativeBase:l.length>d.length?l.slice(d.length):void 0,mountpoint:d,driver:e.mounts[d]})),s=(l,u)=>{if(e.watching){u=Sa(u);for(const d of e.watchListeners)d(l,u)}},i=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await kX(e.mounts[l],s,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,u,d)=>{const f=new Map,p=m=>{let y=f.get(m.base);return y||(y={driver:m.driver,base:m.base,items:[]},f.set(m.base,y)),y};for(const m of l){const y=typeof m=="string",b=Sa(y?m:m.key),v=y?void 0:m.value,x=y||!m.options?u:{...u,...m.options},E=n(b);p(E).items.push({key:b,value:v,relativeKey:E.relativeKey,options:x})}return Promise.all([...f.values()].map(m=>d(m))).then(m=>m.flat())},c={hasItem(l,u={}){l=Sa(l);const{relativeKey:d,driver:f}=n(l);return fi(f.hasItem,d,u)},getItem(l,u={}){l=Sa(l);const{relativeKey:d,driver:f}=n(l);return fi(f.getItem,d,u).then(p=>wA(p))},getItems(l,u={}){return a(l,u,d=>d.driver.getItems?fi(d.driver.getItems,d.items.map(f=>({key:f.relativeKey,options:f.options})),u).then(f=>f.map(p=>({key:uFe(d.base,p.key),value:wA(p.value)}))):Promise.all(d.items.map(f=>fi(d.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:wA(p)})))))},getItemRaw(l,u={}){l=Sa(l);const{relativeKey:d,driver:f}=n(l);return f.getItemRaw?fi(f.getItemRaw,d,u):fi(f.getItem,d,u).then(p=>aFe(p))},async setItem(l,u,d={}){if(u===void 0)return c.removeItem(l);l=Sa(l);const{relativeKey:f,driver:p}=n(l);p.setItem&&(await fi(p.setItem,f,zI(u),d),p.watch||s("update",l))},async setItems(l,u){await a(l,u,async d=>{if(d.driver.setItems)return fi(d.driver.setItems,d.items.map(f=>({key:f.relativeKey,value:zI(f.value),options:f.options})),u);d.driver.setItem&&await Promise.all(d.items.map(f=>fi(d.driver.setItem,f.relativeKey,zI(f.value),f.options)))})},async setItemRaw(l,u,d={}){if(u===void 0)return c.removeItem(l,d);l=Sa(l);const{relativeKey:f,driver:p}=n(l);if(p.setItemRaw)await fi(p.setItemRaw,f,u,d);else if(p.setItem)await fi(p.setItem,f,oFe(u),d);else return;p.watch||s("update",l)},async removeItem(l,u={}){typeof u=="boolean"&&(u={removeMeta:u}),l=Sa(l);const{relativeKey:d,driver:f}=n(l);f.removeItem&&(await fi(f.removeItem,d,u),(u.removeMeta||u.removeMata)&&await fi(f.removeItem,d+"$",u),f.watch||s("remove",l))},async getMeta(l,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),l=Sa(l);const{relativeKey:d,driver:f}=n(l),p=Object.create(null);if(f.getMeta&&Object.assign(p,await fi(f.getMeta,d,u)),!u.nativeOnly){const m=await fi(f.getItem,d+"$",u).then(y=>wA(y));m&&typeof m=="object"&&(typeof m.atime=="string"&&(m.atime=new Date(m.atime)),typeof m.mtime=="string"&&(m.mtime=new Date(m.mtime)),Object.assign(p,m))}return p},setMeta(l,u,d={}){return this.setItem(l+"$",u,d)},removeMeta(l,u={}){return this.removeItem(l+"$",u)},async getKeys(l,u={}){l=bA(l);const d=r(l,!0);let f=[];const p=[];let m=!0;for(const b of d){b.driver.flags?.maxDepth||(m=!1);const v=await fi(b.driver.getKeys,b.relativeBase,u);for(const x of v){const E=b.mountpoint+Sa(x);f.some(A=>E.startsWith(A))||p.push(E)}f=[b.mountpoint,...f.filter(x=>!x.startsWith(b.mountpoint))]}const y=u.maxDepth!==void 0&&!m;return p.filter(b=>(!y||dFe(b,u.maxDepth))&&fFe(b,l))},async clear(l,u={}){l=bA(l),await Promise.all(r(l,!1).map(async d=>{if(d.driver.clear)return fi(d.driver.clear,d.relativeBase,u);if(d.driver.removeItem){const f=await d.driver.getKeys(d.relativeBase||"",u);return Promise.all(f.map(p=>d.driver.removeItem(p,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>RX(l)))},async watch(l){return await i(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,u){if(l=bA(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((d,f)=>f.length-d.length)),e.mounts[l]=u,e.watching&&Promise.resolve(kX(u,s,l)).then(d=>{e.unwatch[l]=d}).catch(console.error),c},async unmount(l,u=!0){l=bA(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&(e.unwatch[l]?.(),delete e.unwatch[l]),u&&await RX(e.mounts[l]),e.mountpoints=e.mountpoints.filter(d=>d!==l),delete e.mounts[l])},getMount(l=""){l=Sa(l)+":";const u=n(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=Sa(l),r(l,u.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(l,u={})=>c.getKeys(l,u),get:(l,u={})=>c.getItem(l,u),set:(l,u,d={})=>c.setItem(l,u,d),has:(l,u={})=>c.hasItem(l,u),del:(l,u={})=>c.removeItem(l,u),remove:(l,u={})=>c.removeItem(l,u)};return c}function kX(t,e,n){return t.watch?t.watch((r,s)=>e(r,n+s)):()=>{}}async function RX(t){typeof t.dispose=="function"&&await fi(t.dispose)}function iw(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function afe(t,e){const n=indexedDB.open(t);n.onupgradeneeded=()=>n.result.createObjectStore(e);const r=iw(n);return(s,i)=>r.then(o=>i(o.transaction(e,s).objectStore(e)))}let T$;function JS(){return T$||(T$=afe("keyval-store","keyval")),T$}function OX(t,e=JS()){return e("readonly",n=>iw(n.get(t)))}function mFe(t,e,n=JS()){return n("readwrite",r=>(r.put(e,t),iw(r.transaction)))}function yFe(t,e=JS()){return e("readwrite",n=>(n.delete(t),iw(n.transaction)))}function wFe(t=JS()){return t("readwrite",e=>(e.clear(),iw(e.transaction)))}function bFe(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},iw(t.transaction)}function vFe(t=JS()){return t("readonly",e=>{if(e.getAllKeys)return iw(e.getAllKeys());const n=[];return bFe(e,r=>n.push(r.key)).then(()=>n)})}const xFe=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n),EFe=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,n=t.replace(e,'$1"$2n"$3');return JSON.parse(n,(r,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function yy(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return EFe(t)}catch{return t}}function Zh(t){return typeof t=="string"?t:xFe(t)||""}const CFe="idb-keyval";var _Fe=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",n=s=>e+s;let r;return t.dbName&&t.storeName&&(r=afe(t.dbName,t.storeName)),{name:CFe,options:t,async hasItem(s){return!(typeof await OX(n(s),r)>"u")},async getItem(s){return await OX(n(s),r)??null},setItem(s,i){return mFe(n(s),i,r)},removeItem(s){return yFe(n(s),r)},getKeys(){return vFe(r)},clear(){return wFe(r)}}};const SFe="WALLET_CONNECT_V2_INDEXED_DB",AFe="keyvaluestorage";let IFe=class{constructor(){this.indexedDb=gFe({driver:_Fe({dbName:SFe,storeName:AFe})})}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 n=await this.indexedDb.getItem(e);if(n!==null)return n}async setItem(e,n){await this.indexedDb.setItem(e,Zh(n))}async removeItem(e){await this.indexedDb.removeItem(e)}};var N$=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},WI={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(n){return this.hasOwnProperty(n)?String(this[n]):null},t.prototype.setItem=function(n,r){this[n]=String(r)},t.prototype.removeItem=function(n){delete this[n]},t.prototype.clear=function(){const n=this;Object.keys(n).forEach(function(r){n[r]=void 0,delete n[r]})},t.prototype.key=function(n){return n=n||0,Object.keys(this)[n]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof N$<"u"&&N$.localStorage?WI.exports=N$.localStorage:typeof window<"u"&&window.localStorage?WI.exports=window.localStorage:WI.exports=new e})();function TFe(t){var e;return[t[0],yy((e=t[1])!=null?e:"")]}let NFe=class{constructor(){this.localStorage=WI.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(TFe)}async getItem(e){const n=this.localStorage.getItem(e);if(n!==null)return yy(n)}async setItem(e,n){this.localStorage.setItem(e,Zh(n))}async removeItem(e){this.localStorage.removeItem(e)}};const PFe="wc_storage_version",$X=1,kFe=async(t,e,n)=>{const r=PFe,s=await e.getItem(r);if(s&&s>=$X){n(e);return}const i=await t.getKeys();if(!i.length){n(e);return}const o=[];for(;i.length;){const a=i.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(r,$X),n(e),RFe(t,o)},RFe=async(t,e)=>{e.length&&e.forEach(async n=>{await t.removeItem(n)})};let OFe=class{constructor(){this.initialized=!1,this.setInitialized=n=>{this.storage=n,this.initialized=!0};const e=new NFe;this.storage=e;try{const n=new IFe;kFe(e,n,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,n){return await this.initialize(),this.storage.setItem(e,n)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const n=setInterval(()=>{this.initialized&&(clearInterval(n),e())},20)})}};function $Fe(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var DFe=MFe;function MFe(t,e,n){var r=n&&n.stringify||$Fe,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=r(t);for(var a=1;a-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=c||e[u]==null)break;d=c||e[u]==null)break;d=c||e[u]===void 0)break;d",d=p+2,p++;break}l+=r(e[u]),d=p+2,p++;break;case 115:if(u>=c)break;d-1&&(i=!1);const o=["error","fatal","warn","info","debug","trace"];typeof n=="function"&&(n.error=n.fatal=n.warn=n.info=n.debug=n.trace=n),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(n);c.log||(c.log=VC),Object.defineProperty(c,"levelVal",{get:u}),Object.defineProperty(c,"level",{get:d,set:f});const l={transmit:e,serialize:s,asObject:t.browser.asObject,levels:o,timestamp:WFe(t)};c.levels=Jd.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=VC,c.serializers=r,c._serialize=s,c._stdErrSerialize=i,c.child=p,e&&(c._logEvent=c7());function u(){return this.level==="silent"?1/0:this.levels.values[this.level]}function d(){return this._level}function f(m){if(m!=="silent"&&!this.levels.values[m])throw Error("unknown level "+m);this._level=m,Kw(l,c,"error","log"),Kw(l,c,"fatal","error"),Kw(l,c,"warn","error"),Kw(l,c,"info","log"),Kw(l,c,"debug","log"),Kw(l,c,"trace","log")}function p(m,y){if(!m)throw new Error("missing bindings for child Pino");y=y||{},s&&m.serializers&&(y.serializers=m.serializers);const b=y.serializers;if(s&&b){var v=Object.assign({},r,b),x=t.browser.serialize===!0?Object.keys(v):s;delete m.serializers,ZP([m],x,v,this._stdErrSerialize)}function E(A){this._childLevel=(A._childLevel|0)+1,this.error=Gw(A,m,"error"),this.fatal=Gw(A,m,"fatal"),this.warn=Gw(A,m,"warn"),this.info=Gw(A,m,"info"),this.debug=Gw(A,m,"debug"),this.trace=Gw(A,m,"trace"),v&&(this.serializers=v,this._serialize=x),e&&(this._logEvent=c7([].concat(A._logEvent.bindings,m)))}return E.prototype=this,new E(this)}return c}Jd.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};Jd.stdSerializers=LFe;Jd.stdTimeFunctions=Object.assign({},{nullTime:cfe,epochTime:lfe,unixTime:VFe,isoTime:HFe});function Kw(t,e,n,r){const s=Object.getPrototypeOf(e);e[n]=e.levelVal>e.levels.values[n]?VC:s[n]?s[n]:WC[n]||WC[r]||VC,UFe(t,e,n)}function UFe(t,e,n){!t.transmit&&e[n]===VC||(e[n]=function(r){return function(){const i=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===WC?WC:this;for(var c=0;c-1&&i in n&&(t[s][i]=n[i](t[s][i]))}function Gw(t,e,n){return function(){const r=new Array(1+arguments.length);r[0]=e;for(var s=1;sthis.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let n=this.head;for(;n!==null;)e.push(n.value),n=n.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const n=e.value;return e=e.next,{done:!1,value:n}}}}},ufe=class{constructor(e,n=pz){this.level=e??"error",this.levelValue=xb.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new MX(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===xb.levels.values.error?console.error(e):n===xb.levels.values.warn?console.warn(e):n===xb.levels.values.debug?console.debug(e):n===xb.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Zh({timestamp:new Date().toISOString(),log:e}));const n=typeof e=="string"?JSON.parse(e).level:e.level;n>=this.levelValue&&this.forwardToConsole(e,n)}getLogs(){return this.logs}clearLogs(){this.logs=new MX(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Zh({extraMetadata:e})),new Blob(n,{type:"application/json"})}},ZFe=class{constructor(e,n=pz){this.baseChunkLogger=new ufe(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const n=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}},YFe=class{constructor(e,n=pz){this.baseChunkLogger=new ufe(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var XFe=Object.defineProperty,QFe=Object.defineProperties,JFe=Object.getOwnPropertyDescriptors,LX=Object.getOwnPropertySymbols,eje=Object.prototype.hasOwnProperty,tje=Object.prototype.propertyIsEnumerable,BX=(t,e,n)=>e in t?XFe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,yT=(t,e)=>{for(var n in e||(e={}))eje.call(e,n)&&BX(t,n,e[n]);if(LX)for(var n of LX(e))tje.call(e,n)&&BX(t,n,e[n]);return t},wT=(t,e)=>QFe(t,JFe(e));function sx(t){return wT(yT({},t),{level:t?.level||KFe.level})}function nje(t,e=t3){return t[e]||""}function rje(t,e,n=t3){return t[n]=e,t}function sc(t,e=t3){let n="";return typeof t.bindings>"u"?n=nje(t,e):n=t.bindings().context||"",n}function sje(t,e,n=t3){const r=sc(t,n);return r.trim()?`${r}/${e}`:e}function Mo(t,e,n=t3){const r=sje(t,e,n),s=t.child({context:r});return rje(s,r,n)}function ije(t){var e,n;const r=new ZFe((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:e3(wT(yT({},t.opts),{level:"trace",browser:wT(yT({},(n=t.opts)==null?void 0:n.browser),{write:s=>r.write(s)})})),chunkLoggerController:r}}function oje(t){var e;const n=new YFe((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:e3(wT(yT({},t.opts),{level:"trace"}),n),chunkLoggerController:n}}function gz(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?ije(t):oje(t)}var aje=Object.defineProperty,cje=(t,e,n)=>e in t?aje(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,UX=(t,e,n)=>cje(t,typeof e!="symbol"?e+"":e,n);let lje=class extends rw{constructor(e){super(),this.opts=e,UX(this,"protocol","wc"),UX(this,"version",2)}};var uje=Object.defineProperty,dje=(t,e,n)=>e in t?uje(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fje=(t,e,n)=>dje(t,e+"",n);let hje=class extends rw{constructor(e,n){super(),this.core=e,this.logger=n,fje(this,"records",new Map)}},pje=class{constructor(e,n){this.logger=e,this.core=n}},gje=class extends rw{constructor(e,n){super(),this.relayer=e,this.logger=n}},mje=class extends rw{constructor(e){super()}},yje=class{constructor(e,n,r,s){this.core=e,this.logger=n,this.name=r}},wje=class extends rw{constructor(e,n){super(),this.relayer=e,this.logger=n}},bje=class extends rw{constructor(e,n){super(),this.core=e,this.logger=n}},vje=class{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}},xje=class{constructor(e,n){this.projectId=e,this.logger=n}},Eje=class{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}};var Cje=Object.defineProperty,_je=(t,e,n)=>e in t?Cje(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,FX=(t,e,n)=>_je(t,typeof e!="symbol"?e+"":e,n);let Sje=class{constructor(e){this.opts=e,FX(this,"protocol","wc"),FX(this,"version",2)}},Aje=class{constructor(e){this.client=e}};function Ije(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function dfe(t,...e){if(!Ije(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function jX(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Tje(t,e){dfe(t);const n=e.outputLen;if(t.lengthnew DataView(t.buffer,t.byteOffset,t.byteLength);function Nje(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function ffe(t){return typeof t=="string"&&(t=Nje(t)),dfe(t),t}let Pje=class{clone(){return this._cloneInto()}};function kje(t){const e=r=>t().update(ffe(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function hfe(t=32){if(Zw&&typeof Zw.getRandomValues=="function")return Zw.getRandomValues(new Uint8Array(t));if(Zw&&typeof Zw.randomBytes=="function")return Zw.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Rje(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}let Oje=class extends Pje{constructor(e,n,r,s){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=k$(this.buffer)}update(e){jX(this);const{view:n,buffer:r,blockLen:s}=this;e=ffe(e);const i=e.length;for(let o=0;os-o&&(this.process(r,0),o=0);for(let d=o;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d>l7&xA)}:{h:Number(t>>l7&xA)|0,l:Number(t&xA)|0}}function $je(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;sBigInt(t>>>0)<>>0),Mje=(t,e,n)=>t>>>n,Lje=(t,e,n)=>t<<32-n|e>>>n,Bje=(t,e,n)=>t>>>n|e<<32-n,Uje=(t,e,n)=>t<<32-n|e>>>n,Fje=(t,e,n)=>t<<64-n|e>>>n-32,jje=(t,e,n)=>t>>>n-32|e<<64-n,zje=(t,e)=>e,Wje=(t,e)=>t,Vje=(t,e,n)=>t<>>32-n,Hje=(t,e,n)=>e<>>32-n,qje=(t,e,n)=>e<>>64-n,Kje=(t,e,n)=>t<>>64-n;function Gje(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}const Zje=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Yje=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Xje=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Qje=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,Jje=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),eze=(t,e,n,r,s,i)=>e+n+r+s+i+(t/2**32|0)|0,Bn={fromBig:pfe,split:$je,toBig:Dje,shrSH:Mje,shrSL:Lje,rotrSH:Bje,rotrSL:Uje,rotrBH:Fje,rotrBL:jje,rotr32H:zje,rotr32L:Wje,rotlSH:Vje,rotlSL:Hje,rotlBH:qje,rotlBL:Kje,add:Gje,add3L:Zje,add3H:Yje,add4L:Xje,add4H:Qje,add5H:eze,add5L:Jje},[tze,nze]=Bn.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Hp=new Uint32Array(80),qp=new Uint32Array(80);let rze=class extends Oje{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:n,Bh:r,Bl:s,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:p,Gl:m,Hh:y,Hl:b}=this;return[e,n,r,s,i,o,a,c,l,u,d,f,p,m,y,b]}set(e,n,r,s,i,o,a,c,l,u,d,f,p,m,y,b){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=p|0,this.Gl=m|0,this.Hh=y|0,this.Hl=b|0}process(e,n){for(let E=0;E<16;E++,n+=4)Hp[E]=e.getUint32(n),qp[E]=e.getUint32(n+=4);for(let E=16;E<80;E++){const A=Hp[E-15]|0,_=qp[E-15]|0,k=Bn.rotrSH(A,_,1)^Bn.rotrSH(A,_,8)^Bn.shrSH(A,_,7),B=Bn.rotrSL(A,_,1)^Bn.rotrSL(A,_,8)^Bn.shrSL(A,_,7),W=Hp[E-2]|0,S=qp[E-2]|0,$=Bn.rotrSH(W,S,19)^Bn.rotrBH(W,S,61)^Bn.shrSH(W,S,6),R=Bn.rotrSL(W,S,19)^Bn.rotrBL(W,S,61)^Bn.shrSL(W,S,6),M=Bn.add4L(B,R,qp[E-7],qp[E-16]),j=Bn.add4H(M,k,$,Hp[E-7],Hp[E-16]);Hp[E]=j|0,qp[E]=M|0}let{Ah:r,Al:s,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:p,Fl:m,Gh:y,Gl:b,Hh:v,Hl:x}=this;for(let E=0;E<80;E++){const A=Bn.rotrSH(d,f,14)^Bn.rotrSH(d,f,18)^Bn.rotrBH(d,f,41),_=Bn.rotrSL(d,f,14)^Bn.rotrSL(d,f,18)^Bn.rotrBL(d,f,41),k=d&p^~d&y,B=f&m^~f&b,W=Bn.add5L(x,_,B,nze[E],qp[E]),S=Bn.add5H(W,v,A,k,tze[E],Hp[E]),$=W|0,R=Bn.rotrSH(r,s,28)^Bn.rotrBH(r,s,34)^Bn.rotrBH(r,s,39),M=Bn.rotrSL(r,s,28)^Bn.rotrBL(r,s,34)^Bn.rotrBL(r,s,39),j=r&i^r&a^i&a,z=s&o^s&c^o&c;v=y|0,x=b|0,y=p|0,b=m|0,p=d|0,m=f|0,{h:d,l:f}=Bn.add(l|0,u|0,S|0,$|0),l=a|0,u=c|0,a=i|0,c=o|0,i=r|0,o=s|0;const N=Bn.add3L($,M,z);r=Bn.add3H(N,S,R,j),s=N|0}({h:r,l:s}=Bn.add(this.Ah|0,this.Al|0,r|0,s|0)),{h:i,l:o}=Bn.add(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Bn.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Bn.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=Bn.add(this.Eh|0,this.El|0,d|0,f|0),{h:p,l:m}=Bn.add(this.Fh|0,this.Fl|0,p|0,m|0),{h:y,l:b}=Bn.add(this.Gh|0,this.Gl|0,y|0,b|0),{h:v,l:x}=Bn.add(this.Hh|0,this.Hl|0,v|0,x|0),this.set(r,s,i,o,a,c,l,u,d,f,p,m,y,b,v,x)}roundClean(){Hp.fill(0),qp.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};const sze=kje(()=>new rze);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const mz=BigInt(0),gfe=BigInt(1),ize=BigInt(2);function yz(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wz(t){if(!yz(t))throw new Error("Uint8Array expected")}function R$(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const oze=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function bz(t){wz(t);let e="";for(let n=0;n=Zf._0&&t<=Zf._9)return t-Zf._0;if(t>=Zf.A&&t<=Zf.F)return t-(Zf.A-10);if(t>=Zf.a&&t<=Zf.f)return t-(Zf.a-10)}function yfe(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let s=0,i=0;stypeof t=="bigint"&&mz<=t;function cze(t,e,n){return O$(t)&&O$(e)&&O$(n)&&e<=t&&tmz;t>>=gfe,e+=1);return e}const uze=t=>(ize<typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||yz(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function vz(t,e,n={}){const r=(s,i,o)=>{const a=dze[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))r(s,i,!1);for(const[s,i]of Object.entries(n))r(s,i,!0);return t}function VX(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const i=t(n,...r);return e.set(n,i),i}}const wi=BigInt(0),$s=BigInt(1),cm=BigInt(2),fze=BigInt(3),d7=BigInt(4),HX=BigInt(5),qX=BigInt(8);function ri(t,e){const n=t%e;return n>=wi?n:e+n}function hze(t,e,n){if(ewi;)e&$s&&(r=r*t%n),t=t*t%n,e>>=$s;return r}function Ad(t,e,n){let r=t;for(;e-- >wi;)r*=r,r%=n;return r}function KX(t,e){if(t===wi)throw new Error("invert: expected non-zero number");if(e<=wi)throw new Error("invert: expected positive modulus, got "+e);let n=ri(t,e),r=e,s=wi,i=$s;for(;n!==wi;){const o=r/n,a=r%n,c=s-i*o;r=n,n=a,s=i,i=c}if(r!==$s)throw new Error("invert: does not exist");return ri(s,e)}function pze(t){const e=(t-$s)/cm;let n,r,s;for(n=t-$s,r=0;n%cm===wi;n/=cm,r++);for(s=cm;s1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+$s)/d7;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const i=(n+$s)/cm;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,l=o.pow(o.mul(o.ONE,s),n),u=o.pow(a,i),d=o.pow(a,n);for(;!o.eql(d,o.ONE);){if(o.eql(d,o.ZERO))return o.ZERO;let f=1;for(let m=o.sqr(d);f(ri(t,e)&$s)===$s,yze=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function wze(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=yze.reduce((r,s)=>(r[s]="function",r),e);return vz(t,n)}function bze(t,e,n){if(nwi;)n&$s&&(r=t.mul(r,s)),s=t.sqr(s),n>>=$s;return r}function vze(t,e){const n=new Array(e.length),r=e.reduce((i,o,a)=>t.is0(o)?i:(n[a]=i,t.mul(i,o)),t.ONE),s=t.inv(r);return e.reduceRight((i,o,a)=>t.is0(o)?i:(n[a]=t.mul(i,n[a]),t.mul(i,o)),s),n}function bfe(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function vfe(t,e,n=!1,r={}){if(t<=wi)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=bfe(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:s,BYTES:i,MASK:uze(s),ZERO:wi,ONE:$s,create:c=>ri(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return wi<=c&&cc===wi,isOdd:c=>(c&$s)===$s,neg:c=>ri(-c,t),eql:(c,l)=>c===l,sqr:c=>ri(c*c,t),add:(c,l)=>ri(c+l,t),sub:(c,l)=>ri(c-l,t),mul:(c,l)=>ri(c*l,t),pow:(c,l)=>bze(a,c,l),div:(c,l)=>ri(c*KX(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>KX(c,t),sqrt:r.sqrt||(c=>(o||(o=gze(t)),o(a,c))),invertBatch:c=>vze(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>n?u7(c,i):wfe(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return n?VI(c):aze(c)}});return Object.freeze(a)}const GX=BigInt(0),EA=BigInt(1);function $$(t,e){const n=e.negate();return t?n:e}function xfe(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function D$(t,e){xfe(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1);return{windows:n,windowSize:r}}function xze(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function Eze(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const M$=new WeakMap,Efe=new WeakMap;function L$(t){return Efe.get(t)||1}function Cze(t,e){return{constTimeNegate:$$,hasPrecomputes(n){return L$(n)!==1},unsafeLadder(n,r,s=t.ZERO){let i=n;for(;r>GX;)r&EA&&(s=s.add(i)),i=i.double(),r>>=EA;return s},precomputeWindow(n,r){const{windows:s,windowSize:i}=D$(r,e),o=[];let a=n,c=a;for(let l=0;l>=d,m>o&&(m-=u,s+=EA);const y=p,b=p+Math.abs(m)-1,v=f%2!==0,x=m<0;m===0?c=c.add($$(v,r[y])):a=a.add($$(x,r[b]))}return{p:a,f:c}},wNAFUnsafe(n,r,s,i=t.ZERO){const{windows:o,windowSize:a}=D$(n,e),c=BigInt(2**n-1),l=2**n,u=BigInt(n);for(let d=0;d>=u,p>a&&(p-=l,s+=EA),p===0)continue;let m=r[f+Math.abs(p)-1];p<0&&(m=m.negate()),i=i.add(m)}return i},getPrecomputes(n,r,s){let i=M$.get(r);return i||(i=this.precomputeWindow(r,n),n!==1&&M$.set(r,s(i))),i},wNAFCached(n,r,s){const i=L$(n);return this.wNAF(i,this.getPrecomputes(i,n,s),r)},wNAFCachedUnsafe(n,r,s,i){const o=L$(n);return o===1?this.unsafeLadder(n,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,n,s),r,i)},setWindowSize(n,r){xfe(r,e),Efe.set(n,r),M$.delete(n)}}}function _ze(t,e,n,r){if(xze(n,t),Eze(r,e),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,i=lze(BigInt(n.length)),o=i>12?i-3:i>4?i-2:i?2:1,a=(1<=0;d-=o){c.fill(s);for(let p=0;p>BigInt(d)&BigInt(a));c[y]=c[y].add(n[p])}let f=s;for(let p=c.length-1,m=s;p>0;p--)m=m.add(c[p]),f=f.add(m);if(u=u.add(f),d!==0)for(let p=0;p{try{return{isValid:!0,value:n.sqrt(N*n.inv(T))}}catch{return{isValid:!1,value:pu}}}),p=e.adjustScalarBytes||(N=>N),m=e.domain||((N,T,U)=>{if(R$("phflag",U),T.length||U)throw new Error("Contexts/pre-hash are not supported");return N});function y(N,T){i2("coordinate "+N,T,pu,l)}function b(N){if(!(N instanceof E))throw new Error("ExtendedPoint expected")}const v=VX((N,T)=>{const{ex:U,ey:L,ez:P}=N,H=N.is0();T==null&&(T=H?Aze:n.inv(P));const Y=u(U*T),re=u(L*T),de=u(P*T);if(H)return{x:pu,y:xa};if(de!==xa)throw new Error("invZ was invalid");return{x:Y,y:re}}),x=VX(N=>{const{a:T,d:U}=e;if(N.is0())throw new Error("bad point: ZERO");const{ex:L,ey:P,ez:H,et:Y}=N,re=u(L*L),de=u(P*P),fe=u(H*H),ve=u(fe*fe),Ee=u(re*T),oe=u(fe*u(Ee+de)),Oe=u(ve+u(U*u(re*de)));if(oe!==Oe)throw new Error("bad point: equation left != right (1)");const je=u(L*P),V=u(H*Y);if(je!==V)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(T,U,L,P){this.ex=T,this.ey=U,this.ez=L,this.et=P,y("x",T),y("y",U),y("z",L),y("t",P),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(T){if(T instanceof E)throw new Error("extended point not allowed");const{x:U,y:L}=T||{};return y("x",U),y("y",L),new E(U,L,xa,u(U*L))}static normalizeZ(T){const U=n.invertBatch(T.map(L=>L.ez));return T.map((L,P)=>L.toAffine(U[P])).map(E.fromAffine)}static msm(T,U){return _ze(E,d,T,U)}_setWindowSize(T){k.setWindowSize(this,T)}assertValidity(){x(this)}equals(T){b(T);const{ex:U,ey:L,ez:P}=this,{ex:H,ey:Y,ez:re}=T,de=u(U*re),fe=u(H*P),ve=u(L*re),Ee=u(Y*P);return de===fe&&ve===Ee}is0(){return this.equals(E.ZERO)}negate(){return new E(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:T}=e,{ex:U,ey:L,ez:P}=this,H=u(U*U),Y=u(L*L),re=u(CA*u(P*P)),de=u(T*H),fe=U+L,ve=u(u(fe*fe)-H-Y),Ee=de+Y,oe=Ee-re,Oe=de-Y,je=u(ve*oe),V=u(Ee*Oe),we=u(ve*Oe),Ae=u(oe*Ee);return new E(je,V,Ae,we)}add(T){b(T);const{a:U,d:L}=e,{ex:P,ey:H,ez:Y,et:re}=this,{ex:de,ey:fe,ez:ve,et:Ee}=T;if(U===BigInt(-1)){const ie=u((H-P)*(fe+de)),ae=u((H+P)*(fe-de)),Pe=u(ae-ie);if(Pe===pu)return this.double();const $e=u(Y*CA*Ee),Re=u(re*CA*ve),ut=Re+$e,Je=ae+ie,ft=Re-$e,Z=u(ut*Pe),O=u(Je*ft),F=u(ut*ft),ne=u(Pe*Je);return new E(Z,O,ne,F)}const oe=u(P*de),Oe=u(H*fe),je=u(re*L*Ee),V=u(Y*ve),we=u((P+H)*(de+fe)-oe-Oe),Ae=V-je,Ie=V+je,ge=u(Oe-U*oe),Me=u(we*Ae),be=u(Ie*ge),pe=u(we*ge),J=u(Ae*Ie);return new E(Me,be,J,pe)}subtract(T){return this.add(T.negate())}wNAF(T){return k.wNAFCached(this,T,E.normalizeZ)}multiply(T){const U=T;i2("scalar",U,xa,r);const{p:L,f:P}=this.wNAF(U);return E.normalizeZ([L,P])[0]}multiplyUnsafe(T,U=E.ZERO){const L=T;return i2("scalar",L,pu,r),L===pu?_:this.is0()||L===xa?this:k.wNAFCachedUnsafe(this,L,E.normalizeZ,U)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return k.unsafeLadder(this,r).is0()}toAffine(T){return v(this,T)}clearCofactor(){const{h:T}=e;return T===xa?this:this.multiplyUnsafe(T)}static fromHex(T,U=!1){const{d:L,a:P}=e,H=n.BYTES;T=Yf("pointHex",T,H),R$("zip215",U);const Y=T.slice(),re=T[H-1];Y[H-1]=re&-129;const de=VI(Y),fe=U?l:n.ORDER;i2("pointHex.y",de,pu,fe);const ve=u(de*de),Ee=u(ve-xa),oe=u(L*ve-P);let{isValid:Oe,value:je}=f(Ee,oe);if(!Oe)throw new Error("Point.fromHex: invalid y coordinate");const V=(je&xa)===xa,we=(re&128)!==0;if(!U&&je===pu&&we)throw new Error("Point.fromHex: x=0 and x_0=1");return we!==V&&(je=u(-je)),E.fromAffine({x:je,y:de})}static fromPrivateKey(T){return S(T).point}toRawBytes(){const{x:T,y:U}=this.toAffine(),L=u7(U,n.BYTES);return L[L.length-1]|=T&xa?128:0,L}toHex(){return bz(this.toRawBytes())}}E.BASE=new E(e.Gx,e.Gy,xa,u(e.Gx*e.Gy)),E.ZERO=new E(pu,xa,xa,pu);const{BASE:A,ZERO:_}=E,k=Cze(E,a*8);function B(N){return ri(N,r)}function W(N){return B(VI(N))}function S(N){const T=n.BYTES;N=Yf("private key",N,T);const U=Yf("hashed private key",i(N),2*T),L=p(U.slice(0,T)),P=U.slice(T,2*T),H=W(L),Y=A.multiply(H),re=Y.toRawBytes();return{head:L,prefix:P,scalar:H,point:Y,pointBytes:re}}function $(N){return S(N).pointBytes}function R(N=new Uint8Array,...T){const U=WX(...T);return W(i(m(U,Yf("context",N),!!s)))}function M(N,T,U={}){N=Yf("message",N),s&&(N=s(N));const{prefix:L,scalar:P,pointBytes:H}=S(T),Y=R(U.context,L,N),re=A.multiply(Y).toRawBytes(),de=R(U.context,re,H,N),fe=B(Y+de*P);i2("signature.s",fe,pu,r);const ve=WX(re,u7(fe,n.BYTES));return Yf("result",ve,n.BYTES*2)}const j=Ize;function z(N,T,U,L=j){const{context:P,zip215:H}=L,Y=n.BYTES;N=Yf("signature",N,2*Y),T=Yf("message",T),U=Yf("publicKey",U,Y),H!==void 0&&R$("zip215",H),s&&(T=s(T));const re=VI(N.slice(Y,2*Y));let de,fe,ve;try{de=E.fromHex(U,H),fe=E.fromHex(N.slice(0,Y),H),ve=A.multiplyUnsafe(re)}catch{return!1}if(!H&&de.isSmallOrder())return!1;const Ee=R(P,fe.toRawBytes(),de.toRawBytes(),T);return fe.add(de.multiplyUnsafe(Ee)).subtract(ve).clearCofactor().equals(E.ZERO)}return A._setWindowSize(8),{CURVE:e,getPublicKey:$,sign:M,verify:z,ExtendedPoint:E,utils:{getExtendedPublicKey:S,randomPrivateKey:()=>o(n.BYTES),precompute(N=8,T=E.BASE){return T._setWindowSize(N),T.multiply(BigInt(3)),T}}}}BigInt(0),BigInt(1);const xz=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ZX=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Pze=BigInt(1),YX=BigInt(2);BigInt(3);const kze=BigInt(5),Rze=BigInt(8);function Oze(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=xz,o=t*t%i*t%i,a=Ad(o,YX,i)*o%i,c=Ad(a,Pze,i)*t%i,l=Ad(c,kze,i)*c%i,u=Ad(l,e,i)*l%i,d=Ad(u,n,i)*u%i,f=Ad(d,r,i)*d%i,p=Ad(f,s,i)*f%i,m=Ad(p,s,i)*f%i,y=Ad(m,e,i)*l%i;return{pow_p_5_8:Ad(y,YX,i)*t%i,b2:o}}function $ze(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Dze(t,e){const n=xz,r=ri(e*e*e,n),s=ri(r*r*e,n),i=Oze(t*s).pow_p_5_8;let o=ri(t*r*i,n);const a=ri(e*o*o,n),c=o,l=ri(o*ZX,n),u=a===t,d=a===ri(-t,n),f=a===ri(-t*ZX,n);return u&&(o=c),(d||f)&&(o=l),mze(o,n)&&(o=ri(-o,n)),{isValid:u||d,value:o}}const Mze=vfe(xz,void 0,!0),Lze={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Mze,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Rze,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:sze,randomBytes:hfe,adjustScalarBytes:$ze,uvRatio:Dze},Cfe=Nze(Lze),Bze="EdDSA",Uze="JWT",bT=".",YP="base64url",_fe="utf8",Sfe="utf8",Fze=":",jze="did",zze="key",XX="base58btc",Wze="z",Vze="K36",Hze=32;function Ez(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Afe(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ez(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Ife(t,e){e||(e=t.reduce((s,i)=>s+i.length,0));const n=Afe(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return Ez(n)}function qze(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r>>0,A=new Uint8Array(E);v!==x;){for(var _=m[v],k=0,B=E-1;(_!==0||k>>0,A[B]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");b=k,v++}for(var W=E-b;W!==E&&A[W]===0;)W++;for(var S=c.repeat(y);W>>0,E=new Uint8Array(x);m[y];){var A=n[m.charCodeAt(y)];if(A===255)return;for(var _=0,k=x-1;(A!==0||_>>0,E[k]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");v=_,y++}if(m[y]!==" "){for(var B=x-v;B!==x&&E[B]===0;)B++;for(var W=new Uint8Array(b+(x-B)),S=b;B!==x;)W[S++]=E[B++];return W}}}function p(m){var y=f(m);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:p}}var Kze=qze,Gze=Kze;const Tfe=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Zze=t=>new TextEncoder().encode(t),Yze=t=>new TextDecoder().decode(t);let Xze=class{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Qze=class{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Nfe(this,e)}},Jze=class{constructor(e){this.decoders=e}or(e){return Nfe(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Nfe=(t,e)=>new Jze({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let eWe=class{constructor(e,n,r,s){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new Xze(e,n,r),this.decoder=new Qze(e,n,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const XP=({name:t,prefix:e,encode:n,decode:r})=>new eWe(t,e,n,r),n3=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:s}=Gze(n,e);return XP({prefix:t,name:e,encode:r,decode:i=>Tfe(s(i))})},tWe=(t,e,n,r)=>{const s={};for(let u=0;u=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},nWe=(t,e,n)=>{const r=e[e.length-1]==="=",s=(1<n;)o-=n,i+=e[s&a>>o];if(o&&(i+=e[s&a<XP({prefix:e,name:t,encode(s){return nWe(s,r,n)},decode(s){return tWe(s,r,n,t)}}),rWe=XP({prefix:"\0",name:"identity",encode:t=>Yze(t),decode:t=>Zze(t)});var sWe=Object.freeze({__proto__:null,identity:rWe});const iWe=Yi({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var oWe=Object.freeze({__proto__:null,base2:iWe});const aWe=Yi({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var cWe=Object.freeze({__proto__:null,base8:aWe});const lWe=n3({prefix:"9",name:"base10",alphabet:"0123456789"});var uWe=Object.freeze({__proto__:null,base10:lWe});const dWe=Yi({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),fWe=Yi({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hWe=Object.freeze({__proto__:null,base16:dWe,base16upper:fWe});const pWe=Yi({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),gWe=Yi({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),mWe=Yi({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yWe=Yi({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),wWe=Yi({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),bWe=Yi({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),vWe=Yi({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),xWe=Yi({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),EWe=Yi({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var CWe=Object.freeze({__proto__:null,base32:pWe,base32upper:gWe,base32pad:mWe,base32padupper:yWe,base32hex:wWe,base32hexupper:bWe,base32hexpad:vWe,base32hexpadupper:xWe,base32z:EWe});const _We=n3({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),SWe=n3({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var AWe=Object.freeze({__proto__:null,base36:_We,base36upper:SWe});const IWe=n3({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),TWe=n3({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var NWe=Object.freeze({__proto__:null,base58btc:IWe,base58flickr:TWe});const PWe=Yi({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kWe=Yi({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),RWe=Yi({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),OWe=Yi({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var $We=Object.freeze({__proto__:null,base64:PWe,base64pad:kWe,base64url:RWe,base64urlpad:OWe});const Pfe=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),DWe=Pfe.reduce((t,e,n)=>(t[n]=e,t),[]),MWe=Pfe.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function LWe(t){return t.reduce((e,n)=>(e+=DWe[n],e),"")}function BWe(t){const e=[];for(const n of t){const r=MWe[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const UWe=XP({prefix:"🚀",name:"base256emoji",encode:LWe,decode:BWe});var FWe=Object.freeze({__proto__:null,base256emoji:UWe}),jWe=kfe,QX=128,zWe=127,WWe=~zWe,VWe=Math.pow(2,31);function kfe(t,e,n){e=e||[],n=n||0;for(var r=n;t>=VWe;)e[n++]=t&255|QX,t/=128;for(;t&WWe;)e[n++]=t&255|QX,t>>>=7;return e[n]=t|0,kfe.bytes=n-r+1,e}var HWe=f7,qWe=128,JX=127;function f7(t,r){var n=0,r=r||0,s=0,i=r,o,a=t.length;do{if(i>=a)throw f7.bytes=0,new RangeError("Could not decode varint");o=t[i++],n+=s<28?(o&JX)<=qWe);return f7.bytes=i-r,n}var KWe=Math.pow(2,7),GWe=Math.pow(2,14),ZWe=Math.pow(2,21),YWe=Math.pow(2,28),XWe=Math.pow(2,35),QWe=Math.pow(2,42),JWe=Math.pow(2,49),eVe=Math.pow(2,56),tVe=Math.pow(2,63),nVe=function(t){return t(Rfe.encode(t,e,n),e),tQ=t=>Rfe.encodingLength(t),h7=(t,e)=>{const n=e.byteLength,r=tQ(t),s=r+tQ(n),i=new Uint8Array(s+n);return eQ(t,i,0),eQ(n,i,r),i.set(e,s),new sVe(t,n,e,i)};let sVe=class{constructor(e,n,r,s){this.code=e,this.size=n,this.digest=r,this.bytes=s}};const Ofe=({name:t,code:e,encode:n})=>new iVe(t,e,n);let iVe=class{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?h7(this.code,n):n.then(r=>h7(this.code,r))}else throw Error("Unknown type, must be binary type")}};const $fe=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),oVe=Ofe({name:"sha2-256",code:18,encode:$fe("SHA-256")}),aVe=Ofe({name:"sha2-512",code:19,encode:$fe("SHA-512")});var cVe=Object.freeze({__proto__:null,sha256:oVe,sha512:aVe});const Dfe=0,lVe="identity",Mfe=Tfe,uVe=t=>h7(Dfe,Mfe(t)),dVe={code:Dfe,name:lVe,encode:Mfe,digest:uVe};var fVe=Object.freeze({__proto__:null,identity:dVe});new TextEncoder,new TextDecoder;const nQ={...sWe,...oWe,...cWe,...uWe,...hWe,...CWe,...AWe,...NWe,...$We,...FWe};({...cVe,...fVe});function Lfe(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const rQ=Lfe("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),B$=Lfe("ascii","a",t=>{let e="a";for(let n=0;n{t=t.substring(1);const e=Afe(t.length);for(let n=0;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new EVe:typeof navigator<"u"?TVe(navigator.userAgent):PVe()}function IVe(t){return t!==""&&SVe.reduce(function(e,n){var r=n[0],s=n[1];if(e)return e;var i=s.exec(t);return!!i&&[r,i]},!1)}function TVe(t){var e=IVe(t);if(!e)return null;var n=e[0],r=e[1];if(n==="searchbot")return new xVe;var s=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);s?s.length-1){const b=m.getAttribute("href");if(b)if(b.toLowerCase().indexOf("https:")===-1&&b.toLowerCase().indexOf("http:")===-1&&b.indexOf("//")!==0){let v=e.protocol+"//"+e.host;if(b.indexOf("/")===0)v+=b;else{const x=e.pathname.split("/");x.pop();const E=x.join("/");v+=E+"/"+b}f.push(v)}else if(b.indexOf("//")===0){const v=e.protocol+b;f.push(v)}else f.push(b)}}return f}function r(...d){const f=t.getElementsByTagName("meta");for(let p=0;pm.getAttribute(b)).filter(b=>b?d.includes(b):!1);if(y.length&&y){const b=m.getAttribute("content");if(b)return b}}return""}function s(){let d=r("name","og:site_name","og:title","twitter:title");return d||(d=t.title),d}function i(){return r("description","og:description","twitter:description","keywords")}const o=s(),a=i(),c=e.origin,l=n();return{description:a,url:c,icons:l,name:o}}jfe=_z.getWindowMetadata=zVe;function HC(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function g7(t){return HC(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const zfe="2.31.0";let U$={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:n})=>e?`${t??"https://viem.sh"}${e}${n?`#${n}`:""}`:void 0,version:`viem@${zfe}`};class by extends Error{constructor(e,n={}){const r=n.cause instanceof by?n.cause.details:n.cause?.message?n.cause.message:n.details,s=n.cause instanceof by&&n.cause.docsPath||n.docsPath,i=U$.getDocsUrl?.({...n,docsPath:s}),o=[e||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...r?[`Details: ${r}`]:[],...U$.version?[`Version: ${U$.version}`]:[]].join(` +`);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=s,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=e,this.version=zfe}walk(e){return Wfe(this,e)}}function Wfe(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Wfe(t.cause,e):e?null:t}class Vfe extends by{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${n}).`,{name:"SizeExceedsPaddingSizeError"})}}function ax(t,{dir:e,size:n=32}={}){return typeof t=="string"?WVe(t,{dir:e,size:n}):VVe(t,{dir:e,size:n})}function WVe(t,{dir:e,size:n=32}={}){if(n===null)return t;const r=t.replace("0x","");if(r.length>n*2)throw new Vfe({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](n*2,"0")}`}function VVe(t,{dir:e,size:n=32}={}){if(n===null)return t;if(t.length>n)throw new Vfe({size:t.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let s=0;se)throw new qVe({givenSize:g7(t),maxSize:e})}function m7(t,e={}){const{signed:n}=e;e.size&&cx(t,{size:e.size});const r=BigInt(t);if(!n)return r;const s=(t.length-2)/2,i=(1n<e.toString(16).padStart(2,"0"));function y7(t,e={}){return typeof t=="number"||typeof t=="bigint"?qfe(t,e):typeof t=="string"?XVe(t,e):typeof t=="boolean"?ZVe(t,e):Hfe(t,e)}function ZVe(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(cx(n,{size:e.size}),ax(n,{size:e.size})):n}function Hfe(t,e={}){let n="";for(let s=0;si||s=Xf.zero&&t<=Xf.nine)return t-Xf.zero;if(t>=Xf.A&&t<=Xf.F)return t-(Xf.A-10);if(t>=Xf.a&&t<=Xf.f)return t-(Xf.a-10)}function Kfe(t,e={}){let n=t;e.size&&(cx(n,{size:e.size}),n=ax(n,{dir:"right",size:e.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const s=r.length/2,i=new Uint8Array(s);for(let o=0,a=0;othis.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const F$=new nHe(8192);function rHe(t,e){if(F$.has(`${t}.${e}`))return F$.get(`${t}.${e}`);const n=t.substring(2).toLowerCase(),r=Zfe(Gfe(n),"bytes"),s=n.split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(r[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const i=`0x${s.join("")}`;return F$.set(`${t}.${e}`,i),i}function sHe(t){const e=Zfe(`0x${t.substring(4)}`).substring(26);return rHe(`0x${e}`)}async function iHe({hash:t,signature:e}){const n=HC(t)?t:y7(t),{secp256k1:r}=await et(async()=>{const{secp256k1:o}=await import("./secp256k1-BjJYwyg8.js");return{secp256k1:o}},[]);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:d,yParity:f}=e,p=Number(f??d),m=dQ(p);return new r.Signature(m7(l),m7(u)).addRecoveryBit(m)}const o=HC(e)?e:y7(e);if(g7(o)!==65)throw new Error("invalid signature length");const a=KVe(`0x${o.slice(130)}`),c=dQ(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(n.substring(2)).toHex(!1)}`}function dQ(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function oHe({hash:t,signature:e}){return sHe(await iHe({hash:t,signature:e}))}var lx={};const xT=Zy(URe);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.notImplemented=t.bitMask=t.utf8ToBytes=t.randomBytes=t.isBytes=t.hexToBytes=t.concatBytes=t.bytesToUtf8=t.bytesToHex=t.anumber=t.abytes=void 0,t.abool=i,t.numberToHexUnpadded=o,t.hexToNumber=a,t.bytesToNumberBE=c,t.bytesToNumberLE=l,t.numberToBytesBE=u,t.numberToBytesLE=d,t.numberToVarBytesBE=f,t.ensureBytes=p,t.equalBytes=m,t.inRange=b,t.aInRange=v,t.bitLen=x,t.bitGet=E,t.bitSet=A,t.createHmacDrbg=k,t.validateObject=W,t.isHash=S,t._validateObject=$,t.memoized=M;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const e=xT;var n=xT;Object.defineProperty(t,"abytes",{enumerable:!0,get:function(){return n.abytes}}),Object.defineProperty(t,"anumber",{enumerable:!0,get:function(){return n.anumber}}),Object.defineProperty(t,"bytesToHex",{enumerable:!0,get:function(){return n.bytesToHex}}),Object.defineProperty(t,"bytesToUtf8",{enumerable:!0,get:function(){return n.bytesToUtf8}}),Object.defineProperty(t,"concatBytes",{enumerable:!0,get:function(){return n.concatBytes}}),Object.defineProperty(t,"hexToBytes",{enumerable:!0,get:function(){return n.hexToBytes}}),Object.defineProperty(t,"isBytes",{enumerable:!0,get:function(){return n.isBytes}}),Object.defineProperty(t,"randomBytes",{enumerable:!0,get:function(){return n.randomBytes}}),Object.defineProperty(t,"utf8ToBytes",{enumerable:!0,get:function(){return n.utf8ToBytes}});const r=BigInt(0),s=BigInt(1);function i(j,z){if(typeof z!="boolean")throw new Error(j+" boolean expected, got "+z)}function o(j){const z=j.toString(16);return z.length&1?"0"+z:z}function a(j){if(typeof j!="string")throw new Error("hex string expected, got "+typeof j);return j===""?r:BigInt("0x"+j)}function c(j){return a((0,e.bytesToHex)(j))}function l(j){return(0,e.abytes)(j),a((0,e.bytesToHex)(Uint8Array.from(j).reverse()))}function u(j,z){return(0,e.hexToBytes)(j.toString(16).padStart(z*2,"0"))}function d(j,z){return u(j,z).reverse()}function f(j){return(0,e.hexToBytes)(o(j))}function p(j,z,N){let T;if(typeof z=="string")try{T=(0,e.hexToBytes)(z)}catch(L){throw new Error(j+" must be hex string or Uint8Array, cause: "+L)}else if((0,e.isBytes)(z))T=Uint8Array.from(z);else throw new Error(j+" must be hex string or Uint8Array");const U=T.length;if(typeof N=="number"&&U!==N)throw new Error(j+" of length "+N+" expected, got "+U);return T}function m(j,z){if(j.length!==z.length)return!1;let N=0;for(let T=0;Ttypeof j=="bigint"&&r<=j;function b(j,z,N){return y(j)&&y(z)&&y(N)&&z<=j&&jr;j>>=s,z+=1);return z}function E(j,z){return j>>BigInt(z)&s}function A(j,z,N){return j|(N?s:r)<(s<new Uint8Array(Ee),U=Ee=>Uint8Array.of(Ee);let L=T(j),P=T(j),H=0;const Y=()=>{L.fill(1),P.fill(0),H=0},re=(...Ee)=>N(P,L,...Ee),de=(Ee=T(0))=>{P=re(U(0),Ee),L=re(),Ee.length!==0&&(P=re(U(1),Ee),L=re())},fe=()=>{if(H++>=1e3)throw new Error("drbg: tried 1000 values");let Ee=0;const oe=[];for(;Ee{Y(),de(Ee);let Oe;for(;!(Oe=oe(fe()));)de();return Y(),Oe}}const B={bigint:j=>typeof j=="bigint",function:j=>typeof j=="function",boolean:j=>typeof j=="boolean",string:j=>typeof j=="string",stringOrUint8Array:j=>typeof j=="string"||(0,e.isBytes)(j),isSafeInteger:j=>Number.isSafeInteger(j),array:j=>Array.isArray(j),field:(j,z)=>z.Fp.isValid(j),hash:j=>typeof j=="function"&&Number.isSafeInteger(j.outputLen)};function W(j,z,N={}){const T=(U,L,P)=>{const H=B[L];if(typeof H!="function")throw new Error("invalid validator function");const Y=j[U];if(!(P&&Y===void 0)&&!H(Y,j))throw new Error("param "+String(U)+" is invalid. Expected "+L+", got "+Y)};for(const[U,L]of Object.entries(z))T(U,L,!1);for(const[U,L]of Object.entries(N))T(U,L,!0);return j}function S(j){return typeof j=="function"&&Number.isSafeInteger(j.outputLen)}function $(j,z,N={}){if(!j||typeof j!="object")throw new Error("expected valid options object");function T(U,L,P){const H=j[U];if(P&&H===void 0)return;const Y=typeof H;if(Y!==L||H===null)throw new Error(`param "${U}" is invalid: expected ${L}, got ${Y}`)}Object.entries(z).forEach(([U,L])=>T(U,L,!1)),Object.entries(N).forEach(([U,L])=>T(U,L,!0))}const R=()=>{throw new Error("not implemented")};t.notImplemented=R;function M(j){const z=new WeakMap;return(N,...T)=>{const U=z.get(N);if(U!==void 0)return U;const L=j(N,...T);return z.set(N,L),L}}})(lx);function aHe(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l>>0,y=new Uint8Array(m);for(;f!==p;){let x=l[f],E=0;for(let A=m-1;(x!==0||E>>0,y[A]=x%n>>>0,x=x/n>>>0;if(x!==0)throw new Error("Non-zero carry");d=E,f++}let b=m-d;for(;b!==m&&y[b]===0;)b++;let v=r.repeat(u);for(;b>>0,m=new Uint8Array(p);for(;u255)return;let E=e[x];if(E===255)return;let A=0;for(let _=p-1;(E!==0||A>>0,m[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");f=A,u++}let y=p-f;for(;y!==p&&m[y]===0;)y++;const b=new Uint8Array(d+(p-y));let v=d;for(;y!==p;)b[v++]=m[y++];return b}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+n+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var cHe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const ux=aHe(cHe);function lHe(t){const e=t.length;let n=0,r=0;for(;r=55296&&s<=56319&&r>6&31|192;else{if(o>=55296&&o<=56319&&i>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128):(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128)}else{e[s++]=o;continue}e[s++]=o&63|128}}const dHe=new TextEncoder,fHe=50;function hHe(t,e,n){dHe.encodeInto(t,e.subarray(n))}function pHe(t,e,n){t.length>fHe?hHe(t,e,n):uHe(t,e,n)}const gHe=4096;function Yfe(t,e,n){let r=e;const s=r+n,i=[];let o="";for(;r65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(a);i.length>=gHe&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}const mHe=new TextDecoder,yHe=200;function wHe(t,e,n){const r=t.subarray(e,e+n);return mHe.decode(r)}function bHe(t,e,n){return n>yHe?wHe(t,e,n):Yfe(t,e,n)}class _A{constructor(e,n){this.type=e,this.data=n}}class Ic extends Error{constructor(e){super(e);const n=Object.create(Ic.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Ic.name})}}const o2=4294967295;function vHe(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Xfe(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Qfe(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function xHe(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const EHe=-1,CHe=4294967296-1,_He=17179869184-1;function SHe({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=_He)if(e===0&&t<=CHe){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),i=new DataView(s.buffer);return i.setUint32(0,e<<2|n&3),i.setUint32(4,r),s}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Xfe(r,4,t),n}}function AHe(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function IHe(t){if(t instanceof Date){const e=AHe(t);return SHe(e)}else return null}function THe(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,i=n>>>2;return{sec:s,nsec:i}}case 12:{const n=Qfe(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Ic(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function NHe(t){const e=THe(t);return new Date(e.sec*1e3+e.nsec/1e6)}const PHe={type:EHe,encode:IHe,decode:NHe};class ET{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(PHe)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;rthis.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=lHe(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),pHe(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=w7(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(const s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const i of r){const o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),vHe(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Xfe(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function DHe(t,e){return new $He(e).encodeSharedRef(t)}function j$(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const MHe=16,LHe=16;class BHe{constructor(e=MHe,n=LHe){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r0&&e<=this.maxKeyLength}find(e,n,r){const s=this.caches[r-1];e:for(const i of s){const o=i.bytes;for(let a=0;a=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){const s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;const i=Yfe(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,i),i}}const b7="array",xE="map_key",ehe="map_value",UHe=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Ic("The type of key must be string or number but "+typeof t)};class FHe{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=b7,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=xE,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===b7){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===xE||e.type===ehe){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const a2=-1,Sz=new DataView(new ArrayBuffer(0)),jHe=new Uint8Array(Sz.buffer);try{Sz.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const fQ=new RangeError("Insufficient data"),zHe=new BHe;let WHe=class the{constructor(e){this.totalPos=0,this.pos=0,this.view=Sz,this.bytes=jHe,this.headByte=a2,this.stack=new FHe,this.entered=!1,this.extensionCodec=e?.extensionCodec??ET.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??o2,this.maxBinLength=e?.maxBinLength??o2,this.maxArrayLength=e?.maxArrayLength??o2,this.maxMapLength=e?.maxMapLength??o2,this.maxExtLength=e?.maxExtLength??o2,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:zHe,this.mapKeyConverter=e?.mapKeyConverter??UHe}clone(){return new the({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=a2,this.stack.reset()}setBuffer(e){const n=w7(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===a2&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=w7(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:s,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${j$(s)} at ${o} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(const i of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{const s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){const s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();n=this.decodeExtension(s,4)}else throw new Ic(`Unrecognized type byte: ${j$(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===b7)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===xE){if(n==="__proto__")throw new Ic("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=ehe;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=xE;continue e}}return n}}readHeadByte(){return this.headByte===a2&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=a2}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Ic(`Unrecognized array type byte: ${j$(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Ic(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Ic(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new Ic(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===xE:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Ic(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw fQ;const r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new Ic(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=xHe(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Qfe(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function VHe(t,e){return new WHe(e).decode(t)}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function HHe(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function nhe(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function CT(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Az(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function v7(t){if(!Array.isArray(t))throw new Error("array expected")}function _T(t,e){if(!nhe(!0,e))throw new Error(`${t}: array of strings expected`)}function qHe(t,e){if(!nhe(!1,e))throw new Error(`${t}: array of numbers expected`)}function KHe(...t){const e=i=>i,n=(i,o)=>a=>i(o(a)),r=t.map(i=>i.encode).reduceRight(n,e),s=t.map(i=>i.decode).reduce(n,e);return{encode:r,decode:s}}function GHe(t){const e=typeof t=="string"?t.split(""):t,n=e.length;_T("alphabet",e);const r=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(v7(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:s=>(v7(s),s.map(i=>{CT("alphabet.decode",i);const o=r.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return o}))}}function ZHe(t=""){return CT("join",t),{encode:e=>(_T("join.decode",e),e.join(t)),decode:e=>(CT("join.decode",e),e.split(t))}}function YHe(t,e="="){return Az(t),CT("padding",e),{encode(n){for(_T("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){_T("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}const rhe=(t,e)=>e===0?t:rhe(e,t%e),ST=(t,e)=>t+(e-rhe(t,e)),z$=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function hQ(t,e,n,r){if(v7(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(ST(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${ST(e,n)}`);let s=0,i=0;const o=z$[e],a=z$[n]-1,c=[];for(const l of t){if(Az(l),l>=o)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(s=s<32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=n;i-=n)c.push((s>>i-n&a)>>>0);const u=z$[i];if(u===void 0)throw new Error("invalid carry");s&=u-1}if(s=s<=e)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&i>0&&c.push(s>>>0),c}function XHe(t,e=!1){if(Az(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(ST(8,t)>32||ST(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!HHe(n))throw new Error("radix2.encode input should be Uint8Array");return hQ(Array.from(n),8,t,!e)},decode:n=>(qHe("radix2.decode",n),Uint8Array.from(hQ(n,t,8,e)))}}const QHe=KHe(XHe(5),GHe("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),YHe(5),ZHe(""));function Iz(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function she(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Iz(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function EE(t,e){e||(e=t.reduce((s,i)=>s+i.length,0));const n=she(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return Iz(n)}function JHe(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r>>0,A=new Uint8Array(E);v!==x;){for(var _=m[v],k=0,B=E-1;(_!==0||k>>0,A[B]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");b=k,v++}for(var W=E-b;W!==E&&A[W]===0;)W++;for(var S=c.repeat(y);W>>0,E=new Uint8Array(x);m[y];){var A=n[m.charCodeAt(y)];if(A===255)return;for(var _=0,k=x-1;(A!==0||_>>0,E[k]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");v=_,y++}if(m[y]!==" "){for(var B=x-v;B!==x&&E[B]===0;)B++;for(var W=new Uint8Array(b+(x-B)),S=b;B!==x;)W[S++]=E[B++];return W}}}function p(m){var y=f(m);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:p}}var eqe=JHe,tqe=eqe;const nqe=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},rqe=t=>new TextEncoder().encode(t),sqe=t=>new TextDecoder().decode(t);let iqe=class{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},oqe=class{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ihe(this,e)}},aqe=class{constructor(e){this.decoders=e}or(e){return ihe(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const ihe=(t,e)=>new aqe({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let cqe=class{constructor(e,n,r,s){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new iqe(e,n,r),this.decoder=new oqe(e,n,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const JP=({name:t,prefix:e,encode:n,decode:r})=>new cqe(t,e,n,r),r3=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:s}=tqe(n,e);return JP({prefix:t,name:e,encode:r,decode:i=>nqe(s(i))})},lqe=(t,e,n,r)=>{const s={};for(let u=0;u=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},uqe=(t,e,n)=>{const r=e[e.length-1]==="=",s=(1<n;)o-=n,i+=e[s&a>>o];if(o&&(i+=e[s&a<JP({prefix:e,name:t,encode(s){return uqe(s,r,n)},decode(s){return lqe(s,r,n,t)}}),dqe=JP({prefix:"\0",name:"identity",encode:t=>sqe(t),decode:t=>rqe(t)}),fqe=Object.freeze(Object.defineProperty({__proto__:null,identity:dqe},Symbol.toStringTag,{value:"Module"})),hqe=Xi({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),pqe=Object.freeze(Object.defineProperty({__proto__:null,base2:hqe},Symbol.toStringTag,{value:"Module"})),gqe=Xi({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),mqe=Object.freeze(Object.defineProperty({__proto__:null,base8:gqe},Symbol.toStringTag,{value:"Module"})),yqe=r3({prefix:"9",name:"base10",alphabet:"0123456789"}),wqe=Object.freeze(Object.defineProperty({__proto__:null,base10:yqe},Symbol.toStringTag,{value:"Module"})),bqe=Xi({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),vqe=Xi({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),xqe=Object.freeze(Object.defineProperty({__proto__:null,base16:bqe,base16upper:vqe},Symbol.toStringTag,{value:"Module"})),Eqe=Xi({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Cqe=Xi({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_qe=Xi({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Sqe=Xi({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Aqe=Xi({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Iqe=Xi({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Tqe=Xi({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Nqe=Xi({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Pqe=Xi({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),kqe=Object.freeze(Object.defineProperty({__proto__:null,base32:Eqe,base32hex:Aqe,base32hexpad:Tqe,base32hexpadupper:Nqe,base32hexupper:Iqe,base32pad:_qe,base32padupper:Sqe,base32upper:Cqe,base32z:Pqe},Symbol.toStringTag,{value:"Module"})),Rqe=r3({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Oqe=r3({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),$qe=Object.freeze(Object.defineProperty({__proto__:null,base36:Rqe,base36upper:Oqe},Symbol.toStringTag,{value:"Module"})),Dqe=r3({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mqe=r3({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Lqe=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Dqe,base58flickr:Mqe},Symbol.toStringTag,{value:"Module"})),Bqe=Xi({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Uqe=Xi({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fqe=Xi({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),jqe=Xi({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),zqe=Object.freeze(Object.defineProperty({__proto__:null,base64:Bqe,base64pad:Uqe,base64url:Fqe,base64urlpad:jqe},Symbol.toStringTag,{value:"Module"})),ohe=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Wqe=ohe.reduce((t,e,n)=>(t[n]=e,t),[]),Vqe=ohe.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function Hqe(t){return t.reduce((e,n)=>(e+=Wqe[n],e),"")}function qqe(t){const e=[];for(const n of t){const r=Vqe[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const Kqe=JP({prefix:"🚀",name:"base256emoji",encode:Hqe,decode:qqe}),Gqe=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Kqe},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const pQ={...fqe,...pqe,...mqe,...wqe,...xqe,...kqe,...$qe,...Lqe,...zqe,...Gqe};function ahe(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const gQ=ahe("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),W$=ahe("ascii","a",t=>{let e="a";for(let n=0;n{t=t.substring(1);const e=she(t.length);for(let n=0;n=4294967296&&s++,t[e]=r,t[e+1]=s}function mQ(t,e,n,r){let s=t[e]+n;n<0&&(s+=4294967296);let i=t[e+1]+r;s>=4294967296&&i++,t[e]=s,t[e+1]=i}function uhe(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function Kp(t,e,n,r,s,i){const o=j2[s],a=j2[s+1],c=j2[i],l=j2[i+1];AA(In,t,e),mQ(In,t,o,a);let u=In[r]^In[t],d=In[r+1]^In[t+1];In[r]=d,In[r+1]=u,AA(In,n,r),u=In[e]^In[n],d=In[e+1]^In[n+1],In[e]=u>>>24^d<<8,In[e+1]=d>>>24^u<<8,AA(In,t,e),mQ(In,t,c,l),u=In[r]^In[t],d=In[r+1]^In[t+1],In[r]=u>>>16^d<<16,In[r+1]=d>>>16^u<<16,AA(In,n,r),u=In[e]^In[n],d=In[e+1]^In[n+1],In[e]=d>>>31^u<<1,In[e+1]=u>>>31^d<<1}const dhe=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),tKe=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],lo=new Uint8Array(tKe.map(function(t){return t*2})),In=new Uint32Array(32),j2=new Uint32Array(32);function fhe(t,e){let n=0;for(n=0;n<16;n++)In[n]=t.h[n],In[n+16]=dhe[n];for(In[24]=In[24]^t.t,In[25]=In[25]^t.t/4294967296,e&&(In[28]=~In[28],In[29]=~In[29]),n=0;n<32;n++)j2[n]=uhe(t.b,4*n);for(n=0;n<12;n++)Kp(0,8,16,24,lo[n*16+0],lo[n*16+1]),Kp(2,10,18,26,lo[n*16+2],lo[n*16+3]),Kp(4,12,20,28,lo[n*16+4],lo[n*16+5]),Kp(6,14,22,30,lo[n*16+6],lo[n*16+7]),Kp(0,10,20,30,lo[n*16+8],lo[n*16+9]),Kp(2,12,22,24,lo[n*16+10],lo[n*16+11]),Kp(4,14,16,26,lo[n*16+12],lo[n*16+13]),Kp(6,8,18,28,lo[n*16+14],lo[n*16+15]);for(n=0;n<16;n++)t.h[n]=t.h[n]^In[n]^In[n+16]}const Gp=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function hhe(t,e,n,r){if(t===0||t>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(e&&e.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(n&&n.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const s={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};Gp.fill(0),Gp[0]=t,e&&(Gp[1]=e.length),Gp[2]=1,Gp[3]=1,n&&Gp.set(n,32),r&&Gp.set(r,48);for(let i=0;i<16;i++)s.h[i]=dhe[i]^uhe(Gp,i*4);return e&&(Tz(s,e),s.c=128),s}function Tz(t,e){for(let n=0;n>2]>>8*(n&3);return e}function ghe(t,e,n,r,s){n=n||64,t=HI.normalizeInput(t),r&&(r=HI.normalizeInput(r)),s&&(s=HI.normalizeInput(s));const i=hhe(n,e,r,s);return Tz(i,t),phe(i)}function nKe(t,e,n,r,s){const i=ghe(t,e,n,r,s);return HI.toHex(i)}var rKe={blake2b:ghe,blake2bHex:nKe,blake2bInit:hhe,blake2bUpdate:Tz,blake2bFinal:phe};const mhe=lhe;function sKe(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function Zp(t,e,n,r,s,i){mr[t]=mr[t]+mr[e]+s,mr[r]=IA(mr[r]^mr[t],16),mr[n]=mr[n]+mr[r],mr[e]=IA(mr[e]^mr[n],12),mr[t]=mr[t]+mr[e]+i,mr[r]=IA(mr[r]^mr[t],8),mr[n]=mr[n]+mr[r],mr[e]=IA(mr[e]^mr[n],7)}function IA(t,e){return t>>>e^t<<32-e}const yhe=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),uo=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),mr=new Uint32Array(16),Ii=new Uint32Array(16);function whe(t,e){let n=0;for(n=0;n<8;n++)mr[n]=t.h[n],mr[n+8]=yhe[n];for(mr[12]^=t.t,mr[13]^=t.t/4294967296,e&&(mr[14]=~mr[14]),n=0;n<16;n++)Ii[n]=sKe(t.b,4*n);for(n=0;n<10;n++)Zp(0,4,8,12,Ii[uo[n*16+0]],Ii[uo[n*16+1]]),Zp(1,5,9,13,Ii[uo[n*16+2]],Ii[uo[n*16+3]]),Zp(2,6,10,14,Ii[uo[n*16+4]],Ii[uo[n*16+5]]),Zp(3,7,11,15,Ii[uo[n*16+6]],Ii[uo[n*16+7]]),Zp(0,5,10,15,Ii[uo[n*16+8]],Ii[uo[n*16+9]]),Zp(1,6,11,12,Ii[uo[n*16+10]],Ii[uo[n*16+11]]),Zp(2,7,8,13,Ii[uo[n*16+12]],Ii[uo[n*16+13]]),Zp(3,4,9,14,Ii[uo[n*16+14]],Ii[uo[n*16+15]]);for(n=0;n<8;n++)t.h[n]^=mr[n]^mr[n+8]}function bhe(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const n=e?e.length:0;if(e&&!(n>0&&n<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(yhe),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^n<<8^t,n>0&&(Nz(r,e),r.c=64),r}function Nz(t,e){for(let n=0;n>2]>>8*(n&3)&255;return e}function xhe(t,e,n){n=n||32,t=mhe.normalizeInput(t);const r=bhe(n,e);return Nz(r,t),vhe(r)}function iKe(t,e,n){const r=xhe(t,e,n);return mhe.toHex(r)}var oKe={blake2s:xhe,blake2sHex:iKe,blake2sInit:bhe,blake2sUpdate:Nz,blake2sFinal:vhe};const c2=rKe,l2=oKe;var aKe={blake2b:c2.blake2b,blake2bHex:c2.blake2bHex,blake2bInit:c2.blake2bInit,blake2bUpdate:c2.blake2bUpdate,blake2bFinal:c2.blake2bFinal,blake2s:l2.blake2s,blake2sHex:l2.blake2sHex,blake2sInit:l2.blake2sInit,blake2sUpdate:l2.blake2sUpdate,blake2sFinal:l2.blake2sFinal},cKe={};const lKe=":";function dv(t){const[e,n]=t.split(lKe);return{namespace:e,reference:n}}function Ehe(t,e){return t.includes(":")?[t]:e.chains||[]}var uKe=Object.defineProperty,dKe=Object.defineProperties,fKe=Object.getOwnPropertyDescriptors,yQ=Object.getOwnPropertySymbols,hKe=Object.prototype.hasOwnProperty,pKe=Object.prototype.propertyIsEnumerable,x7=(t,e,n)=>e in t?uKe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,wQ=(t,e)=>{for(var n in e||(e={}))hKe.call(e,n)&&x7(t,n,e[n]);if(yQ)for(var n of yQ(e))pKe.call(e,n)&&x7(t,n,e[n]);return t},gKe=(t,e)=>dKe(t,fKe(e)),bQ=(t,e,n)=>x7(t,typeof e!="symbol"?e+"":e,n);const mKe="ReactNative",$c={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},yKe="js";function AT(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function k0(){return!wy()&&!!Cz()&&navigator.product===mKe}function wKe(){return k0()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function bKe(){return k0()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function dx(){return!AT()&&!!Cz()&&!!wy()}function s3(){return k0()?$c.reactNative:AT()?$c.node:dx()?$c.browser:$c.unknown}function vQ(){var t;try{return k0()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function vKe(t,e){const n=new URLSearchParams(t);for(const r of Object.keys(e).sort())if(e.hasOwnProperty(r)){const s=e[r];s!==void 0&&n.set(r,s)}return n.toString()}function xKe(t){var e,n;const r=Che();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(s=>s!=="")),gKe(wQ(wQ({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(n=t?.icons)!=null&&n.length&&t.icons.length>0?t.icons:r.icons})}catch(s){return console.warn("Error populating app metadata",s),t||r}}function Che(){return jfe()||{name:"",description:"",url:"",icons:[""]}}function EKe(){if(s3()===$c.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:n,Version:r}=global.Platform;return[n,r].join("-")}const t=AVe();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function CKe(){var t;const e=s3();return e===$c.browser?[e,((t=Ffe())==null?void 0:t.host)||"unknown"].join(":"):e}function _he(t,e,n){const r=EKe(),s=CKe();return[[t,e].join("-"),[yKe,n].join("-"),r,s].join("/")}function _Ke({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:s,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=n.split("?"),u=_he(t,e,r),d={auth:s,ua:u,projectId:i,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=vKe(l[1]||"",d);return l[0]+"?"+f}function xm(t,e){return t.filter(n=>e.includes(n)).length===t.length}function E7(t){return Object.fromEntries(t.entries())}function C7(t){return new Map(Object.entries(t))}function am(t=yt.FIVE_MINUTES,e){const n=yt.toMiliseconds(t||yt.FIVE_MINUTES);let r,s,i,o;return{resolve:a=>{i&&r&&(clearTimeout(i),r(a),o=Promise.resolve(a))},reject:a=>{i&&s&&(clearTimeout(i),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);i=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},n),r=a,s=c})}}function Ng(t,e,n){return new Promise(async(r,s)=>{const i=setTimeout(()=>s(new Error(n)),e);try{const o=await t;r(o)}catch(o){s(o)}clearTimeout(i)})}function She(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function SKe(t){return She("topic",t)}function AKe(t){return She("id",t)}function Ahe(t){const[e,n]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof n=="string")r.topic=n;else if(e==="id"&&Number.isInteger(Number(n)))r.id=Number(n);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${n}`);return r}function ei(t,e){return yt.fromMiliseconds(Date.now()+yt.toMiliseconds(t))}function dg(t){return Date.now()>=yt.toMiliseconds(t)}function Tr(t,e){return`${t}${e?`:${e}`:""}`}function ef(t=[],e=[]){return[...new Set([...t,...e])]}async function IKe({id:t,topic:e,wcDeepLink:n}){var r;try{if(!n)return;const s=typeof n=="string"?JSON.parse(n):n,i=s?.href;if(typeof i!="string")return;const o=TKe(i,t,e),a=s3();if(a===$c.browser){if(!((r=wy())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}NKe(o)}else a===$c.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function TKe(t,e,n){const r=`requestId=${e}&sessionTopic=${n}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const i=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${i}${OKe(r,!0)}`}else s=`${s}/wc?${r}`;return s}function NKe(t){let e="_self";RKe()?e="_top":(kKe()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function PKe(t,e){let n="";try{if(dx()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function xQ(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function EQ(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Pz(){return typeof process<"u"&&cKe.IS_VITEST==="true"}function kKe(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function RKe(){try{return window.self!==window.top}catch{return!1}}function OKe(t,e=!1){const n=Buffer.from(t).toString("base64");return e?n.replace(/[=]/g,""):n}function Ihe(t){return Buffer.from(t,"base64").toString("utf-8")}function $Ke(t){return new Promise(e=>setTimeout(e,t))}let DKe=class{constructor({limit:e}){bQ(this,"limit"),bQ(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const n=this.set.values().next().value;n&&this.set.delete(n)}this.set.add(e)}}has(e){return this.set.has(e)}};const TA=BigInt(2**32-1),CQ=BigInt(32);function The(t,e=!1){return e?{h:Number(t&TA),l:Number(t>>CQ&TA)}:{h:Number(t>>CQ&TA)|0,l:Number(t&TA)|0}}function Nhe(t,e=!1){const n=t.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let i=0;it>>>n,SQ=(t,e,n)=>t<<32-n|e>>>n,fg=(t,e,n)=>t>>>n|e<<32-n,hg=(t,e,n)=>t<<32-n|e>>>n,z2=(t,e,n)=>t<<64-n|e>>>n-32,W2=(t,e,n)=>t>>>n-32|e<<64-n,MKe=(t,e)=>e,LKe=(t,e)=>t,BKe=(t,e,n)=>t<>>32-n,UKe=(t,e,n)=>e<>>32-n,FKe=(t,e,n)=>e<>>64-n,jKe=(t,e,n)=>t<>>64-n;function Su(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}const kz=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Rz=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,zKe=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),WKe=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,VKe=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),HKe=(t,e,n,r,s,i)=>e+n+r+s+i+(t/2**32|0)|0,Yw=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Oz(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Yh(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function zl(t,...e){if(!Oz(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function $z(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Yh(t.outputLen),Yh(t.blockLen)}function f0(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Dz(t,e){zl(t);const n=e.outputLen;if(t.length>>e}const Phe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function khe(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const sh=Phe?t=>t:t=>khe(t);function qKe(t){for(let e=0;et:qKe,Rhe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",KKe=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function KC(t){if(zl(t),Rhe)return t.toHex();let e="";for(let n=0;n=Qf._0&&t<=Qf._9)return t-Qf._0;if(t>=Qf.A&&t<=Qf.F)return t-(Qf.A-10);if(t>=Qf.a&&t<=Qf.f)return t-(Qf.a-10)}function Mz(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Rhe)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let s=0,i=0;st().update(Vu(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function ZKe(t){const e=(r,s)=>t(s).update(Vu(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function fx(t=32){if(Yw&&typeof Yw.getRandomValues=="function")return Yw.getRandomValues(new Uint8Array(t));if(Yw&&typeof Yw.randomBytes=="function")return Uint8Array.from(Yw.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const YKe=BigInt(0),u2=BigInt(1),XKe=BigInt(2),QKe=BigInt(7),JKe=BigInt(256),eGe=BigInt(113),Ohe=[],$he=[],Dhe=[];for(let t=0,e=u2,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ohe.push(2*(5*r+n)),$he.push((t+1)*(t+2)/2%64);let s=YKe;for(let i=0;i<7;i++)e=(e<>QKe)*eGe)%JKe,e&XKe&&(s^=u2<<(u2<n>32?FKe(t,e,n):BKe(t,e,n),TQ=(t,e,n)=>n>32?jKe(t,e,n):UKe(t,e,n);function rGe(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=n[c],u=n[c+1],d=IQ(l,u,1)^n[a],f=TQ(l,u,1)^n[a+1];for(let p=0;p<50;p+=10)t[o+p]^=d,t[o+p+1]^=f}let s=t[2],i=t[3];for(let o=0;o<24;o++){const a=$he[o],c=IQ(s,i,a),l=TQ(s,i,a),u=Ohe[o];s=t[u],i=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=tGe[r],t[1]^=nGe[r]}Wl(n)}let sGe=class Lhe extends ek{constructor(e,n,r,s=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=i,Yh(r),!(0=r&&this.keccak();const o=Math.min(r-this.posOut,i-s);e.set(n.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=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 Yh(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Dz(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,Wl(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new Lhe(n,r,s,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const iGe=(t,e,n)=>i3(()=>new sGe(e,t,n)),oGe=iGe(1,136,256/8);function aGe(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function cGe(t,e,n){return t&e^~t&n}function lGe(t,e,n){return t&e^t&n^e&n}let Bhe=class extends ek{constructor(e,n,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=V$(this.buffer)}update(e){f0(this),e=Vu(e),zl(e);const{view:n,buffer:r,blockLen:s}=this,i=e.length;for(let o=0;os-o&&(this.process(r,0),o=0);for(let d=o;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d>>3,y=Id(p,17)^Id(p,19)^p>>>10;Xp[d]=y+Xp[d-7]+m+Xp[d-16]|0}let{A:r,B:s,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const f=Id(a,6)^Id(a,11)^Id(a,25),p=u+f+cGe(a,c,l)+uGe[d]+Xp[d]|0,m=(Id(r,2)^Id(r,13)^Id(r,22))+lGe(r,s,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=s,s=r,r=p+m|0}r=r+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,s,i,o,a,c,l,u)}roundClean(){Wl(Xp)}destroy(){this.set(0,0,0,0,0,0,0,0),Wl(this.buffer)}};const Uhe=Nhe(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),fGe=Uhe[0],hGe=Uhe[1],Qp=new Uint32Array(80),Jp=new Uint32Array(80);let Lz=class extends Bhe{constructor(e=64){super(128,e,16,!1),this.Ah=ho[0]|0,this.Al=ho[1]|0,this.Bh=ho[2]|0,this.Bl=ho[3]|0,this.Ch=ho[4]|0,this.Cl=ho[5]|0,this.Dh=ho[6]|0,this.Dl=ho[7]|0,this.Eh=ho[8]|0,this.El=ho[9]|0,this.Fh=ho[10]|0,this.Fl=ho[11]|0,this.Gh=ho[12]|0,this.Gl=ho[13]|0,this.Hh=ho[14]|0,this.Hl=ho[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:s,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:p,Gl:m,Hh:y,Hl:b}=this;return[e,n,r,s,i,o,a,c,l,u,d,f,p,m,y,b]}set(e,n,r,s,i,o,a,c,l,u,d,f,p,m,y,b){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=p|0,this.Gl=m|0,this.Hh=y|0,this.Hl=b|0}process(e,n){for(let E=0;E<16;E++,n+=4)Qp[E]=e.getUint32(n),Jp[E]=e.getUint32(n+=4);for(let E=16;E<80;E++){const A=Qp[E-15]|0,_=Jp[E-15]|0,k=fg(A,_,1)^fg(A,_,8)^_Q(A,_,7),B=hg(A,_,1)^hg(A,_,8)^SQ(A,_,7),W=Qp[E-2]|0,S=Jp[E-2]|0,$=fg(W,S,19)^z2(W,S,61)^_Q(W,S,6),R=hg(W,S,19)^W2(W,S,61)^SQ(W,S,6),M=zKe(B,R,Jp[E-7],Jp[E-16]),j=WKe(M,k,$,Qp[E-7],Qp[E-16]);Qp[E]=j|0,Jp[E]=M|0}let{Ah:r,Al:s,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:p,Fl:m,Gh:y,Gl:b,Hh:v,Hl:x}=this;for(let E=0;E<80;E++){const A=fg(d,f,14)^fg(d,f,18)^z2(d,f,41),_=hg(d,f,14)^hg(d,f,18)^W2(d,f,41),k=d&p^~d&y,B=f&m^~f&b,W=VKe(x,_,B,hGe[E],Jp[E]),S=HKe(W,v,A,k,fGe[E],Qp[E]),$=W|0,R=fg(r,s,28)^z2(r,s,34)^z2(r,s,39),M=hg(r,s,28)^W2(r,s,34)^W2(r,s,39),j=r&i^r&a^i&a,z=s&o^s&c^o&c;v=y|0,x=b|0,y=p|0,b=m|0,p=d|0,m=f|0,{h:d,l:f}=Su(l|0,u|0,S|0,$|0),l=a|0,u=c|0,a=i|0,c=o|0,i=r|0,o=s|0;const N=kz($,M,z);r=Rz(N,S,R,j),s=N|0}({h:r,l:s}=Su(this.Ah|0,this.Al|0,r|0,s|0)),{h:i,l:o}=Su(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Su(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Su(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=Su(this.Eh|0,this.El|0,d|0,f|0),{h:p,l:m}=Su(this.Fh|0,this.Fl|0,p|0,m|0),{h:y,l:b}=Su(this.Gh|0,this.Gl|0,y|0,b|0),{h:v,l:x}=Su(this.Hh|0,this.Hl|0,v|0,x|0),this.set(r,s,i,o,a,c,l,u,d,f,p,m,y,b,v,x)}roundClean(){Wl(Qp,Jp)}destroy(){Wl(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},pGe=class extends Lz{constructor(){super(48),this.Ah=fo[0]|0,this.Al=fo[1]|0,this.Bh=fo[2]|0,this.Bl=fo[3]|0,this.Ch=fo[4]|0,this.Cl=fo[5]|0,this.Dh=fo[6]|0,this.Dl=fo[7]|0,this.Eh=fo[8]|0,this.El=fo[9]|0,this.Fh=fo[10]|0,this.Fl=fo[11]|0,this.Gh=fo[12]|0,this.Gl=fo[13]|0,this.Hh=fo[14]|0,this.Hl=fo[15]|0}};const po=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class gGe extends Lz{constructor(){super(32),this.Ah=po[0]|0,this.Al=po[1]|0,this.Bh=po[2]|0,this.Bl=po[3]|0,this.Ch=po[4]|0,this.Cl=po[5]|0,this.Dh=po[6]|0,this.Dl=po[7]|0,this.Eh=po[8]|0,this.El=po[9]|0,this.Fh=po[10]|0,this.Fl=po[11]|0,this.Gh=po[12]|0,this.Gl=po[13]|0,this.Hh=po[14]|0,this.Hl=po[15]|0}}const tk=i3(()=>new dGe),mGe=i3(()=>new Lz),yGe=i3(()=>new pGe),wGe=i3(()=>new gGe),bGe=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),Qs=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),St=new Uint32Array(32);function eg(t,e,n,r,s,i){const o=s[i],a=s[i+1];let c=St[2*t],l=St[2*t+1],u=St[2*e],d=St[2*e+1],f=St[2*n],p=St[2*n+1],m=St[2*r],y=St[2*r+1],b=kz(c,u,o);l=Rz(b,l,d,a),c=b|0,{Dh:y,Dl:m}={Dh:y^l,Dl:m^c},{Dh:y,Dl:m}={Dh:MKe(y,m),Dl:LKe(y)},{h:p,l:f}=Su(p,f,y,m),{Bh:d,Bl:u}={Bh:d^p,Bl:u^f},{Bh:d,Bl:u}={Bh:fg(d,u,24),Bl:hg(d,u,24)},St[2*t]=c,St[2*t+1]=l,St[2*e]=u,St[2*e+1]=d,St[2*n]=f,St[2*n+1]=p,St[2*r]=m,St[2*r+1]=y}function tg(t,e,n,r,s,i){const o=s[i],a=s[i+1];let c=St[2*t],l=St[2*t+1],u=St[2*e],d=St[2*e+1],f=St[2*n],p=St[2*n+1],m=St[2*r],y=St[2*r+1],b=kz(c,u,o);l=Rz(b,l,d,a),c=b|0,{Dh:y,Dl:m}={Dh:y^l,Dl:m^c},{Dh:y,Dl:m}={Dh:fg(y,m,16),Dl:hg(y,m,16)},{h:p,l:f}=Su(p,f,y,m),{Bh:d,Bl:u}={Bh:d^p,Bl:u^f},{Bh:d,Bl:u}={Bh:z2(d,u,63),Bl:W2(d,u,63)},St[2*t]=c,St[2*t+1]=l,St[2*e]=u,St[2*e+1]=d,St[2*n]=f,St[2*n+1]=p,St[2*r]=m,St[2*r+1]=y}function vGe(t,e={},n,r,s){if(Yh(n),t<0||t>n)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.length>n))throw new Error("key length must be undefined or 1.."+n);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class xGe extends ek{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Yh(e),Yh(n),this.blockLen=e,this.outputLen=n,this.buffer=new Uint8Array(e),this.buffer32=qC(this.buffer)}update(e){f0(this),e=Vu(e),zl(e);const{blockLen:n,buffer:r,buffer32:s}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;cs[o]=sh(i))}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){const{buffer:n,length:r,finished:s,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(n),e.destroyed=i,e.finished=s,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class EGe extends xGe{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=Qs[0]|0,this.v0h=Qs[1]|0,this.v1l=Qs[2]|0,this.v1h=Qs[3]|0,this.v2l=Qs[4]|0,this.v2h=Qs[5]|0,this.v3l=Qs[6]|0,this.v3h=Qs[7]|0,this.v4l=Qs[8]|0,this.v4h=Qs[9]|0,this.v5l=Qs[10]|0,this.v5h=Qs[11]|0,this.v6l=Qs[12]|0,this.v6h=Qs[13]|0,this.v7l=Qs[14]|0,this.v7h=Qs[15]|0,vGe(n,e,64,16,16);let{key:r,personalization:s,salt:i}=e,o=0;if(r!==void 0&&(r=Vu(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=Vu(i);const a=qC(i);this.v4l^=sh(a[0]),this.v4h^=sh(a[1]),this.v5l^=sh(a[2]),this.v5h^=sh(a[3])}if(s!==void 0){s=Vu(s);const a=qC(s);this.v6l^=sh(a[0]),this.v6h^=sh(a[1]),this.v7l^=sh(a[2]),this.v7h^=sh(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:e,v0h:n,v1l:r,v1h:s,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:d,v5h:f,v6l:p,v6h:m,v7l:y,v7h:b}=this;return[e,n,r,s,i,o,a,c,l,u,d,f,p,m,y,b]}set(e,n,r,s,i,o,a,c,l,u,d,f,p,m,y,b){this.v0l=e|0,this.v0h=n|0,this.v1l=r|0,this.v1h=s|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|0,this.v5l=d|0,this.v5h=f|0,this.v6l=p|0,this.v6h=m|0,this.v7l=y|0,this.v7h=b|0}compress(e,n,r){this.get().forEach((c,l)=>St[l]=c),St.set(Qs,16);let{h:s,l:i}=The(BigInt(this.length));St[24]=Qs[8]^i,St[25]=Qs[9]^s,r&&(St[28]=~St[28],St[29]=~St[29]);let o=0;const a=bGe;for(let c=0;c<12;c++)eg(0,4,8,12,e,n+2*a[o++]),tg(0,4,8,12,e,n+2*a[o++]),eg(1,5,9,13,e,n+2*a[o++]),tg(1,5,9,13,e,n+2*a[o++]),eg(2,6,10,14,e,n+2*a[o++]),tg(2,6,10,14,e,n+2*a[o++]),eg(3,7,11,15,e,n+2*a[o++]),tg(3,7,11,15,e,n+2*a[o++]),eg(0,5,10,15,e,n+2*a[o++]),tg(0,5,10,15,e,n+2*a[o++]),eg(1,6,11,12,e,n+2*a[o++]),tg(1,6,11,12,e,n+2*a[o++]),eg(2,7,8,13,e,n+2*a[o++]),tg(2,7,8,13,e,n+2*a[o++]),eg(3,4,9,14,e,n+2*a[o++]),tg(3,4,9,14,e,n+2*a[o++]);this.v0l^=St[0]^St[16],this.v0h^=St[1]^St[17],this.v1l^=St[2]^St[18],this.v1h^=St[3]^St[19],this.v2l^=St[4]^St[20],this.v2h^=St[5]^St[21],this.v3l^=St[6]^St[22],this.v3h^=St[7]^St[23],this.v4l^=St[8]^St[24],this.v4h^=St[9]^St[25],this.v5l^=St[10]^St[26],this.v5h^=St[11]^St[27],this.v6l^=St[12]^St[28],this.v6h^=St[13]^St[29],this.v7l^=St[14]^St[30],this.v7h^=St[15]^St[31],Wl(St)}destroy(){this.destroyed=!0,Wl(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const CGe=ZKe(t=>new EGe(t)),_Ge="https://rpc.walletconnect.org/v1";function Fhe(t){const e=`Ethereum Signed Message: +${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(oGe(n)).toString("hex")}async function SGe(t,e,n,r,s,i){switch(n.t){case"eip191":return await AGe(t,e,n.s);case"eip1271":return await IGe(t,e,n.s,r,s,i);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}async function AGe(t,e,n){return(await oHe({hash:Fhe(e),signature:n})).toLowerCase()===t.toLowerCase()}async function IGe(t,e,n,r,s,i){const o=dv(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l=n.substring(2),u=(l.length/2).toString(16).padStart(64,"0"),d=(e.startsWith("0x")?e:Fhe(e)).substring(2),f=a+d+c+u+l,p=await fetch(`${i||_Ge}/?chainId=${r}&projectId=${s}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:TGe(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:f},"latest"]})}),{result:m}=await p.json();return m?m.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function TGe(){return Date.now()+Math.floor(Math.random()*1e3)}function NGe(t){const e=atob(t),n=new Uint8Array(e.length);for(let o=0;oi.charCodeAt(0)),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length);const s=CGe(r,{dkLen:32});return ux.encode(s)}function NQ(t){const e=new Uint8Array(tk(kGe(t)));return ux.encode(e)}function kGe(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function PQ(t){const e=Buffer.from(t,"base64"),n=VHe(e).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=DHe(n),s=Buffer.from("TX"),i=Buffer.concat([s,Buffer.from(r)]),o=wGe(i);return QHe.encode(o).replace(/=+$/,"")}function H$(t){const e=[];let n=BigInt(t);for(;n>=BigInt(128);)e.push(Number(n&BigInt(127)|BigInt(128))),n>>=BigInt(7);return e.push(Number(n)),Buffer.from(e)}function RGe(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),n=Buffer.from(t.signed.authInfoBytes,"base64"),r=Buffer.from(t.signature.signature,"base64"),s=[];s.push(Buffer.from([10])),s.push(H$(e.length)),s.push(e),s.push(Buffer.from([18])),s.push(H$(n.length)),s.push(n),s.push(Buffer.from([26])),s.push(H$(r.length)),s.push(r);const i=Buffer.concat(s),o=tk(i);return Buffer.from(o).toString("hex").toUpperCase()}var OGe=Object.defineProperty,$Ge=Object.defineProperties,DGe=Object.getOwnPropertyDescriptors,kQ=Object.getOwnPropertySymbols,MGe=Object.prototype.hasOwnProperty,LGe=Object.prototype.propertyIsEnumerable,RQ=(t,e,n)=>e in t?OGe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,BGe=(t,e)=>{for(var n in e||(e={}))MGe.call(e,n)&&RQ(t,n,e[n]);if(kQ)for(var n of kQ(e))LGe.call(e,n)&&RQ(t,n,e[n]);return t},UGe=(t,e)=>$Ge(t,DGe(e));const FGe="did:pkh:",Bz=t=>t?.split(":"),jGe=t=>{const e=t&&Bz(t);if(e)return t.includes(FGe)?e[3]:e[1]},_7=t=>{const e=t&&Bz(t);if(e)return e[2]+":"+e[3]},IT=t=>{const e=t&&Bz(t);if(e)return e.pop()};async function OQ(t){const{cacao:e,projectId:n}=t,{s:r,p:s}=e,i=jhe(s,s.iss),o=IT(s.iss);return await SGe(o,i,r,_7(s.iss),n)}const jhe=(t,e)=>{const n=`${t.domain} wants you to sign in with your Ethereum account:`,r=IT(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=t.statement||void 0;const i=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${jGe(e)}`,c=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,u=t.exp?`Expiration Time: ${t.exp}`:void 0,d=t.nbf?`Not Before: ${t.nbf}`:void 0,f=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(y=>` +- ${y}`).join("")}`:void 0,m=qI(t.resources);if(m){const y=GC(m);s=YGe(s,y)}return[n,r,"",s,"",i,o,a,c,l,u,d,f,p].filter(y=>y!=null).join(` +`)};function zGe(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function WGe(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function vy(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(n=>{const r=t.att[n];if(Array.isArray(r))throw new Error(`Resource must be an object: ${n}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${n}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${n}`);Object.keys(r).forEach(s=>{const i=r[s];if(!Array.isArray(i))throw new Error(`Ability limits ${s} must be an array of objects, found: ${i}`);if(!i.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);i.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function VGe(t,e,n,r={}){return n?.sort((s,i)=>s.localeCompare(i)),{att:{[t]:HGe(e,n,r)}}}function HGe(t,e,n={}){e=e?.sort((s,i)=>s.localeCompare(i));const r=e.map(s=>({[`${t}/${s}`]:[n]}));return Object.assign({},...r)}function zhe(t){return vy(t),`urn:recap:${zGe(t).replace(/=/g,"")}`}function GC(t){const e=WGe(t.replace("urn:recap:",""));return vy(e),e}function qGe(t,e,n){const r=VGe(t,e,n);return zhe(r)}function KGe(t){return t&&t.includes("urn:recap:")}function GGe(t,e){const n=GC(t),r=GC(e),s=ZGe(n,r);return zhe(s)}function ZGe(t,e){vy(t),vy(e);const n=Object.keys(t.att).concat(Object.keys(e.att)).sort((s,i)=>s.localeCompare(i)),r={att:{}};return n.forEach(s=>{var i,o;Object.keys(((i=t.att)==null?void 0:i[s])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[s])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;r.att[s]=UGe(BGe({},r.att[s]),{[a]:((c=t.att[s])==null?void 0:c[a])||((l=e.att[s])==null?void 0:l[a])})})}),r}function YGe(t="",e){vy(e);const n="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(n))return t;const r=[];let s=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));c.sort((d,f)=>d.action.localeCompare(f.action));const l={};c.forEach(d=>{l[d.ability]||(l[d.ability]=[]),l[d.ability].push(d.action)});const u=Object.keys(l).map(d=>(s++,`(${s}) '${d}': '${l[d].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const i=r.join(" "),o=`${n}${i}`;return`${t?t+" ":""}${o}`}function $Q(t){var e;const n=GC(t);vy(n);const r=(e=n.att)==null?void 0:e.eip155;return r?Object.keys(r).map(s=>s.split("/")[1]):[]}function DQ(t){const e=GC(t);vy(e);const n=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(s=>{var i;(i=s?.[0])!=null&&i.chains&&n.push(s[0].chains)})}),[...new Set(n.flat())]}function qI(t){if(!t)return;const e=t?.[t.length-1];return KGe(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Whe(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function S7(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function q$(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ka(t,...e){if(!Whe(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function MQ(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function XGe(t,e){ka(t);const n=e.outputLen;if(t.length{function n(r,...s){if(ka(r),!JGe)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const l=s[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?ka(l):ka(l,t.nonceLength)}const i=t.tagLength;i&&s[1]!==void 0&&ka(s[1]);const o=e(r,...s),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");ka(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ka(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(ka(l),i&&l.length>s&i),a=Number(n&i);t.setUint32(e+4,o,r),t.setUint32(e+0,a,r)}function sZe(t,e,n){S7(n);const r=new Uint8Array(16),s=QGe(r);return BQ(s,0,BigInt(e),n),BQ(s,8,BigInt(t),n),r}function iZe(t){return t.byteOffset%4===0}function I7(t){return Uint8Array.from(t)}const Vhe=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),oZe=Vhe("expand 16-byte k"),aZe=Vhe("expand 32-byte k"),cZe=Xg(oZe),lZe=Xg(aZe);function fr(t,e){return t<>>32-e}function T7(t){return t.byteOffset%4===0}const NA=64,uZe=16,Hhe=2**32-1,UQ=new Uint32Array;function dZe(t,e,n,r,s,i,o,a){const c=s.length,l=new Uint8Array(NA),u=Xg(l),d=T7(s)&&T7(i),f=d?Xg(s):UQ,p=d?Xg(i):UQ;for(let m=0;m=Hhe)throw new Error("arx: counter overflow");const y=Math.min(NA,c-m);if(d&&y===NA){const b=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let v=0,x;v{ka(a),ka(c),ka(l);const f=l.length;if(u===void 0&&(u=new Uint8Array(f)),ka(u),q$(d),d<0||d>=Hhe)throw new Error("arx: counter overflow");if(u.lengtht[e++]&255|(t[e++]&255)<<8;class hZe{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=A7(e),ka(e,32);const n=Ti(e,0),r=Ti(e,2),s=Ti(e,4),i=Ti(e,6),o=Ti(e,8),a=Ti(e,10),c=Ti(e,12),l=Ti(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|s<<6)&7939,this.r[3]=(s>>>7|i<<9)&8191,this.r[4]=(i>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ti(e,16+2*u)}process(e,n,r=!1){const s=r?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],f=o[5],p=o[6],m=o[7],y=o[8],b=o[9],v=Ti(e,n+0),x=Ti(e,n+2),E=Ti(e,n+4),A=Ti(e,n+6),_=Ti(e,n+8),k=Ti(e,n+10),B=Ti(e,n+12),W=Ti(e,n+14);let S=i[0]+(v&8191),$=i[1]+((v>>>13|x<<3)&8191),R=i[2]+((x>>>10|E<<6)&8191),M=i[3]+((E>>>7|A<<9)&8191),j=i[4]+((A>>>4|_<<12)&8191),z=i[5]+(_>>>1&8191),N=i[6]+((_>>>14|k<<2)&8191),T=i[7]+((k>>>11|B<<5)&8191),U=i[8]+((B>>>8|W<<8)&8191),L=i[9]+(W>>>5|s),P=0,H=P+S*a+$*(5*b)+R*(5*y)+M*(5*m)+j*(5*p);P=H>>>13,H&=8191,H+=z*(5*f)+N*(5*d)+T*(5*u)+U*(5*l)+L*(5*c),P+=H>>>13,H&=8191;let Y=P+S*c+$*a+R*(5*b)+M*(5*y)+j*(5*m);P=Y>>>13,Y&=8191,Y+=z*(5*p)+N*(5*f)+T*(5*d)+U*(5*u)+L*(5*l),P+=Y>>>13,Y&=8191;let re=P+S*l+$*c+R*a+M*(5*b)+j*(5*y);P=re>>>13,re&=8191,re+=z*(5*m)+N*(5*p)+T*(5*f)+U*(5*d)+L*(5*u),P+=re>>>13,re&=8191;let de=P+S*u+$*l+R*c+M*a+j*(5*b);P=de>>>13,de&=8191,de+=z*(5*y)+N*(5*m)+T*(5*p)+U*(5*f)+L*(5*d),P+=de>>>13,de&=8191;let fe=P+S*d+$*u+R*l+M*c+j*a;P=fe>>>13,fe&=8191,fe+=z*(5*b)+N*(5*y)+T*(5*m)+U*(5*p)+L*(5*f),P+=fe>>>13,fe&=8191;let ve=P+S*f+$*d+R*u+M*l+j*c;P=ve>>>13,ve&=8191,ve+=z*a+N*(5*b)+T*(5*y)+U*(5*m)+L*(5*p),P+=ve>>>13,ve&=8191;let Ee=P+S*p+$*f+R*d+M*u+j*l;P=Ee>>>13,Ee&=8191,Ee+=z*c+N*a+T*(5*b)+U*(5*y)+L*(5*m),P+=Ee>>>13,Ee&=8191;let oe=P+S*m+$*p+R*f+M*d+j*u;P=oe>>>13,oe&=8191,oe+=z*l+N*c+T*a+U*(5*b)+L*(5*y),P+=oe>>>13,oe&=8191;let Oe=P+S*y+$*m+R*p+M*f+j*d;P=Oe>>>13,Oe&=8191,Oe+=z*u+N*l+T*c+U*a+L*(5*b),P+=Oe>>>13,Oe&=8191;let je=P+S*b+$*y+R*m+M*p+j*f;P=je>>>13,je&=8191,je+=z*d+N*u+T*l+U*c+L*a,P+=je>>>13,je&=8191,P=(P<<2)+P|0,P=P+H|0,H=P&8191,P=P>>>13,Y+=P,i[0]=H,i[1]=Y,i[2]=re,i[3]=de,i[4]=fe,i[5]=ve,i[6]=Ee,i[7]=oe,i[8]=Oe,i[9]=je}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(s^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+n[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+n[a]|0)+(o>>>16)|0,e[a]=o&65535;Wv(r)}update(e){MQ(this),e=A7(e),ka(e);const{buffer:n,blockLen:r}=this,s=e.length;for(let i=0;i>>0,e[i++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}function pZe(t){const e=(r,s)=>t(s).update(A7(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const gZe=pZe(t=>new hZe(t));function mZe(t,e,n,r,s,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],f=e[2],p=e[3],m=e[4],y=e[5],b=e[6],v=e[7],x=s,E=n[0],A=n[1],_=n[2],k=o,B=a,W=c,S=l,$=u,R=d,M=f,j=p,z=m,N=y,T=b,U=v,L=x,P=E,H=A,Y=_;for(let de=0;de{t.update(e);const n=e.length%16;n&&t.update(wZe.subarray(n))},bZe=new Uint8Array(32);function jQ(t,e,n,r,s){const i=t(e,n,bZe),o=gZe.create(i);s&&FQ(o,s),FQ(o,r);const a=sZe(r.length,s?s.length:0,!0);o.update(a);const c=o.digest();return Wv(i,a),c}const vZe=t=>(e,n,r)=>({encrypt(s,i){const o=s.length;i=LQ(o+16,i,!1),i.set(s);const a=i.subarray(0,-16);t(e,n,a,a,1);const c=jQ(t,e,n,a,r);return i.set(c,o),Wv(c),i},decrypt(s,i){i=LQ(s.length-16,i,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=jQ(t,e,n,o,r);if(!nZe(a,c))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,n,i,i,1),Wv(c),i}}),qhe=rZe({blockSize:64,nonceLength:12,tagLength:16},vZe(yZe));let Khe=class extends ek{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,$z(e);const r=Vu(n);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 s=this.blockLen,i=new Uint8Array(s);i.set(r.length>s?e.create().update(r).digest():r);for(let o=0;onew Khe(t,e).update(n).digest();nk.create=(t,e)=>new Khe(t,e);function xZe(t,e,n){return $z(t),n===void 0&&(n=new Uint8Array(t.outputLen)),nk(t,Vu(n),Vu(e))}const K$=Uint8Array.from([0]),zQ=Uint8Array.of();function EZe(t,e,n,r=32){$z(t),Yh(r);const s=t.outputLen;if(r>255*s)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/s);n===void 0&&(n=zQ);const o=new Uint8Array(i*s),a=nk.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;uEZe(t,xZe(t,e,n),r,s),rk=tk,Uz=BigInt(0),N7=BigInt(1);function TT(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function PA(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Ghe(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Uz:BigInt("0x"+t)}function sk(t){return Ghe(KC(t))}function NT(t){return zl(t),Ghe(KC(Uint8Array.from(t).reverse()))}function Fz(t,e){return Mz(t.toString(16).padStart(e*2,"0"))}function jz(t,e){return Fz(t,e).reverse()}function Na(t,e,n){let r;if(typeof e=="string")try{r=Mz(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(Oz(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(t+" of length "+n+" expected, got "+s);return r}const G$=t=>typeof t=="bigint"&&Uz<=t;function _Ze(t,e,n){return G$(t)&&G$(e)&&G$(n)&&e<=t&&tUz;t>>=N7,e+=1);return e}const ik=t=>(N7<new Uint8Array(f),s=f=>Uint8Array.of(f);let i=r(t),o=r(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...f)=>n(o,i,...f),u=(f=r(0))=>{o=l(s(0),f),i=l(),f.length!==0&&(o=l(s(1),f),i=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f{c(),u(f);let m;for(;!(m=p(d()));)u();return c(),m}}function ok(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(s,i,o){const a=t[s];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([s,i])=>r(s,i,!1)),Object.entries(n).forEach(([s,i])=>r(s,i,!0))}function WQ(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const i=t(n,...r);return e.set(n,i),i}}const za=BigInt(0),na=BigInt(1),Cm=BigInt(2),IZe=BigInt(3),Zhe=BigInt(4),Yhe=BigInt(5),Xhe=BigInt(8);function vl(t,e){const n=t%e;return n>=za?n:e+n}function Eu(t,e,n){let r=t;for(;e-- >za;)r*=r,r%=n;return r}function VQ(t,e){if(t===za)throw new Error("invert: expected non-zero number");if(e<=za)throw new Error("invert: expected positive modulus, got "+e);let n=vl(t,e),r=e,s=za,i=na;for(;n!==za;){const o=r/n,a=r%n,c=s-i*o;r=n,n=a,s=i,i=c}if(r!==na)throw new Error("invert: does not exist");return vl(s,e)}function Qhe(t,e){const n=(t.ORDER+na)/Zhe,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function TZe(t,e){const n=(t.ORDER-Yhe)/Xhe,r=t.mul(e,Cm),s=t.pow(r,n),i=t.mul(e,s),o=t.mul(t.mul(i,Cm),s),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function NZe(t){if(t1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Qhe;let i=s.pow(r,e);const o=(e+na)/Cm;return function(a,c){if(a.is0(c))return c;if(HQ(a,c)!==1)throw new Error("Cannot find square root");let l=n,u=a.mul(a.ONE,i),d=a.pow(c,e),f=a.pow(c,o);for(;!a.eql(d,a.ONE);){if(a.is0(d))return a.ZERO;let p=1,m=a.sqr(d);for(;!a.eql(m,a.ONE);)if(p++,m=a.sqr(m),p===l)throw new Error("Cannot find square root");const y=na<(r[s]="function",r),e);return ok(t,n),t}function OZe(t,e,n){if(nza;)n&na&&(r=t.mul(r,s)),s=t.sqr(s),n>>=na;return r}function Jhe(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),i),r}function HQ(t,e){const n=(t.ORDER-na)/Cm,r=t.pow(e,n),s=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function $Ze(t,e){e!==void 0&&Yh(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function hx(t,e,n=!1,r={}){if(t<=za)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,i;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const u=e;u.BITS&&(s=u.BITS),u.sqrt&&(i=u.sqrt),typeof u.isLE=="boolean"&&(n=u.isLE)}else typeof e=="number"&&(s=e),r.sqrt&&(i=r.sqrt);const{nBitLength:o,nByteLength:a}=$Ze(t,s);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const l=Object.freeze({ORDER:t,isLE:n,BITS:o,BYTES:a,MASK:ik(o),ZERO:za,ONE:na,create:u=>vl(u,t),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return za<=u&&uu===za,isValidNot0:u=>!l.is0(u)&&l.isValid(u),isOdd:u=>(u&na)===na,neg:u=>vl(-u,t),eql:(u,d)=>u===d,sqr:u=>vl(u*u,t),add:(u,d)=>vl(u+d,t),sub:(u,d)=>vl(u-d,t),mul:(u,d)=>vl(u*d,t),pow:(u,d)=>OZe(l,u,d),div:(u,d)=>vl(u*VQ(d,t),t),sqrN:u=>u*u,addN:(u,d)=>u+d,subN:(u,d)=>u-d,mulN:(u,d)=>u*d,inv:u=>VQ(u,t),sqrt:i||(u=>(c||(c=PZe(t)),c(l,u))),toBytes:u=>n?jz(u,a):Fz(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return n?NT(u):sk(u)},invertBatch:u=>Jhe(l,u),cmov:(u,d,f)=>f?d:u});return Object.freeze(l)}function epe(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function tpe(t){const e=epe(t);return e+Math.ceil(e/2)}function DZe(t,e,n=!1){const r=t.length,s=epe(e),i=tpe(e);if(r<16||r1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const o=n?NT(t):sk(t),a=vl(o,e-na)+na;return n?jz(a,s):Fz(a,s)}const Vv=BigInt(0),_m=BigInt(1);function CE(t,e){const n=e.negate();return t?n:e}function MZe(t,e,n){const r=i=>i.pz,s=Jhe(t.Fp,n.map(r));return n.map((i,o)=>i.toAffine(s[o])).map(t.fromAffine)}function npe(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Z$(t,e){npe(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,i=ik(t),o=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function qQ(t,e,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=n;let a=Number(t&s),c=t>>o;a>r&&(a-=i,c+=_m);const l=e*r,u=l+Math.abs(a)-1,d=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function LZe(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function BZe(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Y$=new WeakMap,rpe=new WeakMap;function X$(t){return rpe.get(t)||1}function KQ(t){if(t!==Vv)throw new Error("invalid wNAF")}function UZe(t,e){return{constTimeNegate:CE,hasPrecomputes(n){return X$(n)!==1},unsafeLadder(n,r,s=t.ZERO){let i=n;for(;r>Vv;)r&_m&&(s=s.add(i)),i=i.double(),r>>=_m;return s},precomputeWindow(n,r){const{windows:s,windowSize:i}=Z$(r,e),o=[];let a=n,c=a;for(let l=0;lVv||r>Vv;)n&_m&&(i=i.add(s)),r&_m&&(o=o.add(s)),s=s.double(),n>>=_m,r>>=_m;return{p1:i,p2:o}}function jZe(t,e,n,r){LZe(n,t),BZe(r,e);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=SZe(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=ik(c),u=new Array(Number(l)+1).fill(o),d=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=d;p>=0;p-=c){u.fill(o);for(let y=0;y>BigInt(p)&l);u[v]=u[v].add(n[y])}let m=o;for(let y=u.length-1,b=o;y>0;y--)b=b.add(u[y]),m=m.add(b);if(f=f.add(m),p!==0)for(let y=0;yVv))throw new Error(`CURVE.${o} must be positive bigint`)}const r=GQ(e.p,n.Fp),s=GQ(e.n,n.Fn),i=["Gx","Gy","a","b"];for(const o of i)if(!r.isValid(e[o]))throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:s}}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const d2=BigInt(0),Xw=BigInt(1),kA=BigInt(2);function WZe(t){return ok(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function VZe(t){const e=WZe(t),{P:n,type:r,adjustScalarBytes:s,powPminus2:i,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||fx,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),f=BigInt(a?121665:39081),p=a?kA**BigInt(254):kA**BigInt(447),m=a?BigInt(8)*kA**BigInt(251)-Xw:BigInt(4)*kA**BigInt(445)-Xw,y=p+m+Xw,b=S=>vl(S,n),v=x(d);function x(S){return jz(b(S),u)}function E(S){const $=Na("u coordinate",S,u);return a&&($[31]&=127),b(NT($))}function A(S){return NT(s(Na("scalar",S,u)))}function _(S,$){const R=W(E($),A(S));if(R===d2)throw new Error("invalid private or public key received");return x(R)}function k(S){return _(S,v)}function B(S,$,R){const M=b(S*($-R));return $=b($-M),R=b(R+M),{x_2:$,x_3:R}}function W(S,$){P7("u",S,d2,n),P7("scalar",$,p,y);const R=$,M=S;let j=Xw,z=d2,N=S,T=Xw,U=d2;for(let P=BigInt(l-1);P>=d2;P--){const H=R>>P&Xw;U^=H,{x_2:j,x_3:N}=B(U,j,N),{x_2:z,x_3:T}=B(U,z,T),U=H;const Y=j+z,re=b(Y*Y),de=j-z,fe=b(de*de),ve=re-fe,Ee=N+T,oe=N-T,Oe=b(oe*Y),je=b(Ee*de),V=Oe+je,we=Oe-je;N=b(V*V),T=b(M*b(we*we)),j=b(re*fe),z=b(ve*(re+b(f*ve)))}({x_2:j,x_3:N}=B(U,j,N)),{x_2:z,x_3:T}=B(U,z,T);const L=i(z);return b(j*L)}return{scalarMult:_,scalarMultBase:k,getSharedSecret:(S,$)=>_(S,$),getPublicKey:S=>k(S),utils:{randomPrivateKey:()=>c(u)},GuBytes:v.slice()}}BigInt(0);const HZe=BigInt(1),ZQ=BigInt(2),qZe=BigInt(3),KZe=BigInt(5),GZe=BigInt(8),spe={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:GZe,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ZZe(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=spe.p,o=t*t%i*t%i,a=Eu(o,ZQ,i)*o%i,c=Eu(a,HZe,i)*t%i,l=Eu(c,KZe,i)*c%i,u=Eu(l,e,i)*l%i,d=Eu(u,n,i)*u%i,f=Eu(d,r,i)*d%i,p=Eu(f,s,i)*f%i,m=Eu(p,s,i)*f%i,y=Eu(m,e,i)*l%i;return{pow_p_5_8:Eu(y,ZQ,i)*t%i,b2:o}}function YZe(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const k7=(()=>{const t=spe.p;return VZe({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=ZZe(e);return vl(Eu(n,qZe,t)*r,t)},adjustScalarBytes:YZe})})();function YQ(t){t.lowS!==void 0&&TT("lowS",t.lowS),t.prehash!==void 0&&TT("prehash",t.prehash)}class XZe extends Error{constructor(e=""){super(e)}}const hh={Err:XZe,_tlv:{encode:(t,e)=>{const{Err:n}=hh;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,s=PA(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?PA(s.length/2|128):"";return PA(t)+i+s+e},decode(t,e){const{Err:n}=hh;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const s=e[r++],i=!!(s&128);let o=0;if(!i)o=s;else{const c=s&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=hh;if(t<_E)throw new e("integer: negative integers are not allowed");let n=PA(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=hh;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return sk(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=hh,s=Na("signature",t),{v:i,l:o}=r.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=hh,r=e.encode(2,n.encode(t.r)),s=e.encode(2,n.encode(t.s)),i=r+s;return e.encode(48,i)}},_E=BigInt(0),SE=BigInt(1),QZe=BigInt(2),RA=BigInt(3),JZe=BigInt(4);function eYe(t,e,n){function r(s){const i=t.sqr(s),o=t.mul(i,s);return t.add(t.add(o,t.mul(s,e)),n)}return r}function ipe(t,e,n){const{BYTES:r}=t;function s(i){let o;if(typeof i=="bigint")o=i;else{let a=Na("private key",i);if(e){if(!e.includes(a.length*2))throw new Error("invalid private key");const c=new Uint8Array(r);c.set(a,c.length-a.length),a=c}try{o=t.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof i}`)}}if(n&&(o=t.create(o)),!t.isValidNot0(o))throw new Error("invalid private key: out of range [1..N-1]");return o}return s}function tYe(t,e={}){const{Fp:n,Fn:r}=zZe("weierstrass",t,e),{h:s,n:i}=t;ok(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=e;if(o&&(!n.is0(t.a)||typeof o.beta!="bigint"||typeof o.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(W,S,$){const{x:R,y:M}=S.toAffine(),j=n.toBytes(R);if(TT("isCompressed",$),$){a();const z=!n.isOdd(M);return Em(ope(z),j)}else return Em(Uint8Array.of(4),j,n.toBytes(M))}function l(W){zl(W);const S=n.BYTES,$=S+1,R=2*S+1,M=W.length,j=W[0],z=W.subarray(1);if(M===$&&(j===2||j===3)){const N=n.fromBytes(z);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");const T=f(N);let U;try{U=n.sqrt(T)}catch(P){const H=P instanceof Error?": "+P.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}a();const L=n.isOdd(U);return(j&1)===1!==L&&(U=n.neg(U)),{x:N,y:U}}else if(M===R&&j===4){const N=n.fromBytes(z.subarray(S*0,S*1)),T=n.fromBytes(z.subarray(S*1,S*2));if(!p(N,T))throw new Error("bad point: is not on curve");return{x:N,y:T}}else throw new Error(`bad point: got length ${M}, expected compressed=${$} or uncompressed=${R}`)}const u=e.toBytes||c,d=e.fromBytes||l,f=eYe(n,t.a,t.b);function p(W,S){const $=n.sqr(S),R=f(W);return n.eql($,R)}if(!p(t.Gx,t.Gy))throw new Error("bad curve params: generator point");const m=n.mul(n.pow(t.a,RA),JZe),y=n.mul(n.sqr(t.b),BigInt(27));if(n.is0(n.add(m,y)))throw new Error("bad curve params: a or b");function b(W,S,$=!1){if(!n.isValid(S)||$&&n.is0(S))throw new Error(`bad point coordinate ${W}`);return S}function v(W){if(!(W instanceof _))throw new Error("ProjectivePoint expected")}const x=WQ((W,S)=>{const{px:$,py:R,pz:M}=W;if(n.eql(M,n.ONE))return{x:$,y:R};const j=W.is0();S==null&&(S=j?n.ONE:n.inv(M));const z=n.mul($,S),N=n.mul(R,S),T=n.mul(M,S);if(j)return{x:n.ZERO,y:n.ZERO};if(!n.eql(T,n.ONE))throw new Error("invZ was invalid");return{x:z,y:N}}),E=WQ(W=>{if(W.is0()){if(e.allowInfinityPoint&&!n.is0(W.py))return;throw new Error("bad point: ZERO")}const{x:S,y:$}=W.toAffine();if(!n.isValid(S)||!n.isValid($))throw new Error("bad point: x or y not field elements");if(!p(S,$))throw new Error("bad point: equation left != right");if(!W.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(W,S,$,R,M){return $=new _(n.mul($.px,W),$.py,$.pz),S=CE(R,S),$=CE(M,$),S.add($)}class _{constructor(S,$,R){this.px=b("x",S),this.py=b("y",$,!0),this.pz=b("z",R),Object.freeze(this)}static fromAffine(S){const{x:$,y:R}=S||{};if(!S||!n.isValid($)||!n.isValid(R))throw new Error("invalid affine point");if(S instanceof _)throw new Error("projective point not allowed");return n.is0($)&&n.is0(R)?_.ZERO:new _($,R,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){return MZe(_,"pz",S)}static fromBytes(S){return zl(S),_.fromHex(S)}static fromHex(S){const $=_.fromAffine(d(Na("pointHex",S)));return $.assertValidity(),$}static fromPrivateKey(S){const $=ipe(r,e.allowedPrivateKeyLengths,e.wrapPrivateKey);return _.BASE.multiply($(S))}static msm(S,$){return jZe(_,r,S,$)}precompute(S=8,$=!0){return B.setWindowSize(this,S),$||this.multiply(RA),this}_setWindowSize(S){this.precompute(S)}assertValidity(){E(this)}hasEvenY(){const{y:S}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(S)}equals(S){v(S);const{px:$,py:R,pz:M}=this,{px:j,py:z,pz:N}=S,T=n.eql(n.mul($,N),n.mul(j,M)),U=n.eql(n.mul(R,N),n.mul(z,M));return T&&U}negate(){return new _(this.px,n.neg(this.py),this.pz)}double(){const{a:S,b:$}=t,R=n.mul($,RA),{px:M,py:j,pz:z}=this;let N=n.ZERO,T=n.ZERO,U=n.ZERO,L=n.mul(M,M),P=n.mul(j,j),H=n.mul(z,z),Y=n.mul(M,j);return Y=n.add(Y,Y),U=n.mul(M,z),U=n.add(U,U),N=n.mul(S,U),T=n.mul(R,H),T=n.add(N,T),N=n.sub(P,T),T=n.add(P,T),T=n.mul(N,T),N=n.mul(Y,N),U=n.mul(R,U),H=n.mul(S,H),Y=n.sub(L,H),Y=n.mul(S,Y),Y=n.add(Y,U),U=n.add(L,L),L=n.add(U,L),L=n.add(L,H),L=n.mul(L,Y),T=n.add(T,L),H=n.mul(j,z),H=n.add(H,H),L=n.mul(H,Y),N=n.sub(N,L),U=n.mul(H,P),U=n.add(U,U),U=n.add(U,U),new _(N,T,U)}add(S){v(S);const{px:$,py:R,pz:M}=this,{px:j,py:z,pz:N}=S;let T=n.ZERO,U=n.ZERO,L=n.ZERO;const P=t.a,H=n.mul(t.b,RA);let Y=n.mul($,j),re=n.mul(R,z),de=n.mul(M,N),fe=n.add($,R),ve=n.add(j,z);fe=n.mul(fe,ve),ve=n.add(Y,re),fe=n.sub(fe,ve),ve=n.add($,M);let Ee=n.add(j,N);return ve=n.mul(ve,Ee),Ee=n.add(Y,de),ve=n.sub(ve,Ee),Ee=n.add(R,M),T=n.add(z,N),Ee=n.mul(Ee,T),T=n.add(re,de),Ee=n.sub(Ee,T),L=n.mul(P,ve),T=n.mul(H,de),L=n.add(T,L),T=n.sub(re,L),L=n.add(re,L),U=n.mul(T,L),re=n.add(Y,Y),re=n.add(re,Y),de=n.mul(P,de),ve=n.mul(H,ve),re=n.add(re,de),de=n.sub(Y,de),de=n.mul(P,de),ve=n.add(ve,de),Y=n.mul(re,ve),U=n.add(U,Y),Y=n.mul(Ee,ve),T=n.mul(fe,T),T=n.sub(T,Y),Y=n.mul(fe,re),L=n.mul(Ee,L),L=n.add(L,Y),new _(T,U,L)}subtract(S){return this.add(S.negate())}is0(){return this.equals(_.ZERO)}multiply(S){const{endo:$}=e;if(!r.isValidNot0(S))throw new Error("invalid scalar: out of range");let R,M;const j=z=>B.wNAFCached(this,z,_.normalizeZ);if($){const{k1neg:z,k1:N,k2neg:T,k2:U}=$.splitScalar(S),{p:L,f:P}=j(N),{p:H,f:Y}=j(U);M=P.add(Y),R=A($.beta,L,H,z,T)}else{const{p:z,f:N}=j(S);R=z,M=N}return _.normalizeZ([R,M])[0]}multiplyUnsafe(S){const{endo:$}=e,R=this;if(!r.isValid(S))throw new Error("invalid scalar: out of range");if(S===_E||R.is0())return _.ZERO;if(S===SE)return R;if(B.hasPrecomputes(this))return this.multiply(S);if($){const{k1neg:M,k1:j,k2neg:z,k2:N}=$.splitScalar(S),{p1:T,p2:U}=FZe(_,R,j,N);return A($.beta,T,U,M,z)}else return B.wNAFCachedUnsafe(R,S)}multiplyAndAddUnsafe(S,$,R){const M=this.multiplyUnsafe($).add(S.multiplyUnsafe(R));return M.is0()?void 0:M}toAffine(S){return x(this,S)}isTorsionFree(){const{isTorsionFree:S}=e;return s===SE?!0:S?S(_,this):B.wNAFCachedUnsafe(this,i).is0()}clearCofactor(){const{clearCofactor:S}=e;return s===SE?this:S?S(_,this):this.multiplyUnsafe(s)}toBytes(S=!0){return TT("isCompressed",S),this.assertValidity(),u(_,this,S)}toRawBytes(S=!0){return this.toBytes(S)}toHex(S=!0){return KC(this.toBytes(S))}toString(){return``}}_.BASE=new _(t.Gx,t.Gy,n.ONE),_.ZERO=new _(n.ZERO,n.ONE,n.ZERO),_.Fp=n,_.Fn=r;const k=r.BITS,B=UZe(_,e.endo?Math.ceil(k/2):k);return _}function ope(t){return Uint8Array.of(t?2:3)}function nYe(t,e,n={}){ok(e,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=e.randomBytes||fx,s=e.hmac||((R,...M)=>nk(e.hash,R,Em(...M))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o;function l(R){const M=a>>SE;return R>M}function u(R){return l(R)?o.neg(R):R}function d(R,M){if(!o.isValidNot0(M))throw new Error(`invalid signature ${R}: out of range 1..CURVE.n`)}class f{constructor(M,j,z){d("r",M),d("s",j),this.r=M,this.s=j,z!=null&&(this.recovery=z),Object.freeze(this)}static fromCompact(M){const j=o.BYTES,z=Na("compactSignature",M,j*2);return new f(o.fromBytes(z.subarray(0,j)),o.fromBytes(z.subarray(j,j*2)))}static fromDER(M){const{r:j,s:z}=hh.toSig(Na("DER",M));return new f(j,z)}assertValidity(){}addRecoveryBit(M){return new f(this.r,this.s,M)}recoverPublicKey(M){const j=i.ORDER,{r:z,s:N,recovery:T}=this;if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");if(a*QZe1)throw new Error("recovery id is ambiguous for h>1 curve");const U=T===2||T===3?z+a:z;if(!i.isValid(U))throw new Error("recovery id 2 or 3 invalid");const L=i.toBytes(U),P=t.fromHex(Em(ope((T&1)===0),L)),H=o.inv(U),Y=E(Na("msgHash",M)),re=o.create(-Y*H),de=o.create(N*H),fe=t.BASE.multiplyUnsafe(re).add(P.multiplyUnsafe(de));if(fe.is0())throw new Error("point at infinify");return fe.assertValidity(),fe}hasHighS(){return l(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o.neg(this.s),this.recovery):this}toBytes(M){if(M==="compact")return Em(o.toBytes(this.r),o.toBytes(this.s));if(M==="der")return Mz(hh.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return KC(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return KC(this.toBytes("compact"))}}const p=ipe(o,n.allowedPrivateKeyLengths,n.wrapPrivateKey),m={isValidPrivateKey(R){try{return p(R),!0}catch{return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{const R=a;return DZe(r(tpe(R)),R)},precompute(R=8,M=t.BASE){return M.precompute(R,!1)}};function y(R,M=!0){return t.fromPrivateKey(R).toBytes(M)}function b(R){if(typeof R=="bigint")return!1;if(R instanceof t)return!0;const M=Na("key",R).length,j=i.BYTES,z=j+1,N=2*j+1;if(!(n.allowedPrivateKeyLengths||o.BYTES===z))return M===z||M===N}function v(R,M,j=!0){if(b(R)===!0)throw new Error("first arg must be private key");if(b(M)===!1)throw new Error("second arg must be public key");return t.fromHex(M).multiply(p(R)).toBytes(j)}const x=e.bits2int||function(R){if(R.length>8192)throw new Error("input is too large");const M=sk(R),j=R.length*8-c;return j>0?M>>BigInt(j):M},E=e.bits2int_modN||function(R){return o.create(x(R))},A=ik(c);function _(R){return P7("num < 2^"+c,R,_E,A),o.toBytes(R)}function k(R,M,j=B){if(["recovered","canonical"].some(fe=>fe in j))throw new Error("sign() legacy options not supported");const{hash:z}=e;let{lowS:N,prehash:T,extraEntropy:U}=j;N==null&&(N=!0),R=Na("msgHash",R),YQ(j),T&&(R=Na("prehashed msgHash",z(R)));const L=E(R),P=p(M),H=[_(P),_(L)];if(U!=null&&U!==!1){const fe=U===!0?r(i.BYTES):U;H.push(Na("extraEntropy",fe))}const Y=Em(...H),re=L;function de(fe){const ve=x(fe);if(!o.isValidNot0(ve))return;const Ee=o.inv(ve),oe=t.BASE.multiply(ve).toAffine(),Oe=o.create(oe.x);if(Oe===_E)return;const je=o.create(Ee*o.create(re+Oe*P));if(je===_E)return;let V=(oe.x===Oe?0:2)|Number(oe.y&SE),we=je;return N&&l(je)&&(we=u(je),V^=1),new f(Oe,we,V)}return{seed:Y,k2sig:de}}const B={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function S(R,M,j=B){const{seed:z,k2sig:N}=k(R,M,j);return AZe(e.hash.outputLen,o.BYTES,s)(z,N)}t.BASE.precompute(8);function $(R,M,j,z=W){const N=R;M=Na("msgHash",M),j=Na("publicKey",j),YQ(z);const{lowS:T,prehash:U,format:L}=z;if("strict"in z)throw new Error("options.strict was renamed to lowS");if(L!==void 0&&!["compact","der","js"].includes(L))throw new Error('format must be "compact", "der" or "js"');const P=typeof N=="string"||Oz(N),H=!P&&!L&&typeof N=="object"&&N!==null&&typeof N.r=="bigint"&&typeof N.s=="bigint";if(!P&&!H)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Y,re;try{if(H)if(L===void 0||L==="js")Y=new f(N.r,N.s);else throw new Error("invalid format");if(P){try{L!=="compact"&&(Y=f.fromDER(N))}catch(V){if(!(V instanceof hh.Err))throw V}!Y&&L!=="der"&&(Y=f.fromCompact(N))}re=t.fromHex(j)}catch{return!1}if(!Y||T&&Y.hasHighS())return!1;U&&(M=e.hash(M));const{r:de,s:fe}=Y,ve=E(M),Ee=o.inv(fe),oe=o.create(ve*Ee),Oe=o.create(de*Ee),je=t.BASE.multiplyUnsafe(oe).add(re.multiplyUnsafe(Oe));return je.is0()?!1:o.create(je.x)===de}return Object.freeze({getPublicKey:y,getSharedSecret:v,sign:S,verify:$,utils:m,Point:t,Signature:f})}function rYe(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=hx(e.n,t.nBitLength),s={Fp:n,Fn:r,allowedPrivateKeyLengths:t.allowedPrivateKeyLengths,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,wrapPrivateKey:t.wrapPrivateKey,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function sYe(t){const{CURVE:e,curveOpts:n}=rYe(t),r={hash:t.hash,hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,ecdsaOpts:r}}function iYe(t,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:t})}function oYe(t){const{CURVE:e,curveOpts:n,ecdsaOpts:r}=sYe(t),s=tYe(e,n),i=nYe(s,r,n);return iYe(t,i)}function R7(t,e){const n=r=>oYe({...t,hash:r});return{...n(e),create:n}}const ape={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},cpe={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},lpe={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},aYe=hx(ape.p),cYe=hx(cpe.p),lYe=hx(lpe.p),uYe=R7({...ape,Fp:aYe,lowS:!1},tk);R7({...cpe,Fp:cYe,lowS:!1},yGe),R7({...lpe,Fp:lYe,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},mGe);const dYe=uYe,upe="base10",ra="base16",Bu="base64pad",vg="base64url",o3="utf8",dpe=0,Nh=1,a3=2,fYe=0,XQ=1,AE=12,zz=32;function hYe(){const t=k7.utils.randomPrivateKey(),e=k7.getPublicKey(t);return{privateKey:Ya(t,ra),publicKey:Ya(e,ra)}}function O7(){const t=fx(zz);return Ya(t,ra)}function pYe(t,e){const n=k7.getSharedSecret(kl(t,ra),kl(e,ra)),r=CZe(rk,n,void 0,void 0,zz);return Ya(r,ra)}function KI(t){const e=rk(kl(t,ra));return Ya(e,ra)}function jd(t){const e=rk(kl(t,o3));return Ya(e,ra)}function fpe(t){return kl(`${t}`,upe)}function xy(t){return Number(Ya(t,upe))}function hpe(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ppe(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4;return e+"=".repeat(n)}function gYe(t){const e=fpe(typeof t.type<"u"?t.type:dpe);if(xy(e)===Nh&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof t.senderPublicKey<"u"?kl(t.senderPublicKey,ra):void 0,r=typeof t.iv<"u"?kl(t.iv,ra):fx(AE),s=kl(t.symKey,ra),i=qhe(s,r).encrypt(kl(t.message,o3)),o=gpe({type:e,sealed:i,iv:r,senderPublicKey:n});return t.encoding===vg?hpe(o):o}function mYe(t){const e=kl(t.symKey,ra),{sealed:n,iv:r}=ZC({encoded:t.encoded,encoding:t.encoding}),s=qhe(e,r).decrypt(n);if(s===null)throw new Error("Failed to decrypt");return Ya(s,o3)}function yYe(t,e){const n=fpe(a3),r=fx(AE),s=kl(t,o3),i=gpe({type:n,sealed:s,iv:r});return e===vg?hpe(i):i}function wYe(t,e){const{sealed:n}=ZC({encoded:t,encoding:e});return Ya(n,o3)}function gpe(t){if(xy(t.type)===a3)return Ya(EE([t.type,t.sealed]),Bu);if(xy(t.type)===Nh){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ya(EE([t.type,t.senderPublicKey,t.iv,t.sealed]),Bu)}return Ya(EE([t.type,t.iv,t.sealed]),Bu)}function ZC(t){const e=(t.encoding||Bu)===vg?ppe(t.encoded):t.encoded,n=kl(e,Bu),r=n.slice(fYe,XQ),s=XQ;if(xy(r)===Nh){const c=s+zz,l=c+AE,u=n.slice(s,c),d=n.slice(c,l),f=n.slice(l);return{type:r,sealed:f,iv:d,senderPublicKey:u}}if(xy(r)===a3){const c=n.slice(s),l=fx(AE);return{type:r,sealed:c,iv:l}}const i=s+AE,o=n.slice(s,i),a=n.slice(i);return{type:r,sealed:a,iv:o}}function bYe(t,e){const n=ZC({encoded:t,encoding:e?.encoding});return mpe({type:xy(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?Ya(n.senderPublicKey,ra):void 0,receiverPublicKey:e?.receiverPublicKey})}function mpe(t){const e=t?.type||dpe;if(e===Nh){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function QQ(t){return t.type===Nh&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function JQ(t){return t.type===a3}function vYe(t){const e=Buffer.from(t.x,"base64"),n=Buffer.from(t.y,"base64");return EE([new Uint8Array([4]),e,n])}function xYe(t,e){const[n,r,s]=t.split("."),i=Buffer.from(ppe(s),"base64");if(i.length!==64)throw new Error("Invalid signature length");const o=i.slice(0,32),a=i.slice(32,64),c=`${n}.${r}`,l=rk(c),u=vYe(e);if(!dYe.verify(EE([o,a]),l,u))throw new Error("Invalid signature");return p7(t).payload}const EYe="irn";function PT(t){return t?.relay||{protocol:EYe}}function V2(t){const e=Zqe[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function CYe(t,e="-"){const n={},r="relay"+e;return Object.keys(t).forEach(s=>{if(s.startsWith(r)){const i=s.replace(r,""),o=t[s];n[i]=o}}),n}function eJ(t){if(!t.includes("wc:")){const l=Ihe(t);l!=null&&l.includes("wc:")&&(t=l)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),n=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),s=t.substring(e+1,n).split("@"),i=typeof n<"u"?t.substring(n):"",o=new URLSearchParams(i),a={};o.forEach((l,u)=>{a[u]=l});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:_Ye(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:CYe(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function _Ye(t){return t.startsWith("//")?t.substring(2):t}function SYe(t,e="-"){const n="relay",r={};return Object.keys(t).forEach(s=>{const i=s,o=n+e+i;t[i]&&(r[o]=t[i])}),r}function tJ(t){const e=new URLSearchParams,n=SYe(t.relay);Object.keys(n).sort().forEach(s=>{e.set(s,n[s])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const r=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${r}`}function OA(t,e,n){return`${t}?wc_ev=${n}&topic=${e}`}var AYe=Object.defineProperty,IYe=Object.defineProperties,TYe=Object.getOwnPropertyDescriptors,nJ=Object.getOwnPropertySymbols,NYe=Object.prototype.hasOwnProperty,PYe=Object.prototype.propertyIsEnumerable,rJ=(t,e,n)=>e in t?AYe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,kYe=(t,e)=>{for(var n in e||(e={}))NYe.call(e,n)&&rJ(t,n,e[n]);if(nJ)for(var n of nJ(e))PYe.call(e,n)&&rJ(t,n,e[n]);return t},RYe=(t,e)=>IYe(t,TYe(e));function px(t){const e=[];return t.forEach(n=>{const[r,s]=n.split(":");e.push(`${r}:${s}`)}),e}function OYe(t){const e=[];return Object.values(t).forEach(n=>{e.push(...px(n.accounts))}),e}function $Ye(t,e){const n=[];return Object.values(t).forEach(r=>{px(r.accounts).includes(e)&&n.push(...r.methods)}),n}function DYe(t,e){const n=[];return Object.values(t).forEach(r=>{px(r.accounts).includes(e)&&n.push(...r.events)}),n}function ak(t){return t.includes(":")}function Fb(t){return ak(t)?t.split(":")[0]:t}function sJ(t){var e,n,r;const s={};if(!tf(t))return s;for(const[i,o]of Object.entries(t)){const a=ak(i)?[i]:o.chains,c=o.methods||[],l=o.events||[],u=Fb(i);s[u]=RYe(kYe({},s[u]),{chains:ef(a,(e=s[u])==null?void 0:e.chains),methods:ef(c,(n=s[u])==null?void 0:n.methods),events:ef(l,(r=s[u])==null?void 0:r.events)})}return s}function MYe(t){const e={};return t?.forEach(n=>{var r;const[s,i]=n.split(":");e[s]||(e[s]={accounts:[],chains:[],events:[],methods:[]}),e[s].accounts.push(n),(r=e[s].chains)==null||r.push(`${s}:${i}`)}),e}function iJ(t,e){e=e.map(r=>r.replace("did:pkh:",""));const n=MYe(e);for(const[r,s]of Object.entries(n))s.methods?s.methods=ef(s.methods,t):s.methods=t,s.events=["chainChanged","accountsChanged"];return n}function LYe(t,e){var n,r,s,i,o,a;const c=sJ(t),l=sJ(e),u={},d=Object.keys(c).concat(Object.keys(l));for(const f of d)u[f]={chains:ef((n=c[f])==null?void 0:n.chains,(r=l[f])==null?void 0:r.chains),methods:ef((s=c[f])==null?void 0:s.methods,(i=l[f])==null?void 0:i.methods),events:ef((o=c[f])==null?void 0:o.events,(a=l[f])==null?void 0:a.events)};return u}const BYe={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}},UYe={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 gt(t,e){const{message:n,code:r}=UYe[t];return{message:e?`${n} ${e}`:n,code:r}}function ds(t,e){const{message:n,code:r}=BYe[t];return{message:e?`${n} ${e}`:n,code:r}}function Ph(t,e){return!!Array.isArray(t)}function tf(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Co(t){return typeof t>"u"}function js(t,e){return e&&Co(t)?!0:typeof t=="string"&&!!t.trim().length}function Wz(t,e){return typeof t=="number"&&!isNaN(t)}function FYe(t,e){const{requiredNamespaces:n}=e,r=Object.keys(t.namespaces),s=Object.keys(n);let i=!0;return xm(s,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],u=px(a),d=n[o];(!xm(Ehe(o,d),u)||!xm(d.methods,c)||!xm(d.events,l))&&(i=!1)}),i):!1}function kT(t){return js(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function jYe(t){if(js(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const n=e[0]+":"+e[1];return!!e[2]&&kT(n)}}return!1}function zYe(t){function e(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(js(t,!1)){if(e(t))return!0;const n=Ihe(t);return e(n)}}catch{}return!1}function WYe(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function VYe(t){return t?.topic}function HYe(t,e){let n=null;return js(t?.publicKey,!1)||(n=gt("MISSING_OR_INVALID",`${e} controller public key should be a string`)),n}function oJ(t){let e=!0;return Ph(t)?t.length&&(e=t.every(n=>js(n,!1))):e=!1,e}function qYe(t,e,n){let r=null;return Ph(e)&&e.length?e.forEach(s=>{r||kT(s)||(r=ds("UNSUPPORTED_CHAINS",`${n}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):kT(t)||(r=ds("UNSUPPORTED_CHAINS",`${n}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function KYe(t,e,n){let r=null;return Object.entries(t).forEach(([s,i])=>{if(r)return;const o=qYe(s,Ehe(s,i),`${e} ${n}`);o&&(r=o)}),r}function GYe(t,e){let n=null;return Ph(t)?t.forEach(r=>{n||jYe(r)||(n=ds("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=ds("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function ZYe(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const s=GYe(r?.accounts,`${e} namespace`);s&&(n=s)}),n}function YYe(t,e){let n=null;return oJ(t?.methods)?oJ(t?.events)||(n=ds("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):n=ds("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),n}function ype(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const s=YYe(r,`${e}, namespace`);s&&(n=s)}),n}function XYe(t,e,n){let r=null;if(t&&tf(t)){const s=ype(t,e);s&&(r=s);const i=KYe(t,e,n);i&&(r=i)}else r=gt("MISSING_OR_INVALID",`${e}, ${n} should be an object with data`);return r}function Q$(t,e){let n=null;if(t&&tf(t)){const r=ype(t,e);r&&(n=r);const s=ZYe(t,e);s&&(n=s)}else n=gt("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return n}function wpe(t){return js(t.protocol,!0)}function QYe(t,e){let n=!1;return t?t&&Ph(t)&&t.length&&t.forEach(r=>{n=wpe(r)}):n=!0,n}function JYe(t){return typeof t=="number"}function Aa(t){return typeof t<"u"&&typeof t!==null}function eXe(t){return!(!t||typeof t!="object"||!t.code||!Wz(t.code)||!t.message||!js(t.message,!1))}function tXe(t){return!(Co(t)||!js(t.method,!1))}function nXe(t){return!(Co(t)||Co(t.result)&&Co(t.error)||!Wz(t.id)||!js(t.jsonrpc,!1))}function rXe(t){return!(Co(t)||!js(t.name,!1))}function aJ(t,e){return!(!kT(e)||!OYe(t).includes(e))}function sXe(t,e,n){return js(n,!1)?$Ye(t,e).includes(n):!1}function iXe(t,e,n){return js(n,!1)?DYe(t,e).includes(n):!1}function cJ(t,e,n){let r=null;const s=oXe(t),i=aXe(e),o=Object.keys(s),a=Object.keys(i),c=lJ(Object.keys(t)),l=lJ(Object.keys(e)),u=c.filter(d=>!l.includes(d));return u.length&&(r=gt("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces. + Required: ${u.toString()} + Received: ${Object.keys(e).toString()}`)),xm(o,a)||(r=gt("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces. + Required: ${o.toString()} + Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||r)return;const f=px(e[d].accounts);f.includes(d)||(r=gt("NON_CONFORMING_NAMESPACES",`${n} namespaces accounts don't satisfy namespace accounts for ${d} + Required: ${d} + Approved: ${f.toString()}`))}),o.forEach(d=>{r||(xm(s[d].methods,i[d].methods)?xm(s[d].events,i[d].events)||(r=gt("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${d}`)):r=gt("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${d}`))}),r}function oXe(t){const e={};return Object.keys(t).forEach(n=>{var r;n.includes(":")?e[n]=t[n]:(r=t[n].chains)==null||r.forEach(s=>{e[s]={methods:t[n].methods,events:t[n].events}})}),e}function lJ(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function aXe(t){const e={};return Object.keys(t).forEach(n=>{n.includes(":")?e[n]=t[n]:px(t[n].accounts)?.forEach(s=>{e[s]={accounts:t[n].accounts.filter(i=>i.includes(`${s}:`)),methods:t[n].methods,events:t[n].events}})}),e}function cXe(t,e){return Wz(t)&&t<=e.max&&t>=e.min}function uJ(){const t=s3();return new Promise(e=>{switch(t){case $c.browser:e(lXe());break;case $c.reactNative:e(uXe());break;case $c.node:e(dXe());break;default:e(!0)}})}function lXe(){return dx()&&navigator?.onLine}async function uXe(){return k0()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function dXe(){return!0}function fXe(t){switch(s3()){case $c.browser:hXe(t);break;case $c.reactNative:pXe(t);break}}function hXe(t){!k0()&&dx()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function pXe(t){k0()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function gXe(){var t;return dx()&&wy()?((t=wy())==null?void 0:t.visibilityState)==="visible":!0}const J$={};class f2{static get(e){return J$[e]}static set(e,n){J$[e]=n}static delete(e){delete J$[e]}}function mXe(t){const e=ux.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function yXe({publicKey:t,signature:e,payload:n}){var r;const s=$7(n.method),i=128|parseInt(((r=n.version)==null?void 0:r.toString())||"4"),o=vXe(n.address),a=n.era==="00"?new Uint8Array([0]):$7(n.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(n.nonce,16),l=new Uint8Array([c&255,c>>8&255]),u=BigInt(`0x${bXe(n.tip)}`),d=EXe(u),f=new Uint8Array([0,...t,o,...e,...a,...l,...d,...s]),p=xXe(f.length+1);return new Uint8Array([...p,i,...f])}function wXe(t){const e=$7(t),n=aKe.blake2b(e,void 0,32);return"0x"+Buffer.from(n).toString("hex")}function $7(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function bXe(t){return t.startsWith("0x")?t.slice(2):t}function vXe(t){const e=ux.decode(t)[0];return e===42?0:e===60?2:1}function xXe(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function EXe(t){if(t>BigInt(8)&BigInt(255))])}else if(t>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function CXe(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),n=mXe(t.transaction.address),r=yXe({publicKey:n,signature:e,payload:t.transaction}),s=Buffer.from(r).toString("hex");return wXe(s)}const _Xe="PARSE_ERROR",SXe="INVALID_REQUEST",AXe="METHOD_NOT_FOUND",IXe="INVALID_PARAMS",bpe="INTERNAL_ERROR",Vz="SERVER_ERROR",TXe=[-32700,-32600,-32601,-32602,-32603],IE={[_Xe]:{code:-32700,message:"Parse error"},[SXe]:{code:-32600,message:"Invalid Request"},[AXe]:{code:-32601,message:"Method not found"},[IXe]:{code:-32602,message:"Invalid params"},[bpe]:{code:-32603,message:"Internal error"},[Vz]:{code:-32e3,message:"Server error"}},vpe=Vz;function NXe(t){return TXe.includes(t)}function dJ(t){return Object.keys(IE).includes(t)?IE[t]:IE[vpe]}function PXe(t){const e=Object.values(IE).find(n=>n.code===t);return e||IE[vpe]}function xpe(t,e,n){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${e}`):t}var Epe={};/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */var D7=function(t,e){return D7=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)r.hasOwnProperty(s)&&(n[s]=r[s])},D7(t,e)};function kXe(t,e){D7(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var M7=function(){return M7=Object.assign||function(e){for(var n,r=1,s=arguments.length;r=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i}function $Xe(t,e){return function(n,r){e(n,r,t)}}function DXe(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function MXe(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((r=r.apply(t,e||[])).next())})}function LXe(t,e){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,s,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,s&&(i=l[0]&2?s.return:l[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,l[1])).done)return i;switch(s=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,s=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Cpe(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i}function FXe(){for(var t=[],e=0;e1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(m){d(i[0][3],m)}}function c(f){f.value instanceof YC?Promise.resolve(f.value.v).then(l,u):d(i[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function d(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function WXe(t){var e,n;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,i){e[s]=t[s]?function(o){return(n=!n)?{value:YC(t[s](o)),done:s==="return"}:i?i(o):o}:i}}function VXe(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof L7=="function"?L7(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=t[i]&&function(o){return new Promise(function(a,c){o=t[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(l){i({value:l,done:a})},o)}}function HXe(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function qXe(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function KXe(t){return t&&t.__esModule?t:{default:t}}function GXe(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function ZXe(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}const YXe=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return M7},__asyncDelegator:WXe,__asyncGenerator:zXe,__asyncValues:VXe,__await:YC,__awaiter:MXe,__classPrivateFieldGet:GXe,__classPrivateFieldSet:ZXe,__createBinding:BXe,__decorate:OXe,__exportStar:UXe,__extends:kXe,__generator:LXe,__importDefault:KXe,__importStar:qXe,__makeTemplateObject:HXe,__metadata:DXe,__param:$Xe,__read:Cpe,__rest:RXe,__spread:FXe,__spreadArrays:jXe,__values:L7},Symbol.toStringTag,{value:"Module"})),XXe=Zy(YXe);var Jf={},fJ;function QXe(){if(fJ)return Jf;fJ=1,Object.defineProperty(Jf,"__esModule",{value:!0}),Jf.isBrowserCryptoAvailable=Jf.getSubtleCrypto=Jf.getBrowerCrypto=void 0;function t(){return kr?.crypto||kr?.msCrypto||{}}Jf.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Jf.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return Jf.isBrowserCryptoAvailable=n,Jf}var eh={},hJ;function JXe(){if(hJ)return eh;hJ=1,Object.defineProperty(eh,"__esModule",{value:!0}),eh.isBrowser=eh.isNode=eh.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}eh.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}eh.isNode=e;function n(){return!t()&&!e()}return eh.isBrowser=n,eh}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=XXe;e.__exportStar(QXe(),t),e.__exportStar(JXe(),t)})(Epe);function Ld(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function Sm(t=6){return BigInt(Ld(t))}function Pg(t,e,n){return{id:n||Ld(),jsonrpc:"2.0",method:t,params:e}}function ck(t,e){return{id:t,jsonrpc:"2.0",result:e}}function lk(t,e,n){return{id:t,jsonrpc:"2.0",error:eQe(e)}}function eQe(t,e){return typeof t>"u"?dJ(bpe):(typeof t=="string"&&(t=Object.assign(Object.assign({},dJ(Vz)),{message:t})),NXe(t.code)&&(t=PXe(t.code)),t)}let tQe=class{},nQe=class extends tQe{constructor(){super()}},rQe=class extends nQe{constructor(e){super()}};const sQe="^https?:",iQe="^wss?:";function oQe(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function _pe(t,e){const n=oQe(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function pJ(t){return _pe(t,sQe)}function gJ(t){return _pe(t,iQe)}function aQe(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Spe(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Hz(t){return Spe(t)&&"method"in t}function uk(t){return Spe(t)&&(Bd(t)||yl(t))}function Bd(t){return"result"in t}function yl(t){return"error"in t}let Jl=class extends rQe{constructor(e){super(e),this.events=new Ql.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async request(e,n){return this.requestStrict(Pg(e.method,e.params||[],e.id||Sm().toString()),n)}async requestStrict(e,n){return new Promise(async(r,s)=>{if(!this.connection.connected)try{await this.open()}catch(i){s(i)}this.events.on(`${e.id}`,i=>{yl(i)?s(i.error):r(i.result)});try{await this.connection.send(e,n)}catch(i){s(i)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),uk(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const cQe=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),lQe=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",mJ=t=>t.split("?")[0],yJ=10,uQe=cQe();let dQe=class{constructor(e){if(this.url=e,this.events=new Ql.EventEmitter,this.registering=!1,!gJ(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Zh(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!gJ(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,s)=>{this.events.once("register_error",i=>{this.resetMaxListeners(),s(i)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((n,r)=>{const s=Epe.isReactNative()?void 0:{rejectUnauthorized:!aQe(e)},i=new uQe(e,[],s);lQe()?i.onerror=o=>{const a=o;r(this.emitError(a.error))}:i.on("error",o=>{r(this.emitError(o))}),i.onopen=()=>{this.onOpen(i),n(i)}})}onOpen(e){e.onmessage=n=>this.onPayload(n),e.onclose=n=>this.onClose(n),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const n=typeof e.data=="string"?yy(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),s=r.message||r.toString(),i=lk(e,s);this.events.emit("payload",i)}parseError(e,n=this.url){return xpe(e,mJ(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>yJ&&this.events.setMaxListeners(yJ)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${mJ(this.url)}`));return this.events.emit("register_error",n),n}};var fQe={};const Ape="wc",Ipe=2,RT="core",ff=`${Ape}@2:${RT}:`,hQe={name:RT,logger:"error"},pQe={database:":memory:"},gQe="crypto",wJ="client_ed25519_seed",mQe=yt.ONE_DAY,yQe="keychain",wQe="0.3",bQe="messages",vQe="0.3",bJ=yt.SIX_HOURS,xQe="publisher",Tpe="irn",EQe="error",Npe="wss://relay.walletconnect.org",CQe="relayer",yi={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"},_Qe="_subscription",ul={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},SQe=.1,B7="2.21.5",is={link_mode:"link_mode",relay:"relay"},GI={inbound:"inbound",outbound:"outbound"},AQe="0.3",IQe="WALLETCONNECT_CLIENT_ID",vJ="WALLETCONNECT_LINK_MODE_APPS",_c={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},TQe="subscription",NQe="0.3",PQe="pairing",kQe="0.3",h2={wc_pairingDelete:{req:{ttl:yt.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:yt.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:yt.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:yt.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:yt.ONE_DAY,prompt:!1,tag:0},res:{ttl:yt.ONE_DAY,prompt:!1,tag:0}}},lm={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},gu={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},RQe="history",OQe="0.3",$Qe="expirer",pl={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},DQe="0.3",MQe="verify-api",LQe="https://verify.walletconnect.com",Ppe="https://verify.walletconnect.org",TE=Ppe,BQe=`${TE}/v3`,UQe=[LQe,Ppe],FQe="echo",jQe="https://echo.walletconnect.com",Od={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"},ih={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"},mu={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"},Q0={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"},J0={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",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",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},p2={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",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"},zQe=.1,WQe="event-client",VQe=86400,HQe="https://pulse.walletconnect.org/batch";function qQe(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r>>0,A=new Uint8Array(E);v!==x;){for(var _=m[v],k=0,B=E-1;(_!==0||k>>0,A[B]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");b=k,v++}for(var W=E-b;W!==E&&A[W]===0;)W++;for(var S=c.repeat(y);W>>0,E=new Uint8Array(x);m[y];){var A=n[m.charCodeAt(y)];if(A===255)return;for(var _=0,k=x-1;(A!==0||_>>0,E[k]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");v=_,y++}if(m[y]!==" "){for(var B=x-v;B!==x&&E[B]===0;)B++;for(var W=new Uint8Array(b+(x-B)),S=b;B!==x;)W[S++]=E[B++];return W}}}function p(m){var y=f(m);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:p}}var KQe=qQe,GQe=KQe;const kpe=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},ZQe=t=>new TextEncoder().encode(t),YQe=t=>new TextDecoder().decode(t);class XQe{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class QQe{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Rpe(this,e)}}class JQe{constructor(e){this.decoders=e}or(e){return Rpe(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Rpe=(t,e)=>new JQe({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class eJe{constructor(e,n,r,s){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new XQe(e,n,r),this.decoder=new QQe(e,n,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const dk=({name:t,prefix:e,encode:n,decode:r})=>new eJe(t,e,n,r),c3=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:s}=GQe(n,e);return dk({prefix:t,name:e,encode:r,decode:i=>kpe(s(i))})},tJe=(t,e,n,r)=>{const s={};for(let u=0;u=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},nJe=(t,e,n)=>{const r=e[e.length-1]==="=",s=(1<n;)o-=n,i+=e[s&a>>o];if(o&&(i+=e[s&a<dk({prefix:e,name:t,encode(s){return nJe(s,r,n)},decode(s){return tJe(s,r,n,t)}}),rJe=dk({prefix:"\0",name:"identity",encode:t=>YQe(t),decode:t=>ZQe(t)});var sJe=Object.freeze({__proto__:null,identity:rJe});const iJe=Qi({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var oJe=Object.freeze({__proto__:null,base2:iJe});const aJe=Qi({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var cJe=Object.freeze({__proto__:null,base8:aJe});const lJe=c3({prefix:"9",name:"base10",alphabet:"0123456789"});var uJe=Object.freeze({__proto__:null,base10:lJe});const dJe=Qi({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),fJe=Qi({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hJe=Object.freeze({__proto__:null,base16:dJe,base16upper:fJe});const pJe=Qi({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),gJe=Qi({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),mJe=Qi({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yJe=Qi({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),wJe=Qi({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),bJe=Qi({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),vJe=Qi({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),xJe=Qi({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),EJe=Qi({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var CJe=Object.freeze({__proto__:null,base32:pJe,base32upper:gJe,base32pad:mJe,base32padupper:yJe,base32hex:wJe,base32hexupper:bJe,base32hexpad:vJe,base32hexpadupper:xJe,base32z:EJe});const _Je=c3({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),SJe=c3({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var AJe=Object.freeze({__proto__:null,base36:_Je,base36upper:SJe});const IJe=c3({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),TJe=c3({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var NJe=Object.freeze({__proto__:null,base58btc:IJe,base58flickr:TJe});const PJe=Qi({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kJe=Qi({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),RJe=Qi({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),OJe=Qi({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var $Je=Object.freeze({__proto__:null,base64:PJe,base64pad:kJe,base64url:RJe,base64urlpad:OJe});const Ope=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),DJe=Ope.reduce((t,e,n)=>(t[n]=e,t),[]),MJe=Ope.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function LJe(t){return t.reduce((e,n)=>(e+=DJe[n],e),"")}function BJe(t){const e=[];for(const n of t){const r=MJe[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const UJe=dk({prefix:"🚀",name:"base256emoji",encode:LJe,decode:BJe});var FJe=Object.freeze({__proto__:null,base256emoji:UJe}),jJe=$pe,xJ=128,zJe=127,WJe=~zJe,VJe=Math.pow(2,31);function $pe(t,e,n){e=e||[],n=n||0;for(var r=n;t>=VJe;)e[n++]=t&255|xJ,t/=128;for(;t&WJe;)e[n++]=t&255|xJ,t>>>=7;return e[n]=t|0,$pe.bytes=n-r+1,e}var HJe=U7,qJe=128,EJ=127;function U7(t,r){var n=0,r=r||0,s=0,i=r,o,a=t.length;do{if(i>=a)throw U7.bytes=0,new RangeError("Could not decode varint");o=t[i++],n+=s<28?(o&EJ)<=qJe);return U7.bytes=i-r,n}var KJe=Math.pow(2,7),GJe=Math.pow(2,14),ZJe=Math.pow(2,21),YJe=Math.pow(2,28),XJe=Math.pow(2,35),QJe=Math.pow(2,42),JJe=Math.pow(2,49),eet=Math.pow(2,56),tet=Math.pow(2,63),net=function(t){return t(Dpe.encode(t,e,n),e),_J=t=>Dpe.encodingLength(t),F7=(t,e)=>{const n=e.byteLength,r=_J(t),s=r+_J(n),i=new Uint8Array(s+n);return CJ(t,i,0),CJ(n,i,r),i.set(e,s),new set(t,n,e,i)};class set{constructor(e,n,r,s){this.code=e,this.size=n,this.digest=r,this.bytes=s}}const Mpe=({name:t,code:e,encode:n})=>new iet(t,e,n);class iet{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?F7(this.code,n):n.then(r=>F7(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Lpe=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),oet=Mpe({name:"sha2-256",code:18,encode:Lpe("SHA-256")}),aet=Mpe({name:"sha2-512",code:19,encode:Lpe("SHA-512")});var cet=Object.freeze({__proto__:null,sha256:oet,sha512:aet});const Bpe=0,uet="identity",Upe=kpe,det=t=>F7(Bpe,Upe(t)),fet={code:Bpe,name:uet,encode:Upe,digest:det};var het=Object.freeze({__proto__:null,identity:fet});new TextEncoder,new TextDecoder;const SJ={...sJe,...oJe,...cJe,...uJe,...hJe,...CJe,...AJe,...NJe,...$Je,...FJe};({...cet,...het});function Fpe(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function pet(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Fpe(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function jpe(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const AJ=jpe("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),eD=jpe("ascii","a",t=>{let e="a";for(let n=0;n{t=t.substring(1);const e=pet(t.length);for(let n=0;ne in t?yet(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Td=(t,e,n)=>wet(t,typeof e!="symbol"?e+"":e,n);class bet{constructor(e,n){this.core=e,this.logger=n,Td(this,"keychain",new Map),Td(this,"name",yQe),Td(this,"version",wQe),Td(this,"initialized",!1),Td(this,"storagePrefix",ff),Td(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Td(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Td(this,"set",async(r,s)=>{this.isInitialized(),this.keychain.set(r,s),await this.persist()}),Td(this,"get",r=>{this.isInitialized();const s=this.keychain.get(r);if(typeof s>"u"){const{message:i}=gt("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(i)}return s}),Td(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=Mo(n,this.name)}get context(){return sc(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,E7(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?C7(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=gt("NOT_INITIALIZED",this.name);throw new Error(e)}}}var vet=Object.defineProperty,xet=(t,e,n)=>e in t?vet(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ni=(t,e,n)=>xet(t,typeof e!="symbol"?e+"":e,n);class Eet{constructor(e,n,r){this.core=e,this.logger=n,Ni(this,"name",gQe),Ni(this,"keychain"),Ni(this,"randomSessionIdentifier",O7()),Ni(this,"initialized",!1),Ni(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ni(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),Ni(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),i=iQ(s);return Ufe(i.publicKey)}),Ni(this,"generateKeyPair",()=>{this.isInitialized();const s=hYe();return this.setPrivateKey(s.publicKey,s.privateKey)}),Ni(this,"signJWT",async s=>{this.isInitialized();const i=await this.getClientSeed(),o=iQ(i),a=this.randomSessionIdentifier;return await yVe(a,s,mQe,o)}),Ni(this,"generateSharedKey",(s,i,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=pYe(a,i);return this.setSymKey(c,o)}),Ni(this,"setSymKey",async(s,i)=>{this.isInitialized();const o=i||KI(s);return await this.keychain.set(o,s),o}),Ni(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ni(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ni(this,"encode",async(s,i,o)=>{this.isInitialized();const a=mpe(o),c=Zh(i);if(JQ(a))return yYe(c,o?.encoding);if(QQ(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;s=await this.generateSharedKey(f,p)}const l=this.getSymKey(s),{type:u,senderPublicKey:d}=a;return gYe({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),Ni(this,"decode",async(s,i,o)=>{this.isInitialized();const a=bYe(i,o);if(JQ(a)){const c=wYe(i,o?.encoding);return yy(c)}if(QQ(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;s=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(s),l=mYe({symKey:c,encoded:i,encoding:o?.encoding});return yy(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ni(this,"getPayloadType",(s,i=Bu)=>{const o=ZC({encoded:s,encoding:i});return xy(o.type)}),Ni(this,"getPayloadSenderPublicKey",(s,i=Bu)=>{const o=ZC({encoded:s,encoding:i});return o.senderPublicKey?Ya(o.senderPublicKey,ra):void 0}),this.core=e,this.logger=Mo(n,this.name),this.keychain=r||new bet(this.core,this.logger)}get context(){return sc(this.logger)}async setPrivateKey(e,n){return await this.keychain.set(e,n),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(wJ)}catch{e=O7(),await this.keychain.set(wJ,e)}return met(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=gt("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Cet=Object.defineProperty,_et=Object.defineProperties,Aet=Object.getOwnPropertyDescriptors,IJ=Object.getOwnPropertySymbols,Iet=Object.prototype.hasOwnProperty,Tet=Object.prototype.propertyIsEnumerable,j7=(t,e,n)=>e in t?Cet(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Net=(t,e)=>{for(var n in e||(e={}))Iet.call(e,n)&&j7(t,n,e[n]);if(IJ)for(var n of IJ(e))Tet.call(e,n)&&j7(t,n,e[n]);return t},Pet=(t,e)=>_et(t,Aet(e)),bc=(t,e,n)=>j7(t,typeof e!="symbol"?e+"":e,n);class ket extends pje{constructor(e,n){super(e,n),this.logger=e,this.core=n,bc(this,"messages",new Map),bc(this,"messagesWithoutClientAck",new Map),bc(this,"name",bQe),bc(this,"version",vQe),bc(this,"initialized",!1),bc(this,"storagePrefix",ff),bc(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),bc(this,"set",async(r,s,i)=>{this.isInitialized();const o=jd(s);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(r,a),i===GI.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,Pet(Net({},c),{[o]:s}))}return await this.persist(),o}),bc(this,"get",r=>{this.isInitialized();let s=this.messages.get(r);return typeof s>"u"&&(s={}),s}),bc(this,"getWithoutAck",r=>{this.isInitialized();const s={};for(const i of r){const o=this.messagesWithoutClientAck.get(i)||{};s[i]=Object.values(o)}return s}),bc(this,"has",(r,s)=>{this.isInitialized();const i=this.get(r),o=jd(s);return typeof i[o]<"u"}),bc(this,"ack",async(r,s)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(r);if(typeof i>"u")return;const o=jd(s);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,i),await this.persist()}),bc(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=Mo(e,this.name),this.core=n}get context(){return sc(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,E7(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,E7(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?C7(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?C7(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=gt("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ret=Object.defineProperty,Oet=Object.defineProperties,$et=Object.getOwnPropertyDescriptors,TJ=Object.getOwnPropertySymbols,Det=Object.prototype.hasOwnProperty,Met=Object.prototype.propertyIsEnumerable,z7=(t,e,n)=>e in t?Ret(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$A=(t,e)=>{for(var n in e||(e={}))Det.call(e,n)&&z7(t,n,e[n]);if(TJ)for(var n of TJ(e))Met.call(e,n)&&z7(t,n,e[n]);return t},tD=(t,e)=>Oet(t,$et(e)),yu=(t,e,n)=>z7(t,typeof e!="symbol"?e+"":e,n);class Let extends gje{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,yu(this,"events",new Ql.EventEmitter),yu(this,"name",xQe),yu(this,"queue",new Map),yu(this,"publishTimeout",yt.toMiliseconds(yt.ONE_MINUTE)),yu(this,"initialPublishTimeout",yt.toMiliseconds(yt.ONE_SECOND*15)),yu(this,"needsTransportRestart",!1),yu(this,"publish",async(r,s,i)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:s,opts:i}});const a=i?.ttl||bJ,c=PT(i),l=i?.prompt||!1,u=i?.tag||0,d=i?.id||Sm().toString(),f={topic:r,message:s,opts:{ttl:a,relay:c,prompt:l,tag:u,id:d,attestation:i?.attestation,tvf:i?.tvf}},p=`Failed to publish payload, please try again. id:${d} tag:${u}`;try{const m=new Promise(async y=>{const b=({id:x})=>{f.opts.id===x&&(this.removeRequestFromQueue(x),this.relayer.events.removeListener(yi.publish,b),y(f))};this.relayer.events.on(yi.publish,b);const v=Ng(new Promise((x,E)=>{this.rpcPublish({topic:r,message:s,ttl:a,prompt:l,tag:u,id:d,attestation:i?.attestation,tvf:i?.tvf}).then(x).catch(A=>{this.logger.warn(A,A?.message),E(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await v,this.events.removeListener(yi.publish,b)}catch(x){this.queue.set(d,tD($A({},f),{attempt:1})),this.logger.warn(x,x?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:r,message:s,opts:i}}),await Ng(m,this.publishTimeout,p)}catch(m){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(m),(o=i?.internal)!=null&&o.throwOnFailedPublish)throw m}finally{this.queue.delete(d)}}),yu(this,"on",(r,s)=>{this.events.on(r,s)}),yu(this,"once",(r,s)=>{this.events.once(r,s)}),yu(this,"off",(r,s)=>{this.events.off(r,s)}),yu(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.relayer=e,this.logger=Mo(n,this.name),this.registerEventListeners()}get context(){return sc(this.logger)}async rpcPublish(e){var n,r,s,i;const{topic:o,message:a,ttl:c=bJ,prompt:l,tag:u,id:d,attestation:f,tvf:p}=e,m={method:V2(PT().protocol).publish,params:$A({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:f},p),id:d};Co((n=m.params)==null?void 0:n.prompt)&&((r=m.params)==null||delete r.prompt),Co((s=m.params)==null?void 0:s.tag)&&((i=m.params)==null||delete i.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:m});const y=await this.relayer.request(m);return this.relayer.events.emit(yi.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,n)=>{const r=e.attempt+1;this.queue.set(n,tD($A({},e),{attempt:r}));const{topic:s,message:i,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${r}`),await this.rpcPublish(tD($A({},e),{topic:s,message:i,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(sw.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(yi.connection_stalled);return}this.checkQueue()}),this.relayer.on(yi.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var Bet=Object.defineProperty,Uet=(t,e,n)=>e in t?Bet(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Qw=(t,e,n)=>Uet(t,typeof e!="symbol"?e+"":e,n);class Fet{constructor(){Qw(this,"map",new Map),Qw(this,"set",(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])}),Qw(this,"get",e=>this.map.get(e)||[]),Qw(this,"exists",(e,n)=>this.get(e).includes(n)),Qw(this,"delete",(e,n)=>{if(typeof n>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,n))return;const s=r.filter(i=>i!==n);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),Qw(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var jet=Object.defineProperty,zet=Object.defineProperties,Wet=Object.getOwnPropertyDescriptors,NJ=Object.getOwnPropertySymbols,Vet=Object.prototype.hasOwnProperty,Het=Object.prototype.propertyIsEnumerable,W7=(t,e,n)=>e in t?jet(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,g2=(t,e)=>{for(var n in e||(e={}))Vet.call(e,n)&&W7(t,n,e[n]);if(NJ)for(var n of NJ(e))Het.call(e,n)&&W7(t,n,e[n]);return t},nD=(t,e)=>zet(t,Wet(e)),Hr=(t,e,n)=>W7(t,typeof e!="symbol"?e+"":e,n);class qet extends wje{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,Hr(this,"subscriptions",new Map),Hr(this,"topicMap",new Fet),Hr(this,"events",new Ql.EventEmitter),Hr(this,"name",TQe),Hr(this,"version",NQe),Hr(this,"pending",new Map),Hr(this,"cached",[]),Hr(this,"initialized",!1),Hr(this,"storagePrefix",ff),Hr(this,"subscribeTimeout",yt.toMiliseconds(yt.ONE_MINUTE)),Hr(this,"initialSubscribeTimeout",yt.toMiliseconds(yt.ONE_SECOND*15)),Hr(this,"clientId"),Hr(this,"batchSubscribeTopicsLimit",500),Hr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Hr(this,"subscribe",async(r,s)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}});try{const i=PT(s),o={topic:r,relay:i,transportType:s?.transportType};this.pending.set(r,o);const a=await this.rpcSubscribe(r,i,s);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}})),a}catch(i){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(i),i}}),Hr(this,"unsubscribe",async(r,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(r,s.id,s):await this.unsubscribeByTopic(r,s)}),Hr(this,"isSubscribed",r=>new Promise(s=>{s(this.topicMap.topics.includes(r))})),Hr(this,"isKnownTopic",r=>new Promise(s=>{s(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(i=>i.topic===r))})),Hr(this,"on",(r,s)=>{this.events.on(r,s)}),Hr(this,"once",(r,s)=>{this.events.once(r,s)}),Hr(this,"off",(r,s)=>{this.events.off(r,s)}),Hr(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),Hr(this,"start",async()=>{await this.onConnect()}),Hr(this,"stop",async()=>{await this.onDisconnect()}),Hr(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Hr(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(s=>{r.push(s)}),await this.batchSubscribe(r)}),Hr(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(sw.pulse,async()=>{await this.checkPending()}),this.events.on(_c.created,async r=>{const s=_c.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()}),this.events.on(_c.deleted,async r=>{const s=_c.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()})}),this.relayer=e,this.logger=Mo(n,this.name),this.clientId=""}get context(){return sc(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,n){let r=!1;try{r=this.getSubscription(e).topic===n}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,n){const r=this.topicMap.get(e);await Promise.all(r.map(async s=>await this.unsubscribeById(e,s,n)))}async unsubscribeById(e,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}});try{const s=PT(r);await this.restartToComplete({topic:e,id:n,relay:s}),await this.rpcUnsubscribe(e,n,s);const i=ds("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,n,r){var s;(!r||r?.transportType===is.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const i={method:V2(n.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});const o=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(r?.transportType===is.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(i).catch(u=>this.logger.warn(u))},yt.toMiliseconds(yt.ONE_SECOND)),a;const c=new Promise(async u=>{const d=f=>{f.topic===e&&(this.events.removeListener(_c.created,d),u(f.id))};this.events.on(_c.created,d);try{const f=await Ng(new Promise((p,m)=>{this.relayer.request(i).catch(y=>{this.logger.warn(y,y?.message),m(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(_c.created,d),u(f)}catch{}}),l=await Ng(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(yi.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const n=e[0].relay,r={method:V2(n.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await Ng(new Promise(s=>{this.relayer.request(r).catch(i=>this.logger.warn(i)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(yi.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:V2(n.protocol).batchFetchMessages,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let s;try{s=await await Ng(new Promise((i,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(i)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(yi.connection_stalled)}return s}rpcUnsubscribe(e,n,r){const s={method:V2(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,n){this.setSubscription(e,nD(g2({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,g2({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(e,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,e)&&this.deleteSubscription(n,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:n}),this.addSubscription(e,n)}addSubscription(e,n){this.subscriptions.set(e,g2({},n)),this.topicMap.set(n.topic,e),this.events.emit(_c.created,n)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const n=this.subscriptions.get(e);if(!n){const{message:r}=gt("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}deleteSubscription(e,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:n});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(_c.deleted,nD(g2({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(_c.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r"u"||!e.length)return;if(this.subscriptions.size){const{message:n}=gt("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}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 n=>nD(g2({},n),{id:await this.getSubscriptionId(n.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const n=await this.rpcBatchFetchMessages(e);n&&n.messages&&(await $Ke(yt.toMiliseconds(yt.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=gt("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 jd(e+await this.getClientId())}}var Ket=Object.defineProperty,PJ=Object.getOwnPropertySymbols,Get=Object.prototype.hasOwnProperty,Zet=Object.prototype.propertyIsEnumerable,V7=(t,e,n)=>e in t?Ket(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,kJ=(t,e)=>{for(var n in e||(e={}))Get.call(e,n)&&V7(t,n,e[n]);if(PJ)for(var n of PJ(e))Zet.call(e,n)&&V7(t,n,e[n]);return t},hr=(t,e,n)=>V7(t,typeof e!="symbol"?e+"":e,n);class Yet extends mje{constructor(e){super(e),hr(this,"protocol","wc"),hr(this,"version",2),hr(this,"core"),hr(this,"logger"),hr(this,"events",new Ql.EventEmitter),hr(this,"provider"),hr(this,"messages"),hr(this,"subscriber"),hr(this,"publisher"),hr(this,"name",CQe),hr(this,"transportExplicitlyClosed",!1),hr(this,"initialized",!1),hr(this,"connectionAttemptInProgress",!1),hr(this,"relayUrl"),hr(this,"projectId"),hr(this,"packageName"),hr(this,"bundleId"),hr(this,"hasExperiencedNetworkDisruption",!1),hr(this,"pingTimeout"),hr(this,"heartBeatTimeout",yt.toMiliseconds(yt.THIRTY_SECONDS+yt.FIVE_SECONDS)),hr(this,"reconnectTimeout"),hr(this,"connectPromise"),hr(this,"reconnectInProgress",!1),hr(this,"requestsInFlight",[]),hr(this,"connectTimeout",yt.toMiliseconds(yt.ONE_SECOND*15)),hr(this,"request",async n=>{var r,s;this.logger.debug("Publishing Request Payload");const i=n.id||Sm().toString();await this.toEstablishConnection();try{this.logger.trace({id:i,method:n.method,topic:(r=n.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${i}:${((s=n.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${i}`),o}}),hr(this,"resetPingTimeout",()=>{AT()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,r,s,i;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(i=(s=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null?void 0:s.terminate)==null||i.call(s)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),hr(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),hr(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(yi.connect)}),hr(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),hr(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(yi.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),hr(this,"registerProviderListeners",()=>{this.provider.on(ul.payload,this.onPayloadHandler),this.provider.on(ul.connect,this.onConnectHandler),this.provider.on(ul.disconnect,this.onDisconnectHandler),this.provider.on(ul.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Mo(e.logger,this.name):e3(sx({level:e.logger||EQe})),this.messages=new ket(this.logger,e.core),this.subscriber=new qet(this,this.logger),this.publisher=new Let(this,this.logger),this.relayUrl=e?.relayUrl||Npe,this.projectId=e.projectId,wKe()?this.packageName=vQ():bKe()&&(this.bundleId=vQ()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return sc(this.logger)}get connected(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,n,r){this.isInitialized(),await this.publisher.publish(e,n,r),await this.recordMessageEvent({topic:e,message:n,publishedAt:Date.now(),transportType:is.relay},GI.outbound)}async subscribe(e,n){var r,s,i;this.isInitialized(),(!(n!=null&&n.transportType)||n?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=n?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(s=n?.internal)==null?void 0:s.throwOnFailedPublish;let a=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(_c.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(_c.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,kJ({internal:{throwOnFailedPublish:o}},n)).catch(f=>{o&&d(f)})||a,u()})]),a}async unsubscribe(e,n){this.isInitialized(),await this.subscriber.unsubscribe(e,n)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Ng(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.info("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(n,r)=>{await this.connect(e).then(n).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await uJ())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 n=e.sort((r,s)=>r.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+s?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(e,n){const{topic:r}=e;if(!n.sessionExists){const s=ei(yt.FIVE_MINUTES),i={topic:r,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,i)}this.events.emit(yi.message,e),await this.recordMessageEvent(e,GI.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let n=1;for(;n<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise(async(r,s)=>{const i=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(ul.disconnect,i),await Ng(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(ul.disconnect,i),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(ul.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(ul.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const s=r;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,yt.toMiliseconds(n*1))),n++}}startPingTimeout(){var e,n,r,s,i;if(AT())try{(n=(e=this.provider)==null?void 0:e.connection)!=null&&n.socket&&((i=(s=(r=this.provider)==null?void 0:r.connection)==null?void 0:s.socket)==null||i.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 Jl(new dQe(_Ke({sdkVersion:B7,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,n){const{topic:r,message:s}=e;await this.messages.set(r,s,n)}async shouldIgnoreMessageEvent(e){const{topic:n,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(n))return this.logger.warn(`Ignoring message for unknown topic ${n}`),!0;const s=this.messages.has(n,r);return s&&this.logger.warn(`Ignoring duplicate message: ${r}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Hz(e)){if(!e.method.endsWith(_Qe))return;const n=e.params,{topic:r,message:s,publishedAt:i,attestation:o}=n.data,a={topic:r,message:s,publishedAt:i,transportType:is.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(kJ({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else uk(e)&&this.events.emit(yi.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,GI.inbound),this.events.emit(yi.message,e))}async acknowledgePayload(e){const n=ck(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(ul.payload,this.onPayloadHandler),this.provider.off(ul.connect,this.onConnectHandler),this.provider.off(ul.disconnect,this.onDisconnectHandler),this.provider.off(ul.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await uJ();fXe(async n=>{e!==n&&(e=n,n?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(sw.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&gXe())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(yi.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},yt.toMiliseconds(SQe)))))}isInitialized(){if(!this.initialized){const{message:e}=gt("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 Xet(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function RJ(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function OJ(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const Qet="[object RegExp]",Jet="[object String]",ett="[object Number]",ttt="[object Boolean]",$J="[object Arguments]",ntt="[object Symbol]",rtt="[object Date]",stt="[object Map]",itt="[object Set]",ott="[object Array]",att="[object Function]",ctt="[object ArrayBuffer]",rD="[object Object]",ltt="[object Error]",utt="[object DataView]",dtt="[object Uint8Array]",ftt="[object Uint8ClampedArray]",htt="[object Uint16Array]",ptt="[object Uint32Array]",gtt="[object BigUint64Array]",mtt="[object Int8Array]",ytt="[object Int16Array]",wtt="[object Int32Array]",btt="[object BigInt64Array]",vtt="[object Float32Array]",xtt="[object Float64Array]";function Ett(){}function DJ(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function Ctt(t,e,n){return H2(t,e,void 0,void 0,void 0,void 0,n)}function H2(t,e,n,r,s,i,o){const a=o(t,e,n,r,s,i);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return NE(t,e,i,o)}return NE(t,e,i,o)}function NE(t,e,n,r){if(Object.is(t,e))return!0;let s=OJ(t),i=OJ(e);if(s===$J&&(s=rD),i===$J&&(i=rD),s!==i)return!1;switch(s){case Jet:return t.toString()===e.toString();case ett:{const c=t.valueOf(),l=e.valueOf();return Xet(c,l)}case ttt:case rtt:case ntt:return Object.is(t.valueOf(),e.valueOf());case Qet:return t.source===e.source&&t.flags===e.flags;case att:return t===e}n=n??new Map;const o=n.get(t),a=n.get(e);if(o!=null&&a!=null)return o===e;n.set(t,e),n.set(e,t);try{switch(s){case stt:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!H2(l,e.get(c),c,t,e,n,r))return!1;return!0}case itt:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;uH2(d,p,void 0,t,e,n,r));if(f===-1)return!1;l.splice(f,1)}return!0}case ott:case dtt:case ftt:case htt:case ptt:case gtt:case mtt:case ytt:case wtt:case btt:case vtt:case xtt:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;ce in t?Stt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,LJ=(t,e)=>{for(var n in e||(e={}))Att.call(e,n)&&H7(t,n,e[n]);if(MJ)for(var n of MJ(e))Itt.call(e,n)&&H7(t,n,e[n]);return t},Ea=(t,e,n)=>H7(t,typeof e!="symbol"?e+"":e,n);class aw extends yje{constructor(e,n,r,s=ff,i=void 0){super(e,n,r,s),this.core=e,this.logger=n,this.name=r,Ea(this,"map",new Map),Ea(this,"version",AQe),Ea(this,"cached",[]),Ea(this,"initialized",!1),Ea(this,"getKey"),Ea(this,"storagePrefix",ff),Ea(this,"recentlyDeleted",[]),Ea(this,"recentlyDeletedLimit",200),Ea(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Co(o)?this.map.set(this.getKey(o),o):WYe(o)?this.map.set(o.id,o):VYe(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ea(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())}),Ea(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ea(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>_tt(a[c],o[c]))):this.values)),Ea(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=LJ(LJ({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ea(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=Mo(n,this.name),this.storagePrefix=s,this.getKey=i}get context(){return sc(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 n=this.map.get(e);if(!n){if(this.recentlyDeleted.includes(e)){const{message:s}=gt("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:r}=gt("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}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:n}=gt("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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}=gt("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ttt=Object.defineProperty,Ntt=(t,e,n)=>e in t?Ttt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Xn=(t,e,n)=>Ntt(t,typeof e!="symbol"?e+"":e,n);class Ptt{constructor(e,n){this.core=e,this.logger=n,Xn(this,"name",PQe),Xn(this,"version",kQe),Xn(this,"events",new hz),Xn(this,"pairings"),Xn(this,"initialized",!1),Xn(this,"storagePrefix",ff),Xn(this,"ignoredPayloadTypes",[Nh]),Xn(this,"registeredMethods",[]),Xn(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Xn(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),Xn(this,"create",async r=>{this.isInitialized();const s=O7(),i=await this.core.crypto.setSymKey(s),o=ei(yt.FIVE_MINUTES),a={protocol:Tpe},c={topic:i,expiry:o,relay:a,active:!1,methods:r?.methods},l=tJ({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:s,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(lm.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:r?.transportType}),{topic:i,uri:l}}),Xn(this,"pair",async r=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[Od.pairing_started]}});this.isValidPair(r,s);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=eJ(r.uri);s.props.properties.topic=i,s.addTrace(Od.pairing_uri_validation_success),s.addTrace(Od.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(i)){if(u=this.pairings.get(i),s.addTrace(Od.existing_pairing),u.active)throw s.setError(ih.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);s.addTrace(Od.pairing_not_expired)}const d=c||ei(yt.FIVE_MINUTES),f={topic:i,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(i,d),await this.pairings.set(i,f),s.addTrace(Od.store_new_pairing),r.activatePairing&&await this.activate({topic:i}),this.events.emit(lm.create,f),s.addTrace(Od.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),s.addTrace(Od.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(ih.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(p){throw s.setError(ih.subscribe_pairing_topic_failure),p}return s.addTrace(Od.subscribe_pairing_topic_success),f}),Xn(this,"activate",async({topic:r})=>{this.isInitialized();const s=ei(yt.FIVE_MINUTES);this.core.expirer.set(r,s),await this.pairings.update(r,{active:!0,expiry:s})}),Xn(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=r;if(this.pairings.keys.includes(s)){const i=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=am();this.events.once(Tr("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}}),Xn(this,"updateExpiry",async({topic:r,expiry:s})=>{this.isInitialized(),await this.pairings.update(r,{expiry:s})}),Xn(this,"updateMetadata",async({topic:r,metadata:s})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:s})}),Xn(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Xn(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:s}=r;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",ds("USER_DISCONNECTED")),await this.deletePairing(s))}),Xn(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:s,relay:i,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(s);return tJ({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:i,expiryTimestamp:o,methods:a})}),Xn(this,"sendRequest",async(r,s,i)=>{const o=Pg(s,i),a=await this.core.crypto.encode(r,o),c=h2[s].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),Xn(this,"sendResult",async(r,s,i)=>{const o=ck(r,i),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,l=h2[c].res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),Xn(this,"sendError",async(r,s,i)=>{const o=lk(r,i),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,l=h2[c]?h2[c].res:h2.unregistered_method.res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),Xn(this,"deletePairing",async(r,s)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,ds("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),s?Promise.resolve():this.core.expirer.del(r)])}),Xn(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(s=>dg(s.expiry));await Promise.all(r.map(s=>this.deletePairing(s.topic)))}),Xn(this,"onRelayEventRequest",async r=>{const{topic:s,payload:i}=r;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,i);default:return await this.onUnknownRpcMethodRequest(s,i)}}),Xn(this,"onRelayEventResponse",async r=>{const{topic:s,payload:i}=r,o=(await this.core.history.get(s,i.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,i);default:return this.onUnknownRpcMethodResponse(o)}}),Xn(this,"onPairingPingRequest",async(r,s)=>{const{id:i}=s;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.events.emit(lm.ping,{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.logger.error(o)}}),Xn(this,"onPairingPingResponse",(r,s)=>{const{id:i}=s;setTimeout(()=>{Bd(s)?this.events.emit(Tr("pairing_ping",i),{}):yl(s)&&this.events.emit(Tr("pairing_ping",i),{error:s.error})},500)}),Xn(this,"onPairingDeleteRequest",async(r,s)=>{const{id:i}=s;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(lm.delete,{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.logger.error(o)}}),Xn(this,"onUnknownRpcMethodRequest",async(r,s)=>{const{id:i,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=ds("WC_METHOD_UNSUPPORTED",o);await this.sendError(i,r,a),this.logger.error(a)}catch(a){await this.sendError(i,r,a),this.logger.error(a)}}),Xn(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(ds("WC_METHOD_UNSUPPORTED",r))}),Xn(this,"isValidPair",(r,s)=>{var i;if(!Aa(r)){const{message:a}=gt("MISSING_OR_INVALID",`pair() params: ${r}`);throw s.setError(ih.malformed_pairing_uri),new Error(a)}if(!zYe(r.uri)){const{message:a}=gt("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw s.setError(ih.malformed_pairing_uri),new Error(a)}const o=eJ(r?.uri);if(!((i=o?.relay)!=null&&i.protocol)){const{message:a}=gt("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(ih.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=gt("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(ih.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&yt.toMiliseconds(o?.expiryTimestamp){if(!Aa(r)){const{message:i}=gt("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:s}=r;await this.isValidPairingTopic(s)}),Xn(this,"isValidDisconnect",async r=>{if(!Aa(r)){const{message:i}=gt("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:s}=r;await this.isValidPairingTopic(s)}),Xn(this,"isValidPairingTopic",async r=>{if(!js(r,!1)){const{message:s}=gt("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(s)}if(!this.pairings.keys.includes(r)){const{message:s}=gt("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(s)}if(dg(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:s}=gt("EXPIRED",`pairing topic: ${r}`);throw new Error(s)}}),this.core=e,this.logger=Mo(n,this.name),this.pairings=new aw(this.core,this.logger,this.name,this.storagePrefix)}get context(){return sc(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=gt("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(yi.message,async e=>{const{topic:n,message:r,transportType:s}=e;if(this.pairings.keys.includes(n)&&s!==is.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const i=await this.core.crypto.decode(n,r);Hz(i)?(this.core.history.set(n,i),await this.onRelayEventRequest({topic:n,payload:i})):uk(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:n,payload:i}),this.core.history.delete(n,i.id)),await this.core.relayer.messages.ack(n,r)}catch(i){this.logger.error(i)}})}registerExpirerEvents(){this.core.expirer.on(pl.expired,async e=>{const{topic:n}=Ahe(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(lm.expire,{topic:n}))})}}var ktt=Object.defineProperty,Rtt=(t,e,n)=>e in t?ktt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Pi=(t,e,n)=>Rtt(t,typeof e!="symbol"?e+"":e,n);class Ott extends hje{constructor(e,n){super(e,n),this.core=e,this.logger=n,Pi(this,"records",new Map),Pi(this,"events",new Ql.EventEmitter),Pi(this,"name",RQe),Pi(this,"version",OQe),Pi(this,"cached",[]),Pi(this,"initialized",!1),Pi(this,"storagePrefix",ff),Pi(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Pi(this,"set",(r,s,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:s,chainId:i}),this.records.has(s.id))return;const o={id:s.id,topic:r,request:{method:s.method,params:s.params||null},chainId:i,expiry:ei(yt.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(gu.created,o)}),Pi(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const s=await this.getRecord(r.id);typeof s.response>"u"&&(s.response=yl(r)?{error:r.error}:{result:r.result},this.records.set(s.id,s),this.persist(),this.events.emit(gu.updated,s))}),Pi(this,"get",async(r,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:s}),await this.getRecord(s))),Pi(this,"delete",(r,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(i=>{if(i.topic===r){if(typeof s<"u"&&i.id!==s)return;this.records.delete(i.id),this.events.emit(gu.deleted,i)}}),this.persist()}),Pi(this,"exists",async(r,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===r:!1)),Pi(this,"on",(r,s)=>{this.events.on(r,s)}),Pi(this,"once",(r,s)=>{this.events.once(r,s)}),Pi(this,"off",(r,s)=>{this.events.off(r,s)}),Pi(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=Mo(n,this.name)}get context(){return sc(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(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:Pg(n.request.method,n.request.params,n.id),chainId:n.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const n=this.records.get(e);if(!n){const{message:r}=gt("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(gu.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=gt("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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(gu.created,e=>{const n=gu.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(gu.updated,e=>{const n=gu.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(gu.deleted,e=>{const n=gu.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on(sw.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{yt.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(gu.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=gt("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $tt=Object.defineProperty,Dtt=(t,e,n)=>e in t?$tt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,go=(t,e,n)=>Dtt(t,typeof e!="symbol"?e+"":e,n);class Mtt extends bje{constructor(e,n){super(e,n),this.core=e,this.logger=n,go(this,"expirations",new Map),go(this,"events",new Ql.EventEmitter),go(this,"name",$Qe),go(this,"version",DQe),go(this,"cached",[]),go(this,"initialized",!1),go(this,"storagePrefix",ff),go(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),go(this,"has",r=>{try{const s=this.formatTarget(r);return typeof this.getExpiration(s)<"u"}catch{return!1}}),go(this,"set",(r,s)=>{this.isInitialized();const i=this.formatTarget(r),o={target:i,expiry:s};this.expirations.set(i,o),this.checkExpiry(i,o),this.events.emit(pl.created,{target:i,expiration:o})}),go(this,"get",r=>{this.isInitialized();const s=this.formatTarget(r);return this.getExpiration(s)}),go(this,"del",r=>{if(this.isInitialized(),this.has(r)){const s=this.formatTarget(r),i=this.getExpiration(s);this.expirations.delete(s),this.events.emit(pl.deleted,{target:s,expiration:i})}}),go(this,"on",(r,s)=>{this.events.on(r,s)}),go(this,"once",(r,s)=>{this.events.once(r,s)}),go(this,"off",(r,s)=>{this.events.off(r,s)}),go(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=Mo(n,this.name)}get context(){return sc(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 SKe(e);if(typeof e=="number")return AKe(e);const{message:n}=gt("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(n)}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(pl.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=gt("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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 n=this.expirations.get(e);if(!n){const{message:r}=gt("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;yt.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(pl.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(sw.pulse,()=>this.checkExpirations()),this.events.on(pl.created,e=>{const n=pl.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(pl.expired,e=>{const n=pl.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(pl.deleted,e=>{const n=pl.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=gt("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ltt=Object.defineProperty,Btt=(t,e,n)=>e in t?Ltt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Us=(t,e,n)=>Btt(t,typeof e!="symbol"?e+"":e,n);class Utt extends vje{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,Us(this,"name",MQe),Us(this,"abortController"),Us(this,"isDevEnv"),Us(this,"verifyUrlV3",BQe),Us(this,"storagePrefix",ff),Us(this,"version",Ipe),Us(this,"publicKey"),Us(this,"fetchPromise"),Us(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&yt.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt){if(!dx()||this.isDevEnv)return;const i=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${i}&id=${o}&decryptedId=${a}`;try{const l=wy(),u=this.startAbortTimer(yt.ONE_SECOND*5),d=await new Promise((f,p)=>{const m=()=>{window.removeEventListener("message",b),l.body.removeChild(y),p("attestation aborted")};this.abortController.signal.addEventListener("abort",m);const y=l.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",m,{signal:this.abortController.signal});const b=v=>{if(v.data&&typeof v.data=="string")try{const x=JSON.parse(v.data);if(x.type==="verify_attestation"){if(p7(x.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(y),this.abortController.signal.removeEventListener("abort",m),window.removeEventListener("message",b),f(x.attestation===null?"":x.attestation)}}catch(x){this.logger.warn(x)}};l.body.appendChild(y),window.addEventListener("message",b,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),Us(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:i,hash:o,encryptedId:a}=s;if(i===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(i){if(p7(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(s?.verifyUrl);return this.fetchAttestation(o,c)}),Us(this,"fetchAttestation",async(s,i)=>{this.logger.debug(`resolving attestation: ${s} from url: ${i}`);const o=this.startAbortTimer(yt.ONE_SECOND*5),a=await fetch(`${i}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),Us(this,"getVerifyUrl",s=>{let i=s||TE;return UQe.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${TE}`),i=TE),i}),Us(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(yt.FIVE_SECONDS),i=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await i.json()}catch(s){this.logger.warn(s)}}),Us(this,"persistPublicKey",async s=>{this.logger.debug("persisting public key to local storage",s),await this.store.setItem(this.storeKey,s),this.publicKey=s}),Us(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Us(this,"isValidJwtAttestation",async s=>{const i=await this.getPublicKey();try{if(i)return this.validateAttestation(s,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Us(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Us(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async i=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),i(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),Us(this,"validateAttestation",(s,i)=>{const o=xYe(s,i.publicKey),a={hasExpired:yt.toMiliseconds(o.exp)this.abortController.abort(),yt.toMiliseconds(e))}}var Ftt=Object.defineProperty,jtt=(t,e,n)=>e in t?Ftt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,BJ=(t,e,n)=>jtt(t,typeof e!="symbol"?e+"":e,n);class ztt extends xje{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,BJ(this,"context",FQe),BJ(this,"registerDeviceToken",async r=>{const{clientId:s,token:i,notificationType:o,enableEncrypted:a=!1}=r,c=`${jQe}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:i,always_raw:a})})}),this.logger=Mo(n,this.context)}}var Wtt=Object.defineProperty,UJ=Object.getOwnPropertySymbols,Vtt=Object.prototype.hasOwnProperty,Htt=Object.prototype.propertyIsEnumerable,q7=(t,e,n)=>e in t?Wtt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,m2=(t,e)=>{for(var n in e||(e={}))Vtt.call(e,n)&&q7(t,n,e[n]);if(UJ)for(var n of UJ(e))Htt.call(e,n)&&q7(t,n,e[n]);return t},ui=(t,e,n)=>q7(t,typeof e!="symbol"?e+"":e,n);class qtt extends Eje{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,ui(this,"context",WQe),ui(this,"storagePrefix",ff),ui(this,"storageVersion",zQe),ui(this,"events",new Map),ui(this,"shouldPersist",!1),ui(this,"init",async()=>{if(!Pz())try{const s={eventId:EQ(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:_he(this.core.relayer.protocol,this.core.relayer.version,B7)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),ui(this,"createEvent",s=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=s,l=EQ(),u=this.core.projectId||"",d=Date.now(),f=m2({eventId:l,timestamp:d,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,f),this.shouldPersist=!0),f}),ui(this,"getEvent",s=>{const{eventId:i,topic:o}=s;if(i)return this.events.get(i);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return m2(m2({},a),this.setMethods(a.eventId))}),ui(this,"deleteEvent",s=>{const{eventId:i}=s;this.events.delete(i),this.shouldPersist=!0}),ui(this,"setEventListeners",()=>{this.core.heartbeat.on(sw.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{yt.fromMiliseconds(Date.now())-yt.fromMiliseconds(s.timestamp)>VQe&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),ui(this,"setMethods",s=>({addTrace:i=>this.addTrace(s,i),setError:i=>this.setError(s,i)})),ui(this,"addTrace",(s,i)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(i),this.events.set(s,o),this.shouldPersist=!0)}),ui(this,"setError",(s,i)=>{const o=this.events.get(s);o&&(o.props.type=i,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),ui(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),ui(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(i=>{this.events.set(i.eventId,m2(m2({},i),this.setMethods(i.eventId)))})}catch(s){this.logger.warn(s)}}),ui(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[i,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const i of s)this.events.delete(i.eventId),this.shouldPersist=!0}catch(i){this.logger.warn(i)}}),ui(this,"sendEvent",async s=>{const i=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${HQe}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${B7}${i}`,{method:"POST",body:JSON.stringify(s)})}),ui(this,"getAppDomain",()=>Che().url),this.logger=Mo(n,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var Ktt=Object.defineProperty,FJ=Object.getOwnPropertySymbols,Gtt=Object.prototype.hasOwnProperty,Ztt=Object.prototype.propertyIsEnumerable,K7=(t,e,n)=>e in t?Ktt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,jJ=(t,e)=>{for(var n in e||(e={}))Gtt.call(e,n)&&K7(t,n,e[n]);if(FJ)for(var n of FJ(e))Ztt.call(e,n)&&K7(t,n,e[n]);return t},Yr=(t,e,n)=>K7(t,typeof e!="symbol"?e+"":e,n);let Ytt=class zpe extends lje{constructor(e){var n;super(e),Yr(this,"protocol",Ape),Yr(this,"version",Ipe),Yr(this,"name",RT),Yr(this,"relayUrl"),Yr(this,"projectId"),Yr(this,"customStoragePrefix"),Yr(this,"events",new Ql.EventEmitter),Yr(this,"logger"),Yr(this,"heartbeat"),Yr(this,"relayer"),Yr(this,"crypto"),Yr(this,"storage"),Yr(this,"history"),Yr(this,"expirer"),Yr(this,"pairing"),Yr(this,"verify"),Yr(this,"echoClient"),Yr(this,"linkModeSupportedApps"),Yr(this,"eventClient"),Yr(this,"initialized",!1),Yr(this,"logChunkController"),Yr(this,"on",(a,c)=>this.events.on(a,c)),Yr(this,"once",(a,c)=>this.events.once(a,c)),Yr(this,"off",(a,c)=>this.events.off(a,c)),Yr(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Yr(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:is.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(e?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Npe,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=sx({level:typeof e?.logger=="string"&&e.logger?e.logger:hQe.logger,name:RT}),{logger:i,chunkLoggerController:o}=gz({opts:s,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(n=this.logChunkController)!=null&&n.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=Mo(i,this.name),this.heartbeat=new XUe,this.crypto=new Eet(this,this.logger,e?.keychain),this.history=new Ott(this,this.logger),this.expirer=new Mtt(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new OFe(jJ(jJ({},pQe),e?.storageOptions)),this.relayer=new Yet({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Ptt(this,this.logger),this.verify=new Utt(this,this.logger,this.storage),this.echoClient=new ztt(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new qtt(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new zpe(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(IQe,r),n}get context(){return sc(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(vJ,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(vJ)||[],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 n=`_walletConnectCore_${e}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(e){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=e.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&fQe.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const Xtt=Ytt,Wpe="wc",Vpe=2,Hpe="client",qz=`${Wpe}@${Vpe}:${Hpe}:`,sD={name:Hpe,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},zJ="WALLETCONNECT_DEEPLINK_CHOICE",Qtt="proposal",WJ="Proposal expired",Jtt="session",Jw=yt.SEVEN_DAYS,ent="engine",di={wc_sessionPropose:{req:{ttl:yt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:yt.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:yt.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:yt.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:yt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:yt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:yt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:yt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:yt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:yt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:yt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:yt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:yt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:yt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:yt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:yt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:yt.ONE_DAY,prompt:!1,tag:1114},res:{ttl:yt.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:yt.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:yt.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:yt.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:yt.FIVE_MINUTES,prompt:!1,tag:1119}}},iD={min:yt.FIVE_MINUTES,max:yt.SEVEN_DAYS},Nd={idle:"IDLE",active:"ACTIVE"},tnt={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},nnt="request",rnt=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],snt="wc",int="auth",ont="authKeys",ant="pairingTopics",cnt="requests",fk=`${snt}@${1.5}:${int}:`,ZI=`${fk}:PUB_KEY`;var lnt=Object.defineProperty,unt=Object.defineProperties,dnt=Object.getOwnPropertyDescriptors,VJ=Object.getOwnPropertySymbols,fnt=Object.prototype.hasOwnProperty,hnt=Object.prototype.propertyIsEnumerable,G7=(t,e,n)=>e in t?lnt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,rs=(t,e)=>{for(var n in e||(e={}))fnt.call(e,n)&&G7(t,n,e[n]);if(VJ)for(var n of VJ(e))hnt.call(e,n)&&G7(t,n,e[n]);return t},Ca=(t,e)=>unt(t,dnt(e)),st=(t,e,n)=>G7(t,typeof e!="symbol"?e+"":e,n);class pnt extends Aje{constructor(e){super(e),st(this,"name",ent),st(this,"events",new hz),st(this,"initialized",!1),st(this,"requestQueue",{state:Nd.idle,queue:[]}),st(this,"sessionRequestQueue",{state:Nd.idle,queue:[]}),st(this,"emittedSessionRequests",new DKe({limit:500})),st(this,"requestQueueDelay",yt.ONE_SECOND),st(this,"expectedPairingMethodMap",new Map),st(this,"recentlyDeletedMap",new Map),st(this,"recentlyDeletedLimit",200),st(this,"relayMessageCache",[]),st(this,"pendingSessions",new Map),st(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(di)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},yt.toMiliseconds(this.requestQueueDelay)))}),st(this,"connect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=Ca(rs({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=LYe(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=r;let u=s,d,f=!1;try{if(u){const k=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),f=k.active}}catch(k){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),k}if(!u||!f){const{topic:k,uri:B}=await this.client.core.pairing.create();u=k,d=B}if(!u){const{message:k}=gt("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(k)}const p=await this.client.core.crypto.generateKeyPair(),m=di.wc_sessionPropose.req.ttl||yt.FIVE_MINUTES,y=ei(m),b=Ca(rs(rs({requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:Tpe}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Ld()}),v=Tr("session_connect",b.id),{reject:x,resolve:E,done:A}=am(m,WJ),_=({id:k})=>{k===b.id&&(this.client.events.off("proposal_expire",_),this.pendingSessions.delete(b.id),this.events.emit(v,{error:{message:WJ,code:0}}))};return this.client.events.on("proposal_expire",_),this.events.once(v,({error:k,session:B})=>{this.client.events.off("proposal_expire",_),k?x(k):B&&E(B)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:b,throwOnFailedPublish:!0,clientRpcId:b.id}),await this.setProposal(b.id,b),{uri:d,approval:A}}),st(this,"pair",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(n)}catch(r){throw this.client.logger.error("pair() failed"),r}}),st(this,"approve",async n=>{var r,s,i;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[mu.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(S){throw o.setError(Q0.no_internet_connection),S}try{await this.isValidProposalId(n?.id)}catch(S){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(Q0.proposal_not_found),S}try{await this.isValidApprove(n)}catch(S){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Q0.session_approve_namespace_validation_failure),S}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:f}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:m,proposer:y,requiredNamespaces:b,optionalNamespaces:v}=p;let x=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:m});x||(x=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:mu.session_approve_started,properties:{topic:m,trace:[mu.session_approve_started,mu.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),A=y.publicKey,_=await this.client.core.crypto.generateSharedKey(E,A),k=rs(rs(rs({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:E,metadata:this.client.metadata},expiry:ei(Jw)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),f&&{sessionConfig:f}),B=is.relay;x.addTrace(mu.subscribing_session_topic);try{await this.client.core.relayer.subscribe(_,{transportType:B})}catch(S){throw x.setError(Q0.subscribe_session_topic_failure),S}x.addTrace(mu.subscribe_session_topic_success);const W=Ca(rs({},k),{topic:_,requiredNamespaces:b,optionalNamespaces:v,pairingTopic:m,acknowledged:!1,self:k.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:E,transportType:is.relay});await this.client.session.set(_,W),x.addTrace(mu.store_session);try{x.addTrace(mu.publishing_session_settle),await this.sendRequest({topic:_,method:"wc_sessionSettle",params:k,throwOnFailedPublish:!0}).catch(S=>{throw x?.setError(Q0.session_settle_publish_failure),S}),x.addTrace(mu.session_settle_publish_success),x.addTrace(mu.publishing_session_approve),await this.sendResult({id:a,topic:m,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(S=>{throw x?.setError(Q0.session_approve_publish_failure),S}),x.addTrace(mu.session_approve_publish_success)}catch(S){throw this.client.logger.error(S),this.client.session.delete(_,ds("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(_),S}return this.client.core.eventClient.deleteEvent({eventId:x.eventId}),await this.client.core.pairing.updateMetadata({topic:m,metadata:y.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:m}),await this.setExpiry(_,ei(Jw)),{topic:_,acknowledged:()=>Promise.resolve(this.client.session.get(_))}}),st(this,"reject",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(n)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:s}=n;let i;try{i=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}i&&await this.sendError({id:r,topic:i,error:s,rpcOpts:di.wc_sessionPropose.reject}),await this.deleteProposal(r)}),st(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:r,namespaces:s}=n,{done:i,resolve:o,reject:a}=am(),c=Ld(),l=Sm().toString(),u=this.client.session.get(r).namespaces;return this.events.once(Tr("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(r,{namespaces:s}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(r,{namespaces:u}),a(d)}),{acknowledged:i}}),st(this,"extend",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(n)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=n,s=Ld(),{done:i,resolve:o,reject:a}=am();return this.events.once(Tr("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,ei(Jw)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}}),st(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:r,request:s,topic:i,expiry:o=di.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(i);a?.transportType===is.relay&&await this.confirmOnlineStateOrThrow();const c=Ld(),l=Sm().toString(),{done:u,resolve:d,reject:f}=am(o,"Request expired. Please try again.");this.events.once(Tr("session_request",c),({error:b,result:v})=>{b?f(b):d(v)});const p="wc_sessionRequest",m=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(m)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:{request:Ca(rs({},s),{expiryTimestamp:ei(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:m}).catch(b=>f(b)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:r,id:c}),await u();const y={request:Ca(rs({},s),{expiryTimestamp:ei(o)}),chainId:r};return await Promise.all([new Promise(async b=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:y,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,y)}).catch(v=>f(v)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:r,id:c}),b()}),new Promise(async b=>{var v;if(!((v=a.sessionConfig)!=null&&v.disableDeepLink)){const x=await PKe(this.client.core.storage,zJ);await IKe({id:c,topic:i,wcDeepLink:x})}b()}),u()]).then(b=>b[2])}),st(this,"respond",async n=>{this.isInitialized(),await this.isValidRespond(n);const{topic:r,response:s}=n,{id:i}=s,o=this.client.session.get(r);o.transportType===is.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Bd(s)?await this.sendResult({id:i,topic:r,result:s.result,throwOnFailedPublish:!0,appLink:a}):yl(s)&&await this.sendError({id:i,topic:r,error:s.error,appLink:a}),this.cleanupAfterResponse(n)}),st(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:r}=n;if(this.client.session.keys.includes(r)){const s=Ld(),i=Sm().toString(),{done:o,resolve:a,reject:c}=am();this.events.once(Tr("session_ping",s),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:i}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),st(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:s,chainId:i}=n,o=Sm().toString(),a=Ld();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),st(this,"disconnect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(n);const{topic:r}=n;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:ds("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:s}=gt("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(s)}}),st(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>FYe(r,n)))),st(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),st(this,"authenticate",async(n,r)=>{var s;this.isInitialized(),this.isValidAuthenticate(n);const i=r&&this.client.core.linkModeSupportedApps.includes(r)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=i?is.link_mode:is.relay;o===is.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:f,exp:p,nbf:m,methods:y=[],expiry:b}=n,v=[...n.resources||[]],{topic:x,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:x,uri:E}});const A=await this.client.core.crypto.generateKeyPair(),_=KI(A);if(await Promise.all([this.client.auth.authKeys.set(ZI,{responseTopic:_,publicKey:A}),this.client.auth.pairingTopics.set(_,{topic:_,pairingTopic:x})]),await this.client.core.relayer.subscribe(_,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${x}`),y.length>0){const{namespace:P}=dv(a[0]);let H=qGe(P,"request",y);qI(v)&&(H=GGe(H,v.pop())),v.push(H)}const k=b&&b>di.wc_sessionAuthenticate.req.ttl?b:di.wc_sessionAuthenticate.req.ttl,B={authPayload:{type:f??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:p,nbf:m,resources:v},requester:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:ei(k)},W={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},S={requiredNamespaces:{},optionalNamespaces:W,relays:[{protocol:"irn"}],pairingTopic:x,proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:ei(di.wc_sessionPropose.req.ttl),id:Ld()},{done:$,resolve:R,reject:M}=am(k,"Request expired"),j=Ld(),z=Tr("session_connect",S.id),N=Tr("session_request",j),T=async({error:P,session:H})=>{this.events.off(N,U),P?M(P):H&&R({session:H})},U=async P=>{var H,Y,re;if(await this.deletePendingAuthRequest(j,{message:"fulfilled",code:0}),P.error){const je=ds("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===je.code?void 0:(this.events.off(z,T),M(P.error.message))}await this.deleteProposal(S.id),this.events.off(z,T);const{cacaos:de,responder:fe}=P.result,ve=[],Ee=[];for(const je of de){await OQ({cacao:je,projectId:this.client.core.projectId})||(this.client.logger.error(je,"Signature verification failed"),M(ds("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:V}=je,we=qI(V.resources),Ae=[_7(V.iss)],Ie=IT(V.iss);if(we){const ge=$Q(we),Me=DQ(we);ve.push(...ge),Ae.push(...Me)}for(const ge of Ae)Ee.push(`${ge}:${Ie}`)}const oe=await this.client.core.crypto.generateSharedKey(A,fe.publicKey);let Oe;ve.length>0&&(Oe={topic:oe,acknowledged:!0,self:{publicKey:A,metadata:this.client.metadata},peer:fe,controller:fe.publicKey,expiry:ei(Jw),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:x,namespaces:iJ([...new Set(ve)],[...new Set(Ee)]),transportType:o},await this.client.core.relayer.subscribe(oe,{transportType:o}),await this.client.session.set(oe,Oe),x&&await this.client.core.pairing.updateMetadata({topic:x,metadata:fe.metadata}),Oe=this.client.session.get(oe)),(H=this.client.metadata.redirect)!=null&&H.linkMode&&(Y=fe.metadata.redirect)!=null&&Y.linkMode&&(re=fe.metadata.redirect)!=null&&re.universal&&r&&(this.client.core.addLinkModeSupportedApp(fe.metadata.redirect.universal),this.client.session.update(oe,{transportType:is.link_mode})),R({auths:de,session:Oe})};this.events.once(z,T),this.events.once(N,U);let L;try{if(i){const P=Pg("wc_sessionAuthenticate",B,j);this.client.core.history.set(x,P);const H=await this.client.core.crypto.encode("",P,{type:a3,encoding:vg});L=OA(r,x,H)}else await Promise.all([this.sendRequest({topic:x,method:"wc_sessionAuthenticate",params:B,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:j}),this.sendRequest({topic:x,method:"wc_sessionPropose",params:S,expiry:di.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:S.id})])}catch(P){throw this.events.off(z,T),this.events.off(N,U),P}return await this.setProposal(S.id,S),await this.setAuthRequest(j,{request:Ca(rs({},B),{verifyContext:{}}),pairingTopic:x,transportType:o}),{uri:L??E,response:$}}),st(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:s}=n,i=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[J0.authenticated_session_approve_started]}});try{this.isInitialized()}catch(b){throw i.setError(p2.no_internet_connection),b}const o=this.getPendingAuthRequest(r);if(!o)throw i.setError(p2.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||is.relay;a===is.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=KI(c),d={type:Nh,receiverPublicKey:c,senderPublicKey:l},f=[],p=[];for(const b of s){if(!await OQ({cacao:b,projectId:this.client.core.projectId})){i.setError(p2.invalid_cacao);const _=ds("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:_,encodeOpts:d}),new Error(_.message)}i.addTrace(J0.cacaos_verified);const{p:v}=b,x=qI(v.resources),E=[_7(v.iss)],A=IT(v.iss);if(x){const _=$Q(x),k=DQ(x);f.push(..._),E.push(...k)}for(const _ of E)p.push(`${_}:${A}`)}const m=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(J0.create_authenticated_session_topic);let y;if(f?.length>0){y={topic:m,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ei(Jw),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:iJ([...new Set(f)],[...new Set(p)]),transportType:a},i.addTrace(J0.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(m,{transportType:a})}catch(b){throw i.setError(p2.subscribe_authenticated_session_topic_failure),b}i.addTrace(J0.subscribe_authenticated_session_topic_success),await this.client.session.set(m,y),i.addTrace(J0.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(J0.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(b){throw i.setError(p2.authenticated_session_approve_publish_failure),b}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:y}}),st(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:s}=n,i=this.getPendingAuthRequest(r);if(!i)throw new Error(`Could not find pending auth request with id ${r}`);i.transportType===is.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=KI(o),l={type:Nh,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:s,encodeOpts:l,rpcOpts:di.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),st(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:s}=n;return jhe(r,s)}),st(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const n=this.relayMessageCache.shift();n&&await this.onRelayMessage(n)}catch(n){this.client.logger.error(n)}},50)}),st(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(i=>{var o,a;return((o=i.peerMetadata)==null?void 0:o.url)&&((a=i.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&i.topic&&i.topic!==r.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),st(this,"deleteSession",async n=>{var r;const{topic:s,expirerHasDeleted:i=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,ds("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),i||this.client.core.expirer.del(s),this.client.core.storage.removeItem(zJ).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===s&&this.deletePendingSessionRequest(l.id,ds("USER_DISCONNECTED"))}),s===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=Nd.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),st(this,"deleteProposal",async(n,r)=>{if(r)try{const s=this.client.proposal.get(n);this.client.core.eventClient.getEvent({topic:s.pairingTopic})?.setError(Q0.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,ds("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),st(this,"deletePendingSessionRequest",async(n,r,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),s?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==n),s&&(this.sessionRequestQueue.state=Nd.idle,this.client.events.emit("session_request_expire",{id:n}))}),st(this,"deletePendingAuthRequest",async(n,r,s=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),s?Promise.resolve():this.client.core.expirer.del(n)])}),st(this,"setExpiry",async(n,r)=>{this.client.session.keys.includes(n)&&(this.client.core.expirer.set(n,r),await this.client.session.update(n,{expiry:r}))}),st(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,ei(di.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),st(this,"setAuthRequest",async(n,r)=>{const{request:s,pairingTopic:i,transportType:o=is.relay}=r;this.client.core.expirer.set(n,s.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:n,pairingTopic:i,verifyContext:s.verifyContext,transportType:o})}),st(this,"setPendingSessionRequest",async n=>{const{id:r,topic:s,params:i,verifyContext:o}=n,a=i.request.expiryTimestamp||ei(di.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:s,params:i,verifyContext:o})}),st(this,"sendRequest",async n=>{const{topic:r,method:s,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d}=n,f=Pg(s,i,c);let p;const m=!!u;try{const v=m?vg:Bu;p=await this.client.core.crypto.encode(r,f,{encoding:v})}catch(v){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),v}let y;if(rnt.includes(s)){const v=jd(JSON.stringify(f)),x=jd(p);y=await this.client.core.verify.register({id:x,decryptedId:v})}const b=di[s].req;if(b.attestation=y,o&&(b.ttl=o),a&&(b.id=a),this.client.core.history.set(r,f),m){const v=OA(u,r,p);await global.Linking.openURL(v,this.client.name)}else{const v=di[s].req;o&&(v.ttl=o),a&&(v.id=a),v.tvf=Ca(rs({},d),{correlationId:f.id}),l?(v.internal=Ca(rs({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,v)):this.client.core.relayer.publish(r,p,v).catch(x=>this.client.logger.error(x))}return f.id}),st(this,"sendResult",async n=>{const{id:r,topic:s,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,l=ck(r,i);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const m=d?vg:Bu;u=await this.client.core.crypto.encode(s,l,Ca(rs({},a||{}),{encoding:m}))}catch(m){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),m}let f,p;try{f=await this.client.core.history.get(s,r);const m=f.request;try{p=this.getTVFParams(r,m.params,i)}catch(y){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${y?.message}`)}}catch(m){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${r}) failed`),m}if(d){const m=OA(c,s,u);await global.Linking.openURL(m,this.client.name)}else{const m=f.request.method,y=di[m].res;y.tvf=Ca(rs({},p),{correlationId:r}),o?(y.internal=Ca(rs({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,u,y)):this.client.core.relayer.publish(s,u,y).catch(b=>this.client.logger.error(b))}await this.client.core.history.resolve(l)}),st(this,"sendError",async n=>{const{id:r,topic:s,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=n,l=lk(r,i);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=d?vg:Bu;u=await this.client.core.crypto.encode(s,l,Ca(rs({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),p}let f;try{f=await this.client.core.history.get(s,r)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${s}, ${r}) failed`),p}if(d){const p=OA(c,s,u);await global.Linking.openURL(p,this.client.name)}else{const p=f.request.method,m=a||di[p].res;this.client.core.relayer.publish(s,u,m)}await this.client.core.history.resolve(l)}),st(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(s=>{let i=!1;dg(s.expiry)&&(i=!0),this.client.core.crypto.keychain.has(s.topic)||(i=!0),i&&n.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{dg(s.expiryTimestamp)&&r.push(s.id)}),await Promise.all([...n.map(s=>this.deleteSession({topic:s})),...r.map(s=>this.deleteProposal(s))])}),st(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),st(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),st(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Nd.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=Nd.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=Nd.idle}),st(this,"processRequest",async n=>{const{topic:r,payload:s,attestation:i,transportType:o,encryptedId:a}=n,c=s.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:s,attestation:i,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,s);case"wc_sessionPing":return await this.onSessionPingRequest(r,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:s,attestation:i,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:s,attestation:i,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),st(this,"onRelayEventResponse",async n=>{const{topic:r,payload:s,transportType:i}=n,o=(await this.client.core.history.get(r,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(r,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,s);case"wc_sessionExtend":return this.onSessionExtendResponse(r,s);case"wc_sessionPing":return this.onSessionPingResponse(r,s);case"wc_sessionRequest":return this.onSessionRequestResponse(r,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),st(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:s}=gt("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),st(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:s}=n,i=this.expectedPairingMethodMap.get(r);return!i||i.includes(s)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),st(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:s,attestation:i,encryptedId:o}=n,{params:a,id:c}=s;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(ih.proposal_listener_not_found)),this.isValidConnect(rs({},s.params));const u=a.expiryTimestamp||ei(di.wc_sessionPropose.req.ttl),d=rs({id:c,pairingTopic:r,expiryTimestamp:u,attestation:i,encryptedId:o},a);await this.setProposal(c,d);const f=await this.getVerifyContext({attestationId:i,hash:jd(JSON.stringify(s)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(Od.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:f})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:di.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),st(this,"onSessionProposeResponse",async(n,r,s)=>{const{id:i}=r;if(Bd(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(i,{sessionTopic:u,pairingTopic:n,proposalId:i,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:n})}else if(yl(r)){await this.deleteProposal(i);const o=Tr("session_connect",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),st(this,"onSessionSettleRequest",async(n,r)=>{const{id:s,params:i}=r;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:f}=r.params,p=[...this.pendingSessions.values()].find(b=>b.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const m=this.client.proposal.get(p.proposalId),y=Ca(rs(rs(rs({topic:n,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:m.requiredNamespaces,optionalNamespaces:m.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),f&&{sessionConfig:f}),{transportType:is.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(Tr("session_connect",p.proposalId),{session:y}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:r.id,topic:n,result:!0})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),st(this,"onSessionSettleResponse",async(n,r)=>{const{id:s}=r;Bd(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(Tr("session_approve",s),{})):yl(r)&&(await this.client.session.delete(n,ds("USER_DISCONNECTED")),this.events.emit(Tr("session_approve",s),{error:r.error}))}),st(this,"onSessionUpdateRequest",async(n,r)=>{const{params:s,id:i}=r;try{const o=`${n}_session_update`,a=f2.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:n,error:ds("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(rs({topic:n},s));try{f2.set(o,i),await this.client.session.update(n,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:n,result:!0})}catch(c){throw f2.delete(o),c}this.client.events.emit("session_update",{id:i,topic:n,params:s})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),st(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3){const{id:s}=r,i=Tr("session_update",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);Bd(r)?this.events.emit(Tr("session_update",s),{}):yl(r)&&this.events.emit(Tr("session_update",s),{error:r.error})}),st(this,"onSessionExtendRequest",async(n,r)=>{const{id:s}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,ei(Jw)),await this.sendResult({id:s,topic:n,result:!0}),this.client.events.emit("session_extend",{id:s,topic:n})}catch(i){await this.sendError({id:s,topic:n,error:i}),this.client.logger.error(i)}}),st(this,"onSessionExtendResponse",(n,r)=>{const{id:s}=r,i=Tr("session_extend",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);Bd(r)?this.events.emit(Tr("session_extend",s),{}):yl(r)&&this.events.emit(Tr("session_extend",s),{error:r.error})}),st(this,"onSessionPingRequest",async(n,r)=>{const{id:s}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:s,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:n})}catch(i){await this.sendError({id:s,topic:n,error:i}),this.client.logger.error(i)}}),st(this,"onSessionPingResponse",(n,r)=>{const{id:s}=r,i=Tr("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);Bd(r)?this.events.emit(Tr("session_ping",s),{}):yl(r)&&this.events.emit(Tr("session_ping",s),{error:r.error})},500)}),st(this,"onSessionDeleteRequest",async(n,r)=>{const{id:s}=r;try{this.isValidDisconnect({topic:n,reason:r.params}),Promise.all([new Promise(i=>{this.client.core.relayer.once(yi.publish,async()=>{i(await this.deleteSession({topic:n,id:s}))})}),this.sendResult({id:s,topic:n,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:n,error:ds("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}}),st(this,"onSessionRequest",async n=>{var r,s,i;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=n,{id:d,params:f}=a;try{await this.isValidRequest(rs({topic:o},f));const p=this.client.session.get(o),m=await this.getVerifyContext({attestationId:c,hash:jd(JSON.stringify(Pg("wc_sessionRequest",f,d))),encryptedId:l,metadata:p.peer.metadata,transportType:u}),y={id:d,topic:o,params:f,verifyContext:m};await this.setPendingSessionRequest(y),u===is.link_mode&&(r=p.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((s=p.peer.metadata.redirect)==null?void 0:s.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(p){await this.sendError({id:d,topic:o,error:p}),this.client.logger.error(p)}}),st(this,"onSessionRequestResponse",(n,r)=>{const{id:s}=r,i=Tr("session_request",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);Bd(r)?this.events.emit(Tr("session_request",s),{result:r.result}):yl(r)&&this.events.emit(Tr("session_request",s),{error:r.error})}),st(this,"onSessionEventRequest",async(n,r)=>{const{id:s,params:i}=r;try{const o=`${n}_session_event_${i.event.name}`,a=f2.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(rs({topic:n},i)),this.client.events.emit("session_event",{id:s,topic:n,params:i}),f2.set(o,s)}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),st(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:s}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),Bd(r)?this.events.emit(Tr("session_request",s),{result:r.result}):yl(r)&&this.events.emit(Tr("session_request",s),{error:r.error})}),st(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:s,payload:i,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:l,authPayload:u,expiryTimestamp:d}=i.params,f=await this.getVerifyContext({attestationId:o,hash:jd(JSON.stringify(i)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:s,id:i.id,authPayload:u,verifyContext:f,expiryTimestamp:d};await this.setAuthRequest(i.id,{request:p,pairingTopic:s,transportType:c}),c===is.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:i.params,id:i.id,verifyContext:f})}catch(l){this.client.logger.error(l);const u=i.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(i.params.requester.metadata,c),p={type:Nh,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:i.id,topic:s,error:l,encodeOpts:p,rpcOpts:di.wc_sessionAuthenticate.autoReject,appLink:f})}}),st(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),st(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Nd.idle,this.processSessionRequestQueue()},yt.toMiliseconds(this.requestQueueDelay))}),st(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(i=>i.topic===n&&i.request.method==="wc_sessionRequest").forEach(i=>{const o=i.request.id,a=Tr("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Tr("session_request",i.request.id),{error:r})})}),st(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Nd.active){this.client.logger.info("session request queue is already active.");return}const n=this.sessionRequestQueue.queue[0];if(!n){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(n)}catch(r){this.client.logger.error(r)}}),st(this,"emitSessionRequest",n=>{if(this.emittedSessionRequests.has(n.id)){this.client.logger.warn({id:n.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${n.id}`);return}this.sessionRequestQueue.state=Nd.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),st(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(s=>s.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:Pg("wc_sessionPropose",Ca(rs({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),st(this,"isValidConnect",async n=>{if(!Aa(n)){const{message:l}=gt("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:o,scopedProperties:a,relays:c}=n;if(Co(r)||await this.isValidPairingTopic(r),!QYe(c)){const{message:l}=gt("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!Co(s)&&tf(s)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(s,"requiredNamespaces")}if(!Co(i)&&tf(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),Co(o)||this.validateSessionProps(o,"sessionProperties"),!Co(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(s||{}).concat(Object.keys(i||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),st(this,"validateNamespaces",(n,r)=>{const s=XYe(n,"connect()",r);if(s)throw new Error(s.message)}),st(this,"isValidApprove",async n=>{if(!Aa(n))throw new Error(gt("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:s,relayProtocol:i,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=Q$(s,"approve()");if(l)throw new Error(l.message);const u=cJ(c.requiredNamespaces,s,"approve()");if(u)throw new Error(u.message);if(!js(i,!0)){const{message:d}=gt("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(d)}if(Co(o)||this.validateSessionProps(o,"sessionProperties"),!Co(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(s));if(!Object.keys(a).every(f=>d.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),st(this,"isValidReject",async n=>{if(!Aa(n)){const{message:i}=gt("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(i)}const{id:r,reason:s}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!eXe(s)){const{message:i}=gt("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(i)}}),st(this,"isValidSessionSettleRequest",n=>{if(!Aa(n)){const{message:l}=gt("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(l)}const{relay:r,controller:s,namespaces:i,expiry:o}=n;if(!wpe(r)){const{message:l}=gt("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=HYe(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Q$(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(dg(o)){const{message:l}=gt("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),st(this,"isValidUpdate",async n=>{if(!Aa(n)){const{message:c}=gt("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:s}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const i=this.client.session.get(r),o=Q$(s,"update()");if(o)throw new Error(o.message);const a=cJ(i.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),st(this,"isValidExtend",async n=>{if(!Aa(n)){const{message:s}=gt("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(s)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),st(this,"isValidRequest",async n=>{if(!Aa(n)){const{message:c}=gt("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:s,chainId:i,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!aJ(a,i)){const{message:c}=gt("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!tXe(s)){const{message:c}=gt("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!sXe(a,i,s.method)){const{message:c}=gt("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!cXe(o,iD)){const{message:c}=gt("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${iD.min} and ${iD.max}`);throw new Error(c)}}),st(this,"isValidRespond",async n=>{var r;if(!Aa(n)){const{message:o}=gt("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(o)}const{topic:s,response:i}=n;try{await this.isValidSessionTopic(s)}catch(o){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),o}if(!nXe(i)){const{message:o}=gt("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}}),st(this,"isValidPing",async n=>{if(!Aa(n)){const{message:s}=gt("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),st(this,"isValidEmit",async n=>{if(!Aa(n)){const{message:a}=gt("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:s,chainId:i}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!aJ(o,i)){const{message:a}=gt("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!rXe(s)){const{message:a}=gt("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!iXe(o,i,s.name)){const{message:a}=gt("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),st(this,"isValidDisconnect",async n=>{if(!Aa(n)){const{message:s}=gt("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),st(this,"isValidAuthenticate",n=>{const{chains:r,uri:s,domain:i,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!js(s,!1))throw new Error("uri is required parameter");if(!js(i,!1))throw new Error("domain is required parameter");if(!js(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>dv(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=dv(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),st(this,"getVerifyContext",async n=>{const{attestationId:r,hash:s,encryptedId:i,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||TE,validation:"UNKNOWN",origin:o.url||""}};try{if(a===is.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:s,encryptedId:i,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),st(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((s,i)=>{if(s==null){const{message:o}=gt("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${s} for key ${Object.keys(n)[i]}`);throw new Error(o)}})}),st(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),st(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const i=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=i)break;this.recentlyDeletedMap.delete(o)}}}),st(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:s}=gt("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(s)}}),st(this,"isLinkModeEnabled",(n,r)=>{var s,i,o,a,c,l,u,d,f;return!n||r!==is.link_mode?!1:((i=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:i.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=n?.redirect)==null?void 0:u.universal)!==void 0&&((d=n?.redirect)==null?void 0:d.universal)!==""&&((f=n?.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),st(this,"getAppLinkIfEnabled",(n,r)=>{var s;return this.isLinkModeEnabled(n,r)?(s=n?.redirect)==null?void 0:s.universal:void 0}),st(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=xQ(n,"topic")||"",s=decodeURIComponent(xQ(n,"wc_ev")||""),i=this.client.session.keys.includes(r);i&&this.client.session.update(r,{transportType:is.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:s,sessionExists:i})}),st(this,"registerLinkModeListeners",async()=>{var n;if(Pz()||k0()&&(n=this.client.metadata.redirect)!=null&&n.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await r.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),st(this,"getTVFParams",(n,r,s)=>{var i,o,a;if(!((i=r.request)!=null&&i.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const l=this.extractTxHashesFromResult(r.request,s);c.txHashes=l,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn("Error getting TVF params",l)}return c}),st(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const s=n?.data||((r=n?.[0])==null?void 0:r.data);if(!s.startsWith("0x"))return!1;const i=s.slice(2);return/^[0-9a-fA-F]*$/.test(i)?i.length%2===0:!1}catch{}return!1}),st(this,"extractTxHashesFromResult",(n,r)=>{var s;try{if(!r)return[];const i=n.method,o=tnt[i];if(i==="sui_signTransaction")return[PGe(r.transactionBytes)];if(i==="near_signTransaction")return[NQ(r)];if(i==="near_signTransactions")return r.map(c=>NQ(c));if(i==="xrpl_signTransactionFor"||i==="xrpl_signTransaction")return[(s=r.tx_json)==null?void 0:s.hash];if(i==="polkadot_signTransaction")return[CXe({transaction:n.params.transactionPayload,signature:r.signature})];if(i==="algo_signTxn")return Ph(r)?r.map(c=>PQ(c)):[PQ(r)];if(i==="cosmos_signDirect")return[RGe(r)];if(typeof r=="string")return[r];const a=r[o.key];if(Ph(a))return i==="solana_signAllTransactions"?a.map(c=>NGe(c)):a;if(typeof a=="string")return[a]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,s]of Object.entries(n))for(const i of s)try{await this.onProviderMessageEvent({topic:r,message:i,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${i}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=gt("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(yi.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:n,message:r,attestation:s,transportType:i}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(ZI)?this.client.auth.authKeys.get(ZI):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:i===is.link_mode?vg:Bu});Hz(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:s,transportType:i,encryptedId:jd(r)})):uk(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:i}),this.client.core.history.delete(n,a.id)):await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:i}),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(pl.expired,async e=>{const{topic:n,id:r}=Ahe(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,gt("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,gt("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession({topic:n,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(lm.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(lm.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!js(e,!1)){const{message:n}=gt("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:n}=gt("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(dg(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=gt("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!js(e,!1)){const{message:n}=gt("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(n)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:n}=gt("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(dg(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=gt("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=gt("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(n)}}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(js(e,!1)){const{message:n}=gt("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=gt("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!JYe(e)){const{message:n}=gt("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=gt("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(dg(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=gt("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}}class gnt extends aw{constructor(e,n){super(e,n,Qtt,qz),this.core=e,this.logger=n}}let mnt=class extends aw{constructor(e,n){super(e,n,Jtt,qz),this.core=e,this.logger=n}};class ynt extends aw{constructor(e,n){super(e,n,nnt,qz,r=>r.id),this.core=e,this.logger=n}}class wnt extends aw{constructor(e,n){super(e,n,ont,fk,()=>ZI),this.core=e,this.logger=n}}class bnt extends aw{constructor(e,n){super(e,n,ant,fk),this.core=e,this.logger=n}}class vnt extends aw{constructor(e,n){super(e,n,cnt,fk,r=>r.id),this.core=e,this.logger=n}}var xnt=Object.defineProperty,Ent=(t,e,n)=>e in t?xnt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oD=(t,e,n)=>Ent(t,typeof e!="symbol"?e+"":e,n);class Cnt{constructor(e,n){this.core=e,this.logger=n,oD(this,"authKeys"),oD(this,"pairingTopics"),oD(this,"requests"),this.authKeys=new wnt(this.core,this.logger),this.pairingTopics=new bnt(this.core,this.logger),this.requests=new vnt(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var _nt=Object.defineProperty,Snt=(t,e,n)=>e in t?_nt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Qn=(t,e,n)=>Snt(t,typeof e!="symbol"?e+"":e,n);let Ant=class qpe extends Sje{constructor(e){super(e),Qn(this,"protocol",Wpe),Qn(this,"version",Vpe),Qn(this,"name",sD.name),Qn(this,"metadata"),Qn(this,"core"),Qn(this,"logger"),Qn(this,"events",new Ql.EventEmitter),Qn(this,"engine"),Qn(this,"session"),Qn(this,"proposal"),Qn(this,"pendingRequest"),Qn(this,"auth"),Qn(this,"signConfig"),Qn(this,"on",(r,s)=>this.events.on(r,s)),Qn(this,"once",(r,s)=>this.events.once(r,s)),Qn(this,"off",(r,s)=>this.events.off(r,s)),Qn(this,"removeListener",(r,s)=>this.events.removeListener(r,s)),Qn(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),Qn(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"update",async r=>{try{return await this.engine.update(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"request",async r=>{try{return await this.engine.request(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"find",r=>{try{return this.engine.find(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),Qn(this,"authenticate",async(r,s)=>{try{return await this.engine.authenticate(r,s)}catch(i){throw this.logger.error(i.message),i}}),Qn(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),Qn(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),this.name=e?.name||sD.name,this.metadata=xKe(e?.metadata),this.signConfig=e?.signConfig;const n=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:e3(sx({level:e?.logger||sD.logger}));this.core=e?.core||new Xtt(e),this.logger=Mo(n,this.name),this.session=new mnt(this.core,this.logger),this.proposal=new gnt(this.core,this.logger),this.pendingRequest=new ynt(this.core,this.logger),this.engine=new pnt(this),this.auth=new Cnt(this.core,this.logger)}static async init(e){const n=new qpe(e);return await n.initialize(),n}get context(){return sc(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")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var Z7={exports:{}};(function(t,e){var n=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof kr<"u"&&kr,r=function(){function i(){this.fetch=!1,this.DOMException=n.DOMException}return i.prototype=n,new i}();(function(i){(function(o){var a=typeof i<"u"&&i||typeof self<"u"&&self||typeof kr<"u"&&kr||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(N){return N&&DataView.prototype.isPrototypeOf(N)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(N){return N&&u.indexOf(Object.prototype.toString.call(N))>-1};function f(N){if(typeof N!="string"&&(N=String(N)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(N)||N==="")throw new TypeError('Invalid character in header field name: "'+N+'"');return N.toLowerCase()}function p(N){return typeof N!="string"&&(N=String(N)),N}function m(N){var T={next:function(){var U=N.shift();return{done:U===void 0,value:U}}};return c.iterable&&(T[Symbol.iterator]=function(){return T}),T}function y(N){this.map={},N instanceof y?N.forEach(function(T,U){this.append(U,T)},this):Array.isArray(N)?N.forEach(function(T){if(T.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+T.length);this.append(T[0],T[1])},this):N&&Object.getOwnPropertyNames(N).forEach(function(T){this.append(T,N[T])},this)}y.prototype.append=function(N,T){N=f(N),T=p(T);var U=this.map[N];this.map[N]=U?U+", "+T:T},y.prototype.delete=function(N){delete this.map[f(N)]},y.prototype.get=function(N){return N=f(N),this.has(N)?this.map[N]:null},y.prototype.has=function(N){return this.map.hasOwnProperty(f(N))},y.prototype.set=function(N,T){this.map[f(N)]=p(T)},y.prototype.forEach=function(N,T){for(var U in this.map)this.map.hasOwnProperty(U)&&N.call(T,this.map[U],U,this)},y.prototype.keys=function(){var N=[];return this.forEach(function(T,U){N.push(U)}),m(N)},y.prototype.values=function(){var N=[];return this.forEach(function(T){N.push(T)}),m(N)},y.prototype.entries=function(){var N=[];return this.forEach(function(T,U){N.push([U,T])}),m(N)},c.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function b(N){if(!N._noBody){if(N.bodyUsed)return Promise.reject(new TypeError("Already read"));N.bodyUsed=!0}}function v(N){return new Promise(function(T,U){N.onload=function(){T(N.result)},N.onerror=function(){U(N.error)}})}function x(N){var T=new FileReader,U=v(T);return T.readAsArrayBuffer(N),U}function E(N){var T=new FileReader,U=v(T),L=/charset=([A-Za-z0-9_-]+)/.exec(N.type),P=L?L[1]:"utf-8";return T.readAsText(N,P),U}function A(N){for(var T=new Uint8Array(N),U=new Array(T.length),L=0;L-1?T:N}function S(N,T){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');T=T||{};var U=T.body;if(N instanceof S){if(N.bodyUsed)throw new TypeError("Already read");this.url=N.url,this.credentials=N.credentials,T.headers||(this.headers=new y(N.headers)),this.method=N.method,this.mode=N.mode,this.signal=N.signal,!U&&N._bodyInit!=null&&(U=N._bodyInit,N.bodyUsed=!0)}else this.url=String(N);if(this.credentials=T.credentials||this.credentials||"same-origin",(T.headers||!this.headers)&&(this.headers=new y(T.headers)),this.method=W(T.method||this.method||"GET"),this.mode=T.mode||this.mode||null,this.signal=T.signal||this.signal||function(){if("AbortController"in a){var H=new AbortController;return H.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&U)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(U),(this.method==="GET"||this.method==="HEAD")&&(T.cache==="no-store"||T.cache==="no-cache")){var L=/([?&])_=[^&]*/;if(L.test(this.url))this.url=this.url.replace(L,"$1_="+new Date().getTime());else{var P=/\?/;this.url+=(P.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}S.prototype.clone=function(){return new S(this,{body:this._bodyInit})};function $(N){var T=new FormData;return N.trim().split("&").forEach(function(U){if(U){var L=U.split("="),P=L.shift().replace(/\+/g," "),H=L.join("=").replace(/\+/g," ");T.append(decodeURIComponent(P),decodeURIComponent(H))}}),T}function R(N){var T=new y,U=N.replace(/\r?\n[\t ]+/g," ");return U.split("\r").map(function(L){return L.indexOf(` +`)===0?L.substr(1,L.length):L}).forEach(function(L){var P=L.split(":"),H=P.shift().trim();if(H){var Y=P.join(":").trim();try{T.append(H,Y)}catch(re){console.warn("Response "+re.message)}}}),T}k.call(S.prototype);function M(N,T){if(!(this instanceof M))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(T||(T={}),this.type="default",this.status=T.status===void 0?200:T.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=T.statusText===void 0?"":""+T.statusText,this.headers=new y(T.headers),this.url=T.url||"",this._initBody(N)}k.call(M.prototype),M.prototype.clone=function(){return new M(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},M.error=function(){var N=new M(null,{status:200,statusText:""});return N.ok=!1,N.status=0,N.type="error",N};var j=[301,302,303,307,308];M.redirect=function(N,T){if(j.indexOf(T)===-1)throw new RangeError("Invalid status code");return new M(null,{status:T,headers:{location:N}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(T,U){this.message=T,this.name=U;var L=Error(T);this.stack=L.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function z(N,T){return new Promise(function(U,L){var P=new S(N,T);if(P.signal&&P.signal.aborted)return L(new o.DOMException("Aborted","AbortError"));var H=new XMLHttpRequest;function Y(){H.abort()}H.onload=function(){var fe={statusText:H.statusText,headers:R(H.getAllResponseHeaders()||"")};P.url.indexOf("file://")===0&&(H.status<200||H.status>599)?fe.status=200:fe.status=H.status,fe.url="responseURL"in H?H.responseURL:fe.headers.get("X-Request-URL");var ve="response"in H?H.response:H.responseText;setTimeout(function(){U(new M(ve,fe))},0)},H.onerror=function(){setTimeout(function(){L(new TypeError("Network request failed"))},0)},H.ontimeout=function(){setTimeout(function(){L(new TypeError("Network request timed out"))},0)},H.onabort=function(){setTimeout(function(){L(new o.DOMException("Aborted","AbortError"))},0)};function re(fe){try{return fe===""&&a.location.href?a.location.href:fe}catch{return fe}}if(H.open(P.method,re(P.url),!0),P.credentials==="include"?H.withCredentials=!0:P.credentials==="omit"&&(H.withCredentials=!1),"responseType"in H&&(c.blob?H.responseType="blob":c.arrayBuffer&&(H.responseType="arraybuffer")),T&&typeof T.headers=="object"&&!(T.headers instanceof y||a.Headers&&T.headers instanceof a.Headers)){var de=[];Object.getOwnPropertyNames(T.headers).forEach(function(fe){de.push(f(fe)),H.setRequestHeader(fe,p(T.headers[fe]))}),P.headers.forEach(function(fe,ve){de.indexOf(ve)===-1&&H.setRequestHeader(ve,fe)})}else P.headers.forEach(function(fe,ve){H.setRequestHeader(ve,fe)});P.signal&&(P.signal.addEventListener("abort",Y),H.onreadystatechange=function(){H.readyState===4&&P.signal.removeEventListener("abort",Y)}),H.send(typeof P._bodyInit>"u"?null:P._bodyInit)})}return z.polyfill=!0,a.fetch||(a.fetch=z,a.Headers=y,a.Request=S,a.Response=M),o.Headers=y,o.Request=S,o.Response=M,o.fetch=z,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var s=n.fetch?n:r;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,t.exports=e})(Z7,Z7.exports);var Int=Z7.exports;const HJ=Zi(Int);var Tnt=Object.defineProperty,Nnt=Object.defineProperties,Pnt=Object.getOwnPropertyDescriptors,qJ=Object.getOwnPropertySymbols,knt=Object.prototype.hasOwnProperty,Rnt=Object.prototype.propertyIsEnumerable,KJ=(t,e,n)=>e in t?Tnt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,GJ=(t,e)=>{for(var n in e||(e={}))knt.call(e,n)&&KJ(t,n,e[n]);if(qJ)for(var n of qJ(e))Rnt.call(e,n)&&KJ(t,n,e[n]);return t},ZJ=(t,e)=>Nnt(t,Pnt(e));const Ont={Accept:"application/json","Content-Type":"application/json"},$nt="POST",YJ={headers:Ont,method:$nt},XJ=10;let dd=class{constructor(e,n=!1){if(this.url=e,this.disableProviderPing=n,this.events=new Ql.EventEmitter,this.isAvailable=!1,this.registering=!1,!pJ(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=n}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const n=Zh(e),r=await(await HJ(this.url,ZJ(GJ({},YJ),{body:n}))).json();this.onPayload({data:r})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!pJ(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,s)=>{this.events.once("register_error",i=>{this.resetMaxListeners(),s(i)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));r()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const n=Zh({id:1,jsonrpc:"2.0",method:"test",params:[]});await HJ(e,ZJ(GJ({},YJ),{body:n}))}this.onOpen()}catch(n){const r=this.parseError(n);throw this.events.emit("register_error",r),this.onClose(),r}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const n=typeof e.data=="string"?yy(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),s=r.message||r.toString(),i=lk(e,s);this.events.emit("payload",i)}parseError(e,n=this.url){return xpe(e,n,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>XJ&&this.events.setMaxListeners(XJ)}};const QJ="error",Dnt="wss://relay.walletconnect.org",Mnt="wc",Lnt="universal_provider",DA=`${Mnt}@2:${Lnt}:`,Kpe="https://rpc.walletconnect.org/v1/",Eb="generic",Bnt=`${Kpe}bundler`,eu={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Kz(t){return t==null||typeof t!="object"&&typeof t!="function"}function Gpe(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Zpe(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const Unt="[object RegExp]",Ype="[object String]",Xpe="[object Number]",Qpe="[object Boolean]",Jpe="[object Arguments]",Fnt="[object Symbol]",jnt="[object Date]",znt="[object Map]",Wnt="[object Set]",Vnt="[object Array]",Hnt="[object ArrayBuffer]",qnt="[object Object]",Knt="[object DataView]",Gnt="[object Uint8Array]",Znt="[object Uint8ClampedArray]",Ynt="[object Uint16Array]",Xnt="[object Uint32Array]",Qnt="[object Int8Array]",Jnt="[object Int16Array]",ert="[object Int32Array]",trt="[object Float32Array]",nrt="[object Float64Array]";function Gz(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function rrt(t,e){return jb(t,void 0,t,new Map,e)}function jb(t,e,n,r=new Map,s=void 0){const i=s?.(t,e,n,r);if(i!=null)return i;if(Kz(t))return t;if(r.has(t))return r.get(t);if(Array.isArray(t)){const o=new Array(t.length);r.set(t,o);for(let a=0;a{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Xpe:case Ype:case Qpe:{const o=new t.constructor(t?.valueOf());return um(o,t),o}case Jpe:{const o={};return um(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function JJ(t){return irt(t)}function eee(t){return t!==null&&typeof t=="object"&&Zpe(t)==="[object Arguments]"}function tee(t){return typeof t=="object"&&t!==null}function ort(){}function art(t){return Gz(t)}function crt(t){if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const n=t[Symbol.toStringTag];return n==null||!Object.getOwnPropertyDescriptor(t,Symbol.toStringTag)?.writable?!1:t.toString()===`[object ${n}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function lrt(t){if(Kz(t))return t;if(Array.isArray(t)||Gz(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),n=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new n(t);if(t instanceof RegExp){const r=new n(t);return r.lastIndex=t.lastIndex,r}if(t instanceof DataView)return new n(t.buffer.slice(0));if(t instanceof Error){const r=new n(t.message);return r.stack=t.stack,r.name=t.name,r.cause=t.cause,r}if(typeof File<"u"&&t instanceof File)return new n([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const r=Object.create(e);return Object.assign(r,t)}return t}function urt(t,...e){const n=e.slice(0,-1),r=e[e.length-1];let s=t;for(let i=0;ie in t?frt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,MA=(t,e)=>{for(var n in e||(e={}))grt.call(e,n)&&ree(t,n,e[n]);if(nee)for(var n of nee(e))mrt.call(e,n)&&ree(t,n,e[n]);return t},yrt=(t,e)=>hrt(t,prt(e));function jc(t,e,n){var r;const s=dv(t);return((r=e.rpcMap)==null?void 0:r[s.reference])||`${Kpe}?chainId=${s.namespace}:${s.reference}&projectId=${n}`}function cw(t){return t.includes(":")?t.split(":")[1]:t}function ege(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function wrt(t,e){const n=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!n.length)return[];const r=[];return n.forEach(s=>{const i=e.namespaces[s].accounts;r.push(...i)}),r}function see(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>{var r,s;return((r=n?.chains)==null?void 0:r.length)&&((s=n?.chains)==null?void 0:s.length)>0}))}function LA(t={},e={}){const n=see(iee(t)),r=see(iee(e));return drt(n,r)}function iee(t){var e,n,r,s,i;const o={};if(!tf(t))return o;for(const[a,c]of Object.entries(t)){const l=ak(a)?[a]:c.chains,u=c.methods||[],d=c.events||[],f=c.rpcMap||{},p=Fb(a);o[p]=yrt(MA(MA({},o[p]),c),{chains:ef(l,(e=o[p])==null?void 0:e.chains),methods:ef(u,(n=o[p])==null?void 0:n.methods),events:ef(d,(r=o[p])==null?void 0:r.events)}),(tf(f)||tf(((s=o[p])==null?void 0:s.rpcMap)||{}))&&(o[p].rpcMap=MA(MA({},f),(i=o[p])==null?void 0:i.rpcMap))}return o}function oee(t){return t.includes(":")?t.split(":")[2]:t}function aee(t){const e={};for(const[n,r]of Object.entries(t)){const s=r.methods||[],i=r.events||[],o=r.accounts||[],a=ak(n)?[n]:r.chains?r.chains:ege(r.accounts);e[n]={chains:a,methods:s,events:i,accounts:o}}return e}function aD(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const tge={},br=t=>tge[t],cD=(t,e)=>{tge[t]=e};var brt=Object.defineProperty,cee=Object.getOwnPropertySymbols,vrt=Object.prototype.hasOwnProperty,xrt=Object.prototype.propertyIsEnumerable,lee=(t,e,n)=>e in t?brt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,uee=(t,e)=>{for(var n in e||(e={}))vrt.call(e,n)&&lee(t,n,e[n]);if(cee)for(var n of cee(e))xrt.call(e,n)&&lee(t,n,e[n]);return t};const dee="eip155",Ert=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],Crt=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,lD=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,fee=t=>Object.keys(t).filter(e=>Ert.includes(e)).reduce((e,n)=>(e[n]=t[n],e),{}),_rt=(t,e,n)=>{const{sessionProperties:r={},scopedProperties:s={}}=t,i={};if(!tf(s)&&!tf(r))return;const o=fee(r);for(const a of n){const c=Crt(a);if(!c)continue;i[lD(c)]=o;const l=s?.[`${dee}:${c}`];if(l){const u=l?.[`${dee}:${c}:${e}`];i[lD(c)]=uee(uee({},i[lD(c)]),fee(u||l))}}for(const[a,c]of Object.entries(i))Object.keys(c).length===0&&delete i[a];return Object.keys(i).length>0?i:void 0};var Srt=Object.defineProperty,Art=(t,e,n)=>e in t?Srt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,eb=(t,e,n)=>Art(t,typeof e!="symbol"?e+"":e,n);class Irt{constructor(e){eb(this,"name","polkadot"),eb(this,"client"),eb(this,"httpProviders"),eb(this,"events"),eb(this,"namespace"),eb(this,"chainId"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){this.httpProviders[e]||this.setHttpProvider(e,n),this.chainId=e,this.events.emit(eu.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(n=>{var r;const s=cw(n);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[n])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProvider(e,n){const r=n||jc(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Jl(new dd(r,br("disableProviderPing")))}}var Trt=Object.defineProperty,Nrt=Object.defineProperties,Prt=Object.getOwnPropertyDescriptors,hee=Object.getOwnPropertySymbols,krt=Object.prototype.hasOwnProperty,Rrt=Object.prototype.propertyIsEnumerable,X7=(t,e,n)=>e in t?Trt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pee=(t,e)=>{for(var n in e||(e={}))krt.call(e,n)&&X7(t,n,e[n]);if(hee)for(var n of hee(e))Rrt.call(e,n)&&X7(t,n,e[n]);return t},gee=(t,e)=>Nrt(t,Prt(e)),tb=(t,e,n)=>X7(t,typeof e!="symbol"?e+"":e,n);class Ort{constructor(e){tb(this,"name","eip155"),tb(this,"client"),tb(this,"chainId"),tb(this,"namespace"),tb(this,"httpProviders"),tb(this,"events"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){this.httpProviders[e]||this.setHttpProvider(parseInt(e),n),this.chainId=parseInt(e),this.events.emit(eu.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,n){const r=n||jc(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Jl(new dd(r,br("disableProviderPing")))}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProviders(){const e={};return this.namespace.chains.forEach(n=>{var r;const s=parseInt(cw(n));e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[n])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}async handleSwitchChain(e){var n,r;let s=e.request.params?(n=e.request.params[0])==null?void 0:n.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const i=parseInt(s,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${i}`);else throw new Error(`Failed to switch to chain 'eip155:${i}'. 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 n,r,s,i,o;const a=(r=(n=e.request)==null?void 0:n.params)==null?void 0:r[0],c=((i=(s=e.request)==null?void 0:s.params)==null?void 0:i[1])||[];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)||{},d=`${a}${c.join(",")}`,f=u?.[d];if(f)return f;let p;try{p=_rt(l,a,c)}catch(y){console.warn("Failed to extract capabilities from session",y)}if(p)return p;const m=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:gee(pee({},l.sessionProperties||{}),{capabilities:gee(pee({},u||{}),{[d]:m})})})}catch(y){console.warn("Failed to update session with capabilities",y)}return m}async getCallStatus(e){var n,r;const s=this.client.session.get(e.topic),i=(n=s.sessionProperties)==null?void 0:n.bundler_name;if(i){const a=this.getBundlerUrl(e.chainId,i);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(r=s.sessionProperties)==null?void 0:r.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,n){var r;const s=new URL(e),i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Pg("eth_getUserOperationReceipt",[(r=n.request.params)==null?void 0:r[0]]))});if(!i.ok)throw new Error(`Failed to fetch user operation receipt - ${i.status}`);return await i.json()}getBundlerUrl(e,n){return`${Bnt}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${n}`}}var $rt=Object.defineProperty,Drt=(t,e,n)=>e in t?$rt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,nb=(t,e,n)=>Drt(t,typeof e!="symbol"?e+"":e,n);class Mrt{constructor(e){nb(this,"name","solana"),nb(this,"client"),nb(this,"httpProviders"),nb(this,"events"),nb(this,"namespace"),nb(this,"chainId"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){this.httpProviders[e]||this.setHttpProvider(e,n),this.chainId=e,this.events.emit(eu.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(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(n=>{var r;const s=cw(n);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[n])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProvider(e,n){const r=n||jc(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Jl(new dd(r,br("disableProviderPing")))}}var Lrt=Object.defineProperty,Brt=(t,e,n)=>e in t?Lrt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,rb=(t,e,n)=>Brt(t,typeof e!="symbol"?e+"":e,n);class Urt{constructor(e){rb(this,"name","cosmos"),rb(this,"client"),rb(this,"httpProviders"),rb(this,"events"),rb(this,"namespace"),rb(this,"chainId"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){this.httpProviders[e]||this.setHttpProvider(e,n),this.chainId=e,this.events.emit(eu.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(n=>{var r;const s=cw(n);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[n])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProvider(e,n){const r=n||jc(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Jl(new dd(r,br("disableProviderPing")))}}var Frt=Object.defineProperty,jrt=(t,e,n)=>e in t?Frt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,sb=(t,e,n)=>jrt(t,typeof e!="symbol"?e+"":e,n);class zrt{constructor(e){sb(this,"name","algorand"),sb(this,"client"),sb(this,"httpProviders"),sb(this,"events"),sb(this,"namespace"),sb(this,"chainId"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){if(!this.httpProviders[e]){const r=n||jc(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.chainId=e,this.events.emit(eu.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(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(n=>{var r;e[n]=this.createHttpProvider(n,(r=this.namespace.rpcMap)==null?void 0:r[n])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProvider(e,n){const r=n||jc(e,this.namespace,this.client.core.projectId);return typeof r>"u"?void 0:new Jl(new dd(r,br("disableProviderPing")))}}var Wrt=Object.defineProperty,Vrt=(t,e,n)=>e in t?Wrt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ib=(t,e,n)=>Vrt(t,typeof e!="symbol"?e+"":e,n);class Hrt{constructor(e){ib(this,"name","cip34"),ib(this,"client"),ib(this,"httpProviders"),ib(this,"events"),ib(this,"namespace"),ib(this,"chainId"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){this.httpProviders[e]||this.setHttpProvider(e,n),this.chainId=e,this.events.emit(eu.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(n=>{const r=this.getCardanoRPCUrl(n),s=cw(n);e[s]=this.createHttpProvider(s,r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}getCardanoRPCUrl(e){const n=this.namespace.rpcMap;if(n)return n[e]}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProvider(e,n){const r=n||this.getCardanoRPCUrl(e);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Jl(new dd(r,br("disableProviderPing")))}}var qrt=Object.defineProperty,Krt=(t,e,n)=>e in t?qrt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ob=(t,e,n)=>Krt(t,typeof e!="symbol"?e+"":e,n);class Grt{constructor(e){ob(this,"name","elrond"),ob(this,"client"),ob(this,"httpProviders"),ob(this,"events"),ob(this,"namespace"),ob(this,"chainId"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){this.httpProviders[e]||this.setHttpProvider(e,n),this.chainId=e,this.events.emit(eu.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(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(n=>{var r;const s=cw(n);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[n])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProvider(e,n){const r=n||jc(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Jl(new dd(r,br("disableProviderPing")))}}var Zrt=Object.defineProperty,Yrt=(t,e,n)=>e in t?Zrt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ab=(t,e,n)=>Yrt(t,typeof e!="symbol"?e+"":e,n);class Xrt{constructor(e){ab(this,"name","multiversx"),ab(this,"client"),ab(this,"httpProviders"),ab(this,"events"),ab(this,"namespace"),ab(this,"chainId"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){this.httpProviders[e]||this.setHttpProvider(e,n),this.chainId=e,this.events.emit(eu.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(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(n=>{var r;const s=cw(n);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[n])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProvider(e,n){const r=n||jc(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Jl(new dd(r,br("disableProviderPing")))}}var Qrt=Object.defineProperty,Jrt=(t,e,n)=>e in t?Qrt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,cb=(t,e,n)=>Jrt(t,typeof e!="symbol"?e+"":e,n);class est{constructor(e){cb(this,"name","near"),cb(this,"client"),cb(this,"httpProviders"),cb(this,"events"),cb(this,"namespace"),cb(this,"chainId"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){if(this.chainId=e,!this.httpProviders[e]){const r=n||jc(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(eu.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(n=>{var r;e[n]=this.createHttpProvider(n,(r=this.namespace.rpcMap)==null?void 0:r[n])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProvider(e,n){const r=n||jc(e,this.namespace);return typeof r>"u"?void 0:new Jl(new dd(r,br("disableProviderPing")))}}var tst=Object.defineProperty,nst=(t,e,n)=>e in t?tst(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lb=(t,e,n)=>nst(t,typeof e!="symbol"?e+"":e,n);class rst{constructor(e){lb(this,"name","tezos"),lb(this,"client"),lb(this,"httpProviders"),lb(this,"events"),lb(this,"namespace"),lb(this,"chainId"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){if(this.chainId=e,!this.httpProviders[e]){const r=n||jc(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(eu.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(n=>{e[n]=this.createHttpProvider(n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProvider(e,n){const r=n||jc(e,this.namespace);return typeof r>"u"?void 0:new Jl(new dd(r))}}var sst=Object.defineProperty,ist=(t,e,n)=>e in t?sst(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ub=(t,e,n)=>ist(t,typeof e!="symbol"?e+"":e,n);class ost{constructor(e){ub(this,"name",Eb),ub(this,"client"),ub(this,"httpProviders"),ub(this,"events"),ub(this,"namespace"),ub(this,"chainId"),this.namespace=e.namespace,this.events=br("events"),this.client=br("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,n){this.httpProviders[e]||this.setHttpProvider(e,n),this.chainId=e,this.events.emit(eu.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(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}createHttpProviders(){var e,n;const r={};return(n=(e=this.namespace)==null?void 0:e.accounts)==null||n.forEach(s=>{const i=dv(s);r[`${i.namespace}:${i.reference}`]=this.createHttpProvider(s)}),r}getHttpProvider(e){const n=this.httpProviders[e];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,n){const r=this.createHttpProvider(e,n);r&&(this.httpProviders[e]=r)}createHttpProvider(e,n){const r=n||jc(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Jl(new dd(r,br("disableProviderPing")))}}var ast=Object.defineProperty,cst=Object.defineProperties,lst=Object.getOwnPropertyDescriptors,mee=Object.getOwnPropertySymbols,ust=Object.prototype.hasOwnProperty,dst=Object.prototype.propertyIsEnumerable,Q7=(t,e,n)=>e in t?ast(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,BA=(t,e)=>{for(var n in e||(e={}))ust.call(e,n)&&Q7(t,n,e[n]);if(mee)for(var n of mee(e))dst.call(e,n)&&Q7(t,n,e[n]);return t},uD=(t,e)=>cst(t,lst(e)),dl=(t,e,n)=>Q7(t,typeof e!="symbol"?e+"":e,n);let fst=class nge{constructor(e){dl(this,"client"),dl(this,"namespaces"),dl(this,"optionalNamespaces"),dl(this,"sessionProperties"),dl(this,"scopedProperties"),dl(this,"events",new hz),dl(this,"rpcProviders",{}),dl(this,"session"),dl(this,"providerOpts"),dl(this,"logger"),dl(this,"uri"),dl(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:e3(sx({level:e?.logger||QJ})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const n=new nge(e);return await n.initialize(),n}async request(e,n,r){const[s,i]=this.validateChain(n);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:BA({},e),chainId:`${s}:${i}`,topic:this.session.topic,expiry:r})}sendAsync(e,n,r,s){const i=new Date().getTime();this.request(e,r,s).then(o=>n(null,ck(i,o))).catch(o=>n(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:ds("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,n){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:s}=await this.client.authenticate(e,n);r&&(this.uri=r,this.events.emit("display_uri",r));const i=await s();if(this.session=i.session,this.session){const o=aee(this.session.namespaces);this.namespaces=LA(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return i}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}removeListener(e,n){this.events.removeListener(e,n)}off(e,n){this.events.off(e,n)}get isWalletConnect(){return!0}async pair(e){const{uri:n,approval:r}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});n&&(this.uri=n,this.events.emit("display_uri",n));const s=await r();this.session=s;const i=aee(s.namespaces);return this.namespaces=LA(this.namespaces,i),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,n){try{if(!this.session)return;const[r,s]=this.validateChain(e),i=this.getProvider(r);i.name===Eb?i.setDefaultChain(`${r}:${s}`,n):i.setDefaultChain(s,n)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const n=this.client.pairing.getAll();if(Ph(n)){for(const r of n)e.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${n.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,n;if(this.client=this.providerOpts.client||await Ant.init({core:this.providerOpts.core,logger:this.providerOpts.logger||QJ,relayUrl:this.providerOpts.relayUrl||Dnt,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(r){throw this.logger.error("Failed to get session",r),new Error(`The provided session: ${(n=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:n.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(n=>Fb(n)))];cD("client",this.client),cD("events",this.events),cD("disableProviderPing",this.disableProviderPing),e.forEach(n=>{if(!this.session)return;const r=wrt(n,this.session);if(r?.length===0)return;const s=ege(r),i=LA(this.namespaces,this.optionalNamespaces),o=uD(BA({},i[n]),{accounts:r,chains:s});switch(n){case"eip155":this.rpcProviders[n]=new Ort({namespace:o});break;case"algorand":this.rpcProviders[n]=new zrt({namespace:o});break;case"solana":this.rpcProviders[n]=new Mrt({namespace:o});break;case"cosmos":this.rpcProviders[n]=new Urt({namespace:o});break;case"polkadot":this.rpcProviders[n]=new Irt({namespace:o});break;case"cip34":this.rpcProviders[n]=new Hrt({namespace:o});break;case"elrond":this.rpcProviders[n]=new Grt({namespace:o});break;case"multiversx":this.rpcProviders[n]=new Xrt({namespace:o});break;case"near":this.rpcProviders[n]=new est({namespace:o});break;case"tezos":this.rpcProviders[n]=new rst({namespace:o});break;default:this.rpcProviders[Eb]?this.rpcProviders[Eb].updateNamespace(o):this.rpcProviders[Eb]=new ost({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var n;const{topic:r}=e;r===((n=this.session)==null?void 0:n.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var n;const{params:r,topic:s}=e;if(s!==((n=this.session)==null?void 0:n.topic))return;const{event:i}=r;if(i.name==="accountsChanged"){const o=i.data;o&&Ph(o)&&this.events.emit("accountsChanged",o.map(oee))}else if(i.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=Fb(o),l=aD(o)!==aD(a)?`${c}:${aD(a)}`:o;this.onChainChanged(l)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:n})=>{var r,s;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:i}=n,o=(s=this.client)==null?void 0:s.session.get(e);this.session=uD(BA({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:n})}),this.client.on("session_delete",async e=>{var n;e.topic===((n=this.session)==null?void 0:n.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",uD(BA({},ds("USER_DISCONNECTED")),{data:e.topic})))}),this.on(eu.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Eb]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var n;this.getProvider(e).updateNamespace((n=this.session)==null?void 0:n.namespaces[e])})}setNamespaces(e){const{namespaces:n={},optionalNamespaces:r={},sessionProperties:s,scopedProperties:i}=e;this.optionalNamespaces=LA(n,r),this.sessionProperties=s,this.scopedProperties=i}validateChain(e){const[n,r]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[n,r];if(n&&!Object.keys(this.namespaces||{}).map(o=>Fb(o)).includes(n))throw new Error(`Namespace '${n}' is not configured. Please call connect() first with namespace config.`);if(n&&r)return[n,r];const s=Fb(Object.keys(this.namespaces)[0]),i=this.rpcProviders[s].getDefaultChain();return[s,i]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,n=!1){if(!this.namespaces)return;const[r,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(r,s),this.events.emit("chainChanged",s);const i=this.getProvider(r).getDefaultChain();n||this.getProvider(r).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:r,previousChainId:i,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:n,newChainId:r}){var s,i;try{if(n===r)return;const o=(i=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:i.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(oee);if(!Ph(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,n){if(!this.namespaces)return;const r=this.namespaces[e]?e:`${e}:${n}`,s={chains:[],methods:[],events:[],defaultChain:n};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=n):this.namespaces[r]=s}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,n){var r;const s=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${DA}/${e}${s}`,n)}async getFromStore(e){var n;const r=((n=this.session)==null?void 0:n.topic)||"";return await this.client.core.storage.getItem(`${DA}/${e}${r}`)}async deleteFromStore(e){var n;const r=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.removeItem(`${DA}/${e}${r}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const n=await this.client.core.storage.getKeys();for(const r of n)r.startsWith(DA)&&await this.client.core.storage.removeItem(r)}catch(n){this.logger.warn("Failed to cleanup storage",n)}}},em=null;const Da={getSIWX(){return _e.state.siwx},async initializeIfEnabled(t=G.getActiveCaipAddress()){const e=_e.state.siwx;if(!(e&&t))return;const[n,r,s]=t.split(":");if(G.checkIfSupportedNetwork(n,`${n}:${r}`))try{if(_e.state.remoteFeatures?.emailCapture){const o=G.getAccountData(n)?.user;await tn.open({view:"DataCapture",data:{email:o?.email??void 0}});return}if(em&&await em,(await e.getSessions(`${n}:${r}`,s)).length)return;await tn.open({view:"SIWXSignMessage"})}catch(i){console.error("SIWXUtil:initializeIfEnabled",i),Lt.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await Ue._getClient()?.disconnect().catch(console.error),ze.reset("Connect"),Wn.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=_e.state.siwx,e=De.getPlainAddress(G.getActiveCaipAddress()),n=vm(),r=Ue._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!n)throw new Error("No ActiveCaipNetwork or client found");if(!r)throw new Error("No ConnectionController client found");try{const s=await t.createMessage({chainId:n.caipNetworkId,accountAddress:e}),i=s.toString();ke.getConnectorId(n.chainNamespace)===ye.CONNECTOR_ID.AUTH&&ze.pushTransactionStack({});const a=await r.signMessage(i);await t.addSession({data:s,message:i,signature:a}),G.setLastConnectedSIWECaipNetwork(n),tn.close(),Lt.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(s){const i=this.getSIWXEventProperties();(!tn.state.open||ze.state.view==="ApproveTransaction")&&await tn.open({view:"SIWXSignMessage"}),Wn.showError("Error signing message"),Lt.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:i}),console.error("SWIXUtil:requestSignMessage",s)}},async cancelSignMessage(){try{const t=this.getSIWX();if(t?.getRequired?.()){const n=G.getLastConnectedSIWECaipNetwork();if(n){const r=await t?.getSessions(n?.caipNetworkId,De.getPlainAddress(G.getActiveCaipAddress())||"");r&&r.length>0?await G.switchActiveNetwork(n):await Ue.disconnect()}else await Ue.disconnect()}else tn.close();tn.close(),Lt.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(t){console.error("SIWXUtil:cancelSignMessage",t)}},async getAllSessions(){const t=this.getSIWX(),e=G.getAllRequestedCaipNetworks(),n=[];return await Promise.all(e.map(async r=>{const s=await t?.getSessions(r.caipNetworkId,De.getPlainAddress(G.getActiveCaipAddress())||"");s&&n.push(...s)})),n},async getSessions(t){const e=_e.state.siwx;let n=t?.address;if(!n){const s=G.getActiveCaipAddress();n=De.getPlainAddress(s)}let r=t?.caipNetworkId;return r||(r=G.getActiveCaipNetwork()?.caipNetworkId),e&&n&&r?e.getSessions(r,n):[]},async isSIWXCloseDisabled(){const t=this.getSIWX();if(t){const e=ze.state.view==="ApproveTransaction",n=ze.state.view==="SIWXSignMessage";if(e||n)return t.getRequired?.()&&(await this.getSessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:t,chainId:e,socialUri:n,preferredAccountType:r,chainNamespace:s}){const i=Da.getSIWX();if(!i||!s.includes(ye.CHAIN.EVM)||_e.state.remoteFeatures?.emailCapture){const u=await t.connect({chainId:e,socialUri:n,preferredAccountType:r});return{address:u.address,chainId:u.chainId,accounts:u.accounts}}const o=`${s}:${e}`,a=await i.createMessage({chainId:o,accountAddress:"<>"}),c={accountAddress:a.accountAddress,chainId:a.chainId,domain:a.domain,uri:a.uri,version:a.version,nonce:a.nonce,notBefore:a.notBefore,statement:a.statement,resources:a.resources,requestId:a.requestId,issuedAt:a.issuedAt,expirationTime:a.expirationTime,serializedMessage:a.toString()},l=await t.connect({chainId:e,socialUri:n,siwxMessage:c,preferredAccountType:r});return c.accountAddress=l.address,c.serializedMessage=l.message||"",l.signature&&l.message&&await Da.addEmbeddedWalletSession(c,l.message,l.signature),{address:l.address,chainId:l.chainId,accounts:l.accounts}},async addEmbeddedWalletSession(t,e,n){if(em)return em;const r=Da.getSIWX();return r?(em=r.addSession({data:t,message:e,signature:n}).finally(()=>{em=null}),em):Promise.resolve()},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:n}){const r=Da.getSIWX(),s=new Set(e.map(a=>a.split(":")[0]));if(!r||s.size!==1||!s.has("eip155"))return!1;const i=await r.createMessage({chainId:vm()?.caipNetworkId||"",accountAddress:""}),o=await t.authenticate({nonce:i.nonce,domain:i.domain,uri:i.uri,exp:i.expirationTime,iat:i.issuedAt,nbf:i.notBefore,requestId:i.requestId,version:i.version,resources:i.resources,statement:i.statement,chainId:i.chainId,methods:n,chains:[i.chainId,...e.filter(a=>a!==i.chainId)]});if(Wn.showLoading("Authenticating...",{autoClose:!1}),nt.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:o.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"},Array.from(s)[0]),o?.auths?.length){const a=o.auths.map(c=>{const l=t.client.formatAuthMessage({request:c.p,iss:c.p.iss});return{data:{...c.p,accountAddress:c.p.iss.split(":").slice(-1).join(""),chainId:c.p.iss.split(":").slice(2,4).join(":"),uri:c.p.aud,version:c.p.version||i.version,expirationTime:c.p.exp,issuedAt:c.p.iat,notBefore:c.p.nbf},message:l,signature:c.s.s,cacao:c}});try{await r.setSessions(a),Lt.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:Da.getSIWXEventProperties()})}catch(c){throw console.error("SIWX:universalProviderAuth - failed to set sessions",c),Lt.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:Da.getSIWXEventProperties()}),await t.disconnect().catch(console.error),c}finally{Wn.hide()}}return!0},getSIWXEventProperties(){const t=G.state.activeChain;if(!t)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:G.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:Ss(t)===_r.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}},Jr={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",EIP155:ye.CHAIN.EVM,ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"ID_AUTH"},vo={ConnectorExplorerIds:{[ye.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[ye.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[ye.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[ye.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[ye.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Jr.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[Jr.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[Jr.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[Jr.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[Jr.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[Jr.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[Jr.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[Jr.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[Jr.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[Jr.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[Jr.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200"},ConnectorImageIds:{[ye.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[ye.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[ye.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[ye.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[ye.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[ye.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[ye.CONNECTOR_ID.INJECTED]:"Browser Wallet",[ye.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[ye.CONNECTOR_ID.COINBASE]:"Coinbase",[ye.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[ye.CONNECTOR_ID.LEDGER]:"Ledger",[ye.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[ye.CONNECTOR_ID.INJECTED]:"INJECTED",[ye.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[ye.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[ye.CONNECTOR_ID.AUTH]:"AUTH",[Jr.CONNECTOR_TYPE_AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]},Jn={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([n,r])=>{e[`${Jr.EIP155}:${n}`]=r}),e},isLowerCaseMatch(t,e){return t?.toLowerCase()===e?.toLowerCase()},getActiveNamespaceConnectedToAuth(){const t=G.state.activeChain;return ye.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(e=>ke.getConnectorId(e)===ye.CONNECTOR_ID.AUTH&&e===t)},withRetry({conditionFn:t,intervalMs:e,maxRetries:n}){let r=0;return new Promise(s=>{async function i(){return r+=1,await t()?s(!0):r>=n?s(!1):(setTimeout(i,e),null)}i()})}},hst=new AbortController,fs={EmbeddedWalletAbortController:hst,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"ORIGIN_NOT_ALLOWED"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{code:"APKT001",displayMessage:"Network Not Found",debugMessage:"The specified network is not recognized. Please ensure it is included in the `networks` array of your `createAppKit` configuration."},ORIGIN_NOT_ALLOWED:{code:"APKT002",displayMessage:"Invalid App Configuration",debugMessage:()=>`The origin ${Ub()?window.origin:"unknown"} is not in your allow list. Please update your allowed domains at https://dashboard.reown.com.`},IFRAME_LOAD_FAILED:{code:"APKT003",displayMessage:"Network Error: Wallet Load Failed",debugMessage:()=>"Failed to load the embedded wallet. This may be due to network issues or server downtime. Please check your network connection and try again shortly. Contact support if the issue persists."},IFRAME_REQUEST_TIMEOUT:{code:"APKT004",displayMessage:"Wallet Request Timeout",debugMessage:()=>"The request to the embedded wallet timed out. Please check your network connection and try again shortly. Contact support if the issue persists."},UNVERIFIED_DOMAIN:{code:"APKT005",displayMessage:"Unverified Domain",debugMessage:()=>"Embedded wallet load failed. Ensure your domain is verified in https://dashboard.reown.com."},JWT_TOKEN_NOT_VALID:{code:"APKT006",displayMessage:"Session Expired",debugMessage:"Your session is invalid or expired. Please check your system’s date and time settings, then reconnect."},INVALID_PROJECT_ID:{code:"APKT007",displayMessage:"Invalid Project ID",debugMessage:"The specified project ID is invalid. Please visit https://dashboard.reown.com to obtain a valid project ID."},PROJECT_ID_NOT_CONFIGURED:{code:"APKT008",displayMessage:"Project ID Missing",debugMessage:"No project ID is configured. You can create and configure a project ID at https://dashboard.reown.com."},SERVER_ERROR_APP_CONFIGURATION:{code:"APKT009",displayMessage:"Server Error",debugMessage:t=>`Unable to fetch App Configuration. ${t}. Please check your network connection and try again shortly. Contact support if the issue persists.`},RATE_LIMITED_APP_CONFIGURATION:{code:"APKT010",displayMessage:"Rate Limited",debugMessage:"You have been rate limited while retrieving App Configuration. Please wait a few minutes and try again. Contact support if the issue persists."}},ALERT_WARNINGS:{LOCAL_CONFIGURATION_IGNORED:{debugMessage:t=>`[Reown Config Notice] ${t}`}}},pst={createLogger(t,e="error"){const n=sx({level:e}),{logger:r}=gz({opts:n});return r.error=(...s)=>{for(const i of s)if(i instanceof Error){t(i,...s);return}t(void 0,...s)},r}},gst="rpc.walletconnect.org";function yee(t,e){const n=new URL("https://rpc.walletconnect.org/v1/");return n.searchParams.set("chainId",t),n.searchParams.set("projectId",e),n.toString()}const dD=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],Du={extendRpcUrlWithProjectId(t,e){let n=!1;try{n=new URL(t).host===gst}catch{n=!1}if(n){const r=new URL(t);return r.searchParams.has("projectId")||r.searchParams.set("projectId",e),r.toString()}return t},isCaipNetwork(t){return"chainNamespace"in t&&"caipNetworkId"in t},getChainNamespace(t){return this.isCaipNetwork(t)?t.chainNamespace:ye.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${ye.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,n){const r=t.rpcUrls?.default?.http?.[0];return dD.includes(e)?yee(e,n):r||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:n,customRpcUrls:r}){const s=this.getChainNamespace(t),i=this.getCaipNetworkId(t),o=t.rpcUrls?.default?.http?.[0],a=this.getDefaultRpcUrl(t,i,n),c=t?.rpcUrls?.chainDefault?.http?.[0]||o,l=r?.[i]?.map(f=>f.url)||[],u=[...l,...a?[a]:[]],d=[...l];return c&&!d.includes(c)&&d.push(c),{...t,chainNamespace:s,caipNetworkId:i,assets:{imageId:vo.NetworkImageIds[t.id],imageUrl:e?.[t.id]},rpcUrls:{...t.rpcUrls,default:{http:u},chainDefault:{http:d}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:n,customRpcUrls:r}){return t.map(s=>Du.extendCaipNetwork(s,{customNetworkImageUrls:e,customRpcUrls:r,projectId:n}))},getViemTransport(t,e,n){const r=[];return n?.forEach(s=>{r.push(B2(s.url,s.config))}),dD.includes(t.caipNetworkId)&&r.push(B2(yee(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),t?.rpcUrls?.default?.http?.forEach(s=>{r.push(B2(s))}),iX(r)},extendWagmiTransports(t,e,n){if(dD.includes(t.caipNetworkId)){const r=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return iX([n,B2(r)])}return n},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:ye.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){const e=Ge.getActiveCaipNetworkId(),n=G.getAllRequestedCaipNetworks(),r=Array.from(G.state.chains?.keys()||[]),s=e?.split(":")[0],i=s?r.includes(s):!1,o=n?.find(c=>c.caipNetworkId===e);return i&&!o&&e?this.getUnsupportedNetwork(e):o||t||n?.[0]}},OT={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0},_a=Br({providers:{...OT},providerIds:{...OT}}),Fr={state:_a,subscribeKey(t,e){return ai(_a,t,e)},subscribe(t){return Gs(_a,()=>{t(_a)})},subscribeProviders(t){return Gs(_a.providers,()=>t(_a.providers))},setProvider(t,e){t&&e&&(_a.providers[t]=gy(e))},getProvider(t){if(t)return _a.providers[t]},setProviderId(t,e){e&&(_a.providerIds[t]=e)},getProviderId(t){if(t)return _a.providerIds[t]},reset(){_a.providers={...OT},_a.providerIds={...OT}},resetChain(t){_a.providers[t]=void 0,_a.providerIds[t]=void 0}},wee={address:/^0x(?:[A-Fa-f0-9]{40})$/u,transactionHash:/^0x(?:[A-Fa-f0-9]{64})$/u,signedMessage:/^0x(?:[a-fA-F0-9]{62,})$/u},$i={set(t,e){kc.isClient&&localStorage.setItem(`${$t.STORAGE_KEY}${t}`,e)},get(t){return kc.isClient?localStorage.getItem(`${$t.STORAGE_KEY}${t}`):null},delete(t,e){kc.isClient&&(e?localStorage.removeItem(t):localStorage.removeItem(`${$t.STORAGE_KEY}${t}`))}},UA=30*1e3,kc={checkIfAllowedToTriggerEmail(){const t=$i.get($t.LAST_EMAIL_LOGIN_TIME);if(t){const e=Date.now()-Number(t);if(es;function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const i={};for(const o of s)i[o]=o;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(const a of i)o[a]=s[a];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(const o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(wr||(wr={}));var J7;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(J7||(J7={}));const It=wr.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xg=t=>{switch(typeof t){case"undefined":return It.undefined;case"string":return It.string;case"number":return isNaN(t)?It.nan:It.number;case"boolean":return It.boolean;case"function":return It.function;case"bigint":return It.bigint;case"symbol":return It.symbol;case"object":return Array.isArray(t)?It.array:t===null?It.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?It.promise:typeof Map<"u"&&t instanceof Map?It.map:typeof Set<"u"&&t instanceof Set?It.set:typeof Date<"u"&&t instanceof Date?It.date:It.object;default:return It.unknown}},dt=wr.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),mst=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");let Hu=class extends Error{constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let a=r,c=0;for(;cn.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Hu.create=t=>new Hu(t);const XC=(t,e)=>{let n;switch(t.code){case dt.invalid_type:t.received===It.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case dt.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,wr.jsonStringifyReplacer)}`;break;case dt.unrecognized_keys:n=`Unrecognized key(s) in object: ${wr.joinValues(t.keys,", ")}`;break;case dt.invalid_union:n="Invalid input";break;case dt.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${wr.joinValues(t.options)}`;break;case dt.invalid_enum_value:n=`Invalid enum value. Expected ${wr.joinValues(t.options)}, received '${t.received}'`;break;case dt.invalid_arguments:n="Invalid function arguments";break;case dt.invalid_return_type:n="Invalid function return type";break;case dt.invalid_date:n="Invalid date";break;case dt.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:wr.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case dt.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case dt.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case dt.custom:n="Invalid input";break;case dt.invalid_intersection_types:n="Intersection results could not be merged";break;case dt.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case dt.not_finite:n="Number must be finite";break;default:n=e.defaultError,wr.assertNever(t)}return{message:n}};let rge=XC;function yst(t){rge=t}function $T(){return rge}const DT=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};let a="";const c=r.filter(l=>!!l).slice().reverse();for(const l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:s.message||a}},wst=[];function Rt(t,e){const n=DT({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$T(),XC].filter(r=>!!r)});t.common.issues.push(n)}let Xa=class sge{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return En;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n)r.push({key:await s.key,value:await s.value});return sge.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return En;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}};const En=Object.freeze({status:"aborted"}),ige=t=>({status:"dirty",value:t}),sa=t=>({status:"valid",value:t}),eB=t=>t.status==="aborted",tB=t=>t.status==="dirty",QC=t=>t.status==="valid",MT=t=>typeof Promise<"u"&&t instanceof Promise;var Yt;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Yt||(Yt={}));let hf=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const bee=(t,e)=>{if(QC(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Hu(t.common.issues);return this._error=n,this._error}}};function Nn(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>o.code!=="invalid_type"?{message:a.defaultError}:typeof a.data>"u"?{message:r??a.defaultError}:{message:n??a.defaultError},description:s}}let Un=class{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return xg(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:xg(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Xa,ctx:{common:e.parent.common,data:e.data,parsedType:xg(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(MT(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){var r;const s={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xg(e)},i=this._parseSync({data:e,path:s.path,parent:s});return bee(s,i)}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xg(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(MT(s)?s:Promise.resolve(s));return bee(r,i)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const o=e(s),a=()=>i.addIssue({code:dt.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new sd({schema:this,typeName:an.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return kh.create(this,this._def)}nullable(){return Cy.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ey.create(this,this._def)}promise(){return Kv.create(this,this._def)}or(e){return i_.create([this,e],this._def)}and(e){return o_.create(this,e,this._def)}transform(e){return new sd({...Nn(this._def),schema:this,typeName:an.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new u_({...Nn(this._def),innerType:this,defaultValue:n,typeName:an.ZodDefault})}brand(){return new hge({typeName:an.ZodBranded,type:this,...Nn(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new jT({...Nn(this._def),innerType:this,catchValue:n,typeName:an.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Zz.create(this,e)}readonly(){return WT.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const bst=/^c[^\s-]{8,}$/i,vst=/^[a-z][a-z0-9]*$/,xst=/^[0-9A-HJKMNP-TV-Z]{26}$/,Est=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Cst=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_st="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let fD;const Sst=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,Ast=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,Ist=t=>t.precision?t.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${t.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${t.precision}}Z$`):t.precision===0?t.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):t.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function Tst(t,e){return!!((e==="v4"||!e)&&Sst.test(t)||(e==="v6"||!e)&&Ast.test(t))}let Hv=class q2 extends Un{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==It.string){const i=this._getOrReturnCtx(e);return Rt(i,{code:dt.invalid_type,expected:It.string,received:i.parsedType}),En}const r=new Xa;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.lengthi.value&&(s=this._getOrReturnCtx(e,s),Rt(s,{code:dt.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.lengthe.test(s),{validation:n,code:dt.invalid_string,...Yt.errToObj(r)})}_addCheck(e){return new q2({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Yt.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Yt.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Yt.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Yt.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Yt.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Yt.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Yt.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Yt.errToObj(e)})}datetime(e){var n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(n=e?.offset)!==null&&n!==void 0?n:!1,...Yt.errToObj(e?.message)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Yt.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...Yt.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Yt.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Yt.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Yt.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Yt.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Yt.errToObj(n)})}nonempty(e){return this.min(1,Yt.errToObj(e))}trim(){return new q2({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new q2({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new q2({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value{var e;return new Hv({checks:[],typeName:an.ZodString,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...Nn(t)})};function Nst(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=parseInt(t.toFixed(s).replace(".","")),o=parseInt(e.toFixed(s).replace(".",""));return i%o/Math.pow(10,s)}let JC=class nB extends Un{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==It.number){const i=this._getOrReturnCtx(e);return Rt(i,{code:dt.invalid_type,expected:It.number,received:i.parsedType}),En}let r;const s=new Xa;for(const i of this._def.checks)i.kind==="int"?wr.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Rt(r,{code:dt.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.datai.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Rt(r,{code:dt.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Nst(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),Rt(r,{code:dt.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Rt(r,{code:dt.not_finite,message:i.message}),s.dirty()):wr.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Yt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Yt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Yt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Yt.toString(n))}setLimit(e,n,r,s){return new nB({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Yt.toString(s)}]})}_addCheck(e){return new nB({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Yt.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Yt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Yt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Yt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Yt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Yt.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Yt.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Yt.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Yt.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.valuee.kind==="int"||e.kind==="multipleOf"&&wr.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.valuenew JC({checks:[],typeName:an.ZodNumber,coerce:t?.coerce||!1,...Nn(t)});let e_=class rB extends Un{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==It.bigint){const i=this._getOrReturnCtx(e);return Rt(i,{code:dt.invalid_type,expected:It.bigint,received:i.parsedType}),En}let r;const s=new Xa;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.datai.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Rt(r,{code:dt.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Rt(r,{code:dt.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):wr.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Yt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Yt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Yt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Yt.toString(n))}setLimit(e,n,r,s){return new rB({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Yt.toString(s)}]})}_addCheck(e){return new rB({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Yt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Yt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Yt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Yt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Yt.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value{var e;return new e_({checks:[],typeName:an.ZodBigInt,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...Nn(t)})};let t_=class extends Un{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==It.boolean){const r=this._getOrReturnCtx(e);return Rt(r,{code:dt.invalid_type,expected:It.boolean,received:r.parsedType}),En}return sa(e.data)}};t_.create=t=>new t_({typeName:an.ZodBoolean,coerce:t?.coerce||!1,...Nn(t)});let n_=class oge extends Un{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==It.date){const i=this._getOrReturnCtx(e);return Rt(i,{code:dt.invalid_type,expected:It.date,received:i.parsedType}),En}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return Rt(i,{code:dt.invalid_date}),En}const r=new Xa;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()i.value&&(s=this._getOrReturnCtx(e,s),Rt(s,{code:dt.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):wr.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new oge({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Yt.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Yt.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.valuenew n_({checks:[],coerce:t?.coerce||!1,typeName:an.ZodDate,...Nn(t)});let LT=class extends Un{_parse(e){if(this._getType(e)!==It.symbol){const r=this._getOrReturnCtx(e);return Rt(r,{code:dt.invalid_type,expected:It.symbol,received:r.parsedType}),En}return sa(e.data)}};LT.create=t=>new LT({typeName:an.ZodSymbol,...Nn(t)});let r_=class extends Un{_parse(e){if(this._getType(e)!==It.undefined){const r=this._getOrReturnCtx(e);return Rt(r,{code:dt.invalid_type,expected:It.undefined,received:r.parsedType}),En}return sa(e.data)}};r_.create=t=>new r_({typeName:an.ZodUndefined,...Nn(t)});let s_=class extends Un{_parse(e){if(this._getType(e)!==It.null){const r=this._getOrReturnCtx(e);return Rt(r,{code:dt.invalid_type,expected:It.null,received:r.parsedType}),En}return sa(e.data)}};s_.create=t=>new s_({typeName:an.ZodNull,...Nn(t)});let qv=class extends Un{constructor(){super(...arguments),this._any=!0}_parse(e){return sa(e.data)}};qv.create=t=>new qv({typeName:an.ZodAny,...Nn(t)});let Hm=class extends Un{constructor(){super(...arguments),this._unknown=!0}_parse(e){return sa(e.data)}};Hm.create=t=>new Hm({typeName:an.ZodUnknown,...Nn(t)});let Xh=class extends Un{_parse(e){const n=this._getOrReturnCtx(e);return Rt(n,{code:dt.invalid_type,expected:It.never,received:n.parsedType}),En}};Xh.create=t=>new Xh({typeName:an.ZodNever,...Nn(t)});let BT=class extends Un{_parse(e){if(this._getType(e)!==It.undefined){const r=this._getOrReturnCtx(e);return Rt(r,{code:dt.invalid_type,expected:It.void,received:r.parsedType}),En}return sa(e.data)}};BT.create=t=>new BT({typeName:an.ZodVoid,...Nn(t)});let Ey=class YI extends Un{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==It.array)return Rt(n,{code:dt.invalid_type,expected:It.array,received:n.parsedType}),En;if(s.exactLength!==null){const o=n.data.length>s.exactLength.value,a=n.data.lengths.maxLength.value&&(Rt(n,{code:dt.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>s.type._parseAsync(new hf(n,o,n.path,a)))).then(o=>Xa.mergeArray(r,o));const i=[...n.data].map((o,a)=>s.type._parseSync(new hf(n,o,n.path,a)));return Xa.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new YI({...this._def,minLength:{value:e,message:Yt.toString(n)}})}max(e,n){return new YI({...this._def,maxLength:{value:e,message:Yt.toString(n)}})}length(e,n){return new YI({...this._def,exactLength:{value:e,message:Yt.toString(n)}})}nonempty(e){return this.min(1,e)}};Ey.create=(t,e)=>new Ey({type:t,minLength:null,maxLength:null,exactLength:null,typeName:an.ZodArray,...Nn(e)});function Cb(t){if(t instanceof Vl){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=kh.create(Cb(r))}return new Vl({...t._def,shape:()=>e})}else return t instanceof Ey?new Ey({...t._def,type:Cb(t.element)}):t instanceof kh?kh.create(Cb(t.unwrap())):t instanceof Cy?Cy.create(Cb(t.unwrap())):t instanceof h0?h0.create(t.items.map(e=>Cb(e))):t}let Vl=class Cu extends Un{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=wr.objectKeys(e);return this._cached={shape:e,keys:n}}_parse(e){if(this._getType(e)!==It.object){const l=this._getOrReturnCtx(e);return Rt(l,{code:dt.invalid_type,expected:It.object,received:l.parsedType}),En}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Xh&&this._def.unknownKeys==="strip"))for(const l in s.data)o.includes(l)||a.push(l);const c=[];for(const l of o){const u=i[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new hf(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Xh){const l=this._def.unknownKeys;if(l==="passthrough")for(const u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(Rt(s,{code:dt.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const u of a){const d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new hf(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const u of c){const d=await u.key;l.push({key:d,value:await u.value,alwaysSet:u.alwaysSet})}return l}).then(l=>Xa.mergeObjectSync(r,l)):Xa.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return Yt.errToObj,new Cu({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var s,i,o,a;const c=(o=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,n,r).message)!==null&&o!==void 0?o:r.defaultError;return n.code==="unrecognized_keys"?{message:(a=Yt.errToObj(e).message)!==null&&a!==void 0?a:c}:{message:c}}}:{}})}strip(){return new Cu({...this._def,unknownKeys:"strip"})}passthrough(){return new Cu({...this._def,unknownKeys:"passthrough"})}extend(e){return new Cu({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Cu({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:an.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new Cu({...this._def,catchall:e})}pick(e){const n={};return wr.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Cu({...this._def,shape:()=>n})}omit(e){const n={};return wr.objectKeys(this.shape).forEach(r=>{e[r]||(n[r]=this.shape[r])}),new Cu({...this._def,shape:()=>n})}deepPartial(){return Cb(this)}partial(e){const n={};return wr.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}),new Cu({...this._def,shape:()=>n})}required(e){const n={};return wr.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof kh;)i=i._def.innerType;n[r]=i}}),new Cu({...this._def,shape:()=>n})}keyof(){return fge(wr.objectKeys(this.shape))}};Vl.create=(t,e)=>new Vl({shape:()=>t,unknownKeys:"strip",catchall:Xh.create(),typeName:an.ZodObject,...Nn(e)});Vl.strictCreate=(t,e)=>new Vl({shape:()=>t,unknownKeys:"strict",catchall:Xh.create(),typeName:an.ZodObject,...Nn(e)});Vl.lazycreate=(t,e)=>new Vl({shape:t,unknownKeys:"strip",catchall:Xh.create(),typeName:an.ZodObject,...Nn(e)});let i_=class extends Un{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Hu(a.ctx.common.issues));return Rt(n,{code:dt.invalid_union,unionErrors:o}),En}if(n.common.async)return Promise.all(r.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i;const o=[];for(const c of r){const l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(c=>new Hu(c));return Rt(n,{code:dt.invalid_union,unionErrors:a}),En}}get options(){return this._def.options}};i_.create=(t,e)=>new i_({options:t,typeName:an.ZodUnion,...Nn(e)});const XI=t=>t instanceof a_?XI(t.schema):t instanceof sd?XI(t.innerType()):t instanceof c_?[t.value]:t instanceof l3?t.options:t instanceof l_?Object.keys(t.enum):t instanceof u_?XI(t._def.innerType):t instanceof r_?[void 0]:t instanceof s_?[null]:null;let age=class cge extends Un{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==It.object)return Rt(n,{code:dt.invalid_type,expected:It.object,received:n.parsedType}),En;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Rt(n,{code:dt.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),En)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const i of n){const o=XI(i.shape[e]);if(!o)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new cge({typeName:an.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Nn(r)})}};function sB(t,e){const n=xg(t),r=xg(e);if(t===e)return{valid:!0,data:t};if(n===It.object&&r===It.object){const s=wr.objectKeys(e),i=wr.objectKeys(t).filter(a=>s.indexOf(a)!==-1),o={...t,...e};for(const a of i){const c=sB(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(n===It.array&&r===It.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i{if(eB(i)||eB(o))return En;const a=sB(i.value,o.value);return a.valid?((tB(i)||tB(o))&&n.dirty(),{status:n.value,value:a.data}):(Rt(r,{code:dt.invalid_intersection_types}),En)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};o_.create=(t,e,n)=>new o_({left:t,right:e,typeName:an.ZodIntersection,...Nn(n)});let h0=class lge extends Un{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==It.array)return Rt(r,{code:dt.invalid_type,expected:It.array,received:r.parsedType}),En;if(r.data.lengththis._def.items.length&&(Rt(r,{code:dt.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((o,a)=>{const c=this._def.items[a]||this._def.rest;return c?c._parse(new hf(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Xa.mergeArray(n,o)):Xa.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new lge({...this._def,rest:e})}};h0.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new h0({items:t,typeName:an.ZodTuple,rest:null,...Nn(e)})};let uge=class iB extends Un{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==It.object)return Rt(r,{code:dt.invalid_type,expected:It.object,received:r.parsedType}),En;const s=[],i=this._def.keyType,o=this._def.valueType;for(const a in r.data)s.push({key:i._parse(new hf(r,a,r.path,a)),value:o._parse(new hf(r,r.data[a],r.path,a))});return r.common.async?Xa.mergeObjectAsync(n,s):Xa.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Un?new iB({keyType:e,valueType:n,typeName:an.ZodRecord,...Nn(r)}):new iB({keyType:Hv.create(),valueType:e,typeName:an.ZodRecord,...Nn(n)})}},UT=class extends Un{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==It.map)return Rt(r,{code:dt.invalid_type,expected:It.map,received:r.parsedType}),En;const s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new hf(r,a,r.path,[l,"key"])),value:i._parse(new hf(r,c,r.path,[l,"value"]))}));if(r.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const c of o){const l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return En;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const c of o){const l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return En;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};UT.create=(t,e,n)=>new UT({valueType:e,keyType:t,typeName:an.ZodMap,...Nn(n)});let FT=class oB extends Un{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==It.set)return Rt(r,{code:dt.invalid_type,expected:It.set,received:r.parsedType}),En;const s=this._def;s.minSize!==null&&r.data.sizes.maxSize.value&&(Rt(r,{code:dt.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function o(c){const l=new Set;for(const u of c){if(u.status==="aborted")return En;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}const a=[...r.data.values()].map((c,l)=>i._parse(new hf(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,n){return new oB({...this._def,minSize:{value:e,message:Yt.toString(n)}})}max(e,n){return new oB({...this._def,maxSize:{value:e,message:Yt.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};FT.create=(t,e)=>new FT({valueType:t,minSize:null,maxSize:null,typeName:an.ZodSet,...Nn(e)});let dge=class QI extends Un{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==It.function)return Rt(n,{code:dt.invalid_type,expected:It.function,received:n.parsedType}),En;function r(a,c){return DT({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,$T(),XC].filter(l=>!!l),issueData:{code:dt.invalid_arguments,argumentsError:c}})}function s(a,c){return DT({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,$T(),XC].filter(l=>!!l),issueData:{code:dt.invalid_return_type,returnTypeError:c}})}const i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof Kv){const a=this;return sa(async function(...c){const l=new Hu([]),u=await a._def.args.parseAsync(c,i).catch(p=>{throw l.addIssue(r(c,p)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(p=>{throw l.addIssue(s(d,p)),l})})}else{const a=this;return sa(function(...c){const l=a._def.args.safeParse(c,i);if(!l.success)throw new Hu([r(c,l.error)]);const u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new Hu([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new QI({...this._def,args:h0.create(e).rest(Hm.create())})}returns(e){return new QI({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new QI({args:e||h0.create([]).rest(Hm.create()),returns:n||Hm.create(),typeName:an.ZodFunction,...Nn(r)})}},a_=class extends Un{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};a_.create=(t,e)=>new a_({getter:t,typeName:an.ZodLazy,...Nn(e)});let c_=class extends Un{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return Rt(n,{received:n.data,code:dt.invalid_literal,expected:this._def.value}),En}return{status:"valid",value:e.data}}get value(){return this._def.value}};c_.create=(t,e)=>new c_({value:t,typeName:an.ZodLiteral,...Nn(e)});function fge(t,e){return new l3({values:t,typeName:an.ZodEnum,...Nn(e)})}let l3=class aB extends Un{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return Rt(n,{expected:wr.joinValues(r),received:n.parsedType,code:dt.invalid_type}),En}if(this._def.values.indexOf(e.data)===-1){const n=this._getOrReturnCtx(e),r=this._def.values;return Rt(n,{received:n.data,code:dt.invalid_enum_value,options:r}),En}return sa(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e){return aB.create(e)}exclude(e){return aB.create(this.options.filter(n=>!e.includes(n)))}};l3.create=fge;let l_=class extends Un{_parse(e){const n=wr.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==It.string&&r.parsedType!==It.number){const s=wr.objectValues(n);return Rt(r,{expected:wr.joinValues(s),received:r.parsedType,code:dt.invalid_type}),En}if(n.indexOf(e.data)===-1){const s=wr.objectValues(n);return Rt(r,{received:r.data,code:dt.invalid_enum_value,options:s}),En}return sa(e.data)}get enum(){return this._def.values}};l_.create=(t,e)=>new l_({values:t,typeName:an.ZodNativeEnum,...Nn(e)});let Kv=class extends Un{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==It.promise&&n.common.async===!1)return Rt(n,{code:dt.invalid_type,expected:It.promise,received:n.parsedType}),En;const r=n.parsedType===It.promise?n.data:Promise.resolve(n.data);return sa(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Kv.create=(t,e)=>new Kv({type:t,typeName:an.ZodPromise,...Nn(e)});let sd=class extends Un{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===an.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{Rt(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const o=s.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(o).then(a=>this._def.schema._parseAsync({data:a,path:r.path,parent:r})):this._def.schema._parseSync({data:o,path:r.path,parent:r})}if(s.type==="refinement"){const o=a=>{const c=s.refinement(a,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?En:(a.status==="dirty"&&n.dirty(),o(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?En:(a.status==="dirty"&&n.dirty(),o(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!QC(o))return o;const a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>QC(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:n.value,value:a})):o);wr.assertNever(s)}};sd.create=(t,e,n)=>new sd({schema:t,typeName:an.ZodEffects,effect:e,...Nn(n)});sd.createWithPreprocess=(t,e,n)=>new sd({schema:e,effect:{type:"preprocess",transform:t},typeName:an.ZodEffects,...Nn(n)});let kh=class extends Un{_parse(e){return this._getType(e)===It.undefined?sa(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};kh.create=(t,e)=>new kh({innerType:t,typeName:an.ZodOptional,...Nn(e)});let Cy=class extends Un{_parse(e){return this._getType(e)===It.null?sa(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Cy.create=(t,e)=>new Cy({innerType:t,typeName:an.ZodNullable,...Nn(e)});let u_=class extends Un{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===It.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};u_.create=(t,e)=>new u_({innerType:t,typeName:an.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Nn(e)});let jT=class extends Un{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return MT(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Hu(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Hu(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};jT.create=(t,e)=>new jT({innerType:t,typeName:an.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Nn(e)});let zT=class extends Un{_parse(e){if(this._getType(e)!==It.nan){const r=this._getOrReturnCtx(e);return Rt(r,{code:dt.invalid_type,expected:It.nan,received:r.parsedType}),En}return{status:"valid",value:e.data}}};zT.create=t=>new zT({typeName:an.ZodNaN,...Nn(t)});const Pst=Symbol("zod_brand");let hge=class extends Un{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Zz=class pge extends Un{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?En:i.status==="dirty"?(n.dirty(),ige(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?En:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new pge({in:e,out:n,typeName:an.ZodPipeline})}},WT=class extends Un{_parse(e){const n=this._def.innerType._parse(e);return QC(n)&&(n.value=Object.freeze(n.value)),n}};WT.create=(t,e)=>new WT({innerType:t,typeName:an.ZodReadonly,...Nn(e)});const gge=(t,e={},n)=>t?qv.create().superRefine((r,s)=>{var i,o;if(!t(r)){const a=typeof e=="function"?e(r):typeof e=="string"?{message:e}:e,c=(o=(i=a.fatal)!==null&&i!==void 0?i:n)!==null&&o!==void 0?o:!0,l=typeof a=="string"?{message:a}:a;s.addIssue({code:"custom",...l,fatal:c})}}):qv.create(),kst={object:Vl.lazycreate};var an;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(an||(an={}));const Rst=(t,e={message:`Input not instance of ${t.name}`})=>gge(n=>n instanceof t,e),mge=Hv.create,yge=JC.create,Ost=zT.create,$st=e_.create,wge=t_.create,Dst=n_.create,Mst=LT.create,Lst=r_.create,Bst=s_.create,Ust=qv.create,Fst=Hm.create,jst=Xh.create,zst=BT.create,Wst=Ey.create,Vst=Vl.create,Hst=Vl.strictCreate,qst=i_.create,Kst=age.create,Gst=o_.create,Zst=h0.create,Yst=uge.create,Xst=UT.create,Qst=FT.create,Jst=dge.create,eit=a_.create,tit=c_.create,nit=l3.create,rit=l_.create,sit=Kv.create,vee=sd.create,iit=kh.create,oit=Cy.create,ait=sd.createWithPreprocess,cit=Zz.create,lit=()=>mge().optional(),uit=()=>yge().optional(),dit=()=>wge().optional(),fit={string:t=>Hv.create({...t,coerce:!0}),number:t=>JC.create({...t,coerce:!0}),boolean:t=>t_.create({...t,coerce:!0}),bigint:t=>e_.create({...t,coerce:!0}),date:t=>n_.create({...t,coerce:!0})},hit=En;var X=Object.freeze({__proto__:null,defaultErrorMap:XC,setErrorMap:yst,getErrorMap:$T,makeIssue:DT,EMPTY_PATH:wst,addIssueToContext:Rt,ParseStatus:Xa,INVALID:En,DIRTY:ige,OK:sa,isAborted:eB,isDirty:tB,isValid:QC,isAsync:MT,get util(){return wr},get objectUtil(){return J7},ZodParsedType:It,getParsedType:xg,ZodType:Un,ZodString:Hv,ZodNumber:JC,ZodBigInt:e_,ZodBoolean:t_,ZodDate:n_,ZodSymbol:LT,ZodUndefined:r_,ZodNull:s_,ZodAny:qv,ZodUnknown:Hm,ZodNever:Xh,ZodVoid:BT,ZodArray:Ey,ZodObject:Vl,ZodUnion:i_,ZodDiscriminatedUnion:age,ZodIntersection:o_,ZodTuple:h0,ZodRecord:uge,ZodMap:UT,ZodSet:FT,ZodFunction:dge,ZodLazy:a_,ZodLiteral:c_,ZodEnum:l3,ZodNativeEnum:l_,ZodPromise:Kv,ZodEffects:sd,ZodTransformer:sd,ZodOptional:kh,ZodNullable:Cy,ZodDefault:u_,ZodCatch:jT,ZodNaN:zT,BRAND:Pst,ZodBranded:hge,ZodPipeline:Zz,ZodReadonly:WT,custom:gge,Schema:Un,ZodSchema:Un,late:kst,get ZodFirstPartyTypeKind(){return an},coerce:fit,any:Ust,array:Wst,bigint:$st,boolean:wge,date:Dst,discriminatedUnion:Kst,effect:vee,enum:nit,function:Jst,instanceof:Rst,intersection:Gst,lazy:eit,literal:tit,map:Xst,nan:Ost,nativeEnum:rit,never:jst,null:Bst,nullable:oit,number:yge,object:Vst,oboolean:dit,onumber:uit,optional:iit,ostring:lit,pipeline:cit,preprocess:ait,promise:sit,record:Yst,set:Qst,strictObject:Hst,string:mge,symbol:Mst,transformer:vee,tuple:Zst,undefined:Lst,union:qst,unknown:Fst,void:zst,NEVER:hit,ZodIssueCode:dt,quotelessJson:mst,ZodError:Hu});const Es=X.object({message:X.string()});function Nt(t){return X.literal($t[t])}const hk=X.object({serializedMessage:X.string().optional(),accountAddress:X.string(),chainId:X.string(),notBefore:X.string().optional(),domain:X.string(),uri:X.string(),version:X.string(),nonce:X.string(),statement:X.string().optional(),resources:X.array(X.string()).optional(),requestId:X.string().optional(),issuedAt:X.string().optional(),expirationTime:X.string().optional()});X.object({accessList:X.array(X.string()),blockHash:X.string().nullable(),blockNumber:X.string().nullable(),chainId:X.string().or(X.number()),from:X.string(),gas:X.string(),hash:X.string(),input:X.string().nullable(),maxFeePerGas:X.string(),maxPriorityFeePerGas:X.string(),nonce:X.string(),r:X.string(),s:X.string(),to:X.string(),transactionIndex:X.string().nullable(),type:X.string(),v:X.string(),value:X.string()});const pit=X.object({chainId:X.string().or(X.number()),rpcUrl:X.optional(X.string())}),git=X.object({email:X.string().email()}),mit=X.object({otp:X.string()}),yit=X.object({uri:X.string(),preferredAccountType:X.optional(X.string()),chainId:X.optional(X.string().or(X.number())),siwxMessage:X.optional(hk),rpcUrl:X.optional(X.string())}),wit=X.object({chainId:X.optional(X.string().or(X.number())),preferredAccountType:X.optional(X.string()),socialUri:X.optional(X.string()),siwxMessage:X.optional(hk),rpcUrl:X.optional(X.string())}),bit=X.object({provider:X.enum(["google","github","apple","facebook","x","discord"])}),vit=X.object({email:X.string().email()}),xit=X.object({otp:X.string()}),Eit=X.object({otp:X.string()}),Cit=X.object({themeMode:X.optional(X.enum(["light","dark"])),themeVariables:X.optional(X.record(X.string(),X.string().or(X.number()))),w3mThemeVariables:X.optional(X.record(X.string(),X.string()))}),_it=X.object({metadata:X.object({name:X.string(),description:X.string(),url:X.string(),icons:X.array(X.string())}).optional(),sdkVersion:X.string().optional(),sdkType:X.string().optional(),projectId:X.string()}),Sit=X.object({type:X.string()}),Ait=X.object({action:X.enum(["VERIFY_DEVICE","VERIFY_OTP","CONNECT"])}),Iit=X.object({url:X.string()}),Tit=X.object({userName:X.string()}),Nit=X.object({email:X.string().optional().nullable(),address:X.string(),chainId:X.string().or(X.number()),accounts:X.array(X.object({address:X.string(),type:X.enum([_r.ACCOUNT_TYPES.EOA,_r.ACCOUNT_TYPES.SMART_ACCOUNT])})).optional(),userName:X.string().optional().nullable(),preferredAccountType:X.optional(X.string()),signature:X.string().optional(),message:X.string().optional(),siwxMessage:X.optional(hk)}),Pit=X.object({action:X.enum(["VERIFY_PRIMARY_OTP","VERIFY_SECONDARY_OTP"])}),kit=X.object({email:X.string().email().optional().nullable(),address:X.string(),chainId:X.string().or(X.number()),smartAccountDeployed:X.optional(X.boolean()),accounts:X.array(X.object({address:X.string(),type:X.enum([_r.ACCOUNT_TYPES.EOA,_r.ACCOUNT_TYPES.SMART_ACCOUNT])})).optional(),preferredAccountType:X.optional(X.string()),signature:X.string().optional(),message:X.string().optional(),siwxMessage:X.optional(hk)}),Rit=X.object({uri:X.string()}),Oit=X.object({isConnected:X.boolean()}),$it=X.object({chainId:X.string().or(X.number())}),Dit=X.object({chainId:X.string().or(X.number())}),Mit=X.object({newEmail:X.string().email()}),Lit=X.object({smartAccountEnabledNetworks:X.array(X.number())});X.object({address:X.string(),isDeployed:X.boolean()});const Bit=X.object({version:X.string().optional()}),Uit=X.object({type:X.string(),address:X.string()}),Fit=X.any(),jit=X.object({method:X.literal("eth_accounts")}),zit=X.object({method:X.literal("eth_blockNumber")}),Wit=X.object({method:X.literal("eth_call"),params:X.array(X.any())}),Vit=X.object({method:X.literal("eth_chainId")}),Hit=X.object({method:X.literal("eth_estimateGas"),params:X.array(X.any())}),qit=X.object({method:X.literal("eth_feeHistory"),params:X.array(X.any())}),Kit=X.object({method:X.literal("eth_gasPrice")}),Git=X.object({method:X.literal("eth_getAccount"),params:X.array(X.any())}),Zit=X.object({method:X.literal("eth_getBalance"),params:X.array(X.any())}),Yit=X.object({method:X.literal("eth_getBlockByHash"),params:X.array(X.any())}),Xit=X.object({method:X.literal("eth_getBlockByNumber"),params:X.array(X.any())}),Qit=X.object({method:X.literal("eth_getBlockReceipts"),params:X.array(X.any())}),Jit=X.object({method:X.literal("eth_getBlockTransactionCountByHash"),params:X.array(X.any())}),eot=X.object({method:X.literal("eth_getBlockTransactionCountByNumber"),params:X.array(X.any())}),tot=X.object({method:X.literal("eth_getCode"),params:X.array(X.any())}),not=X.object({method:X.literal("eth_getFilterChanges"),params:X.array(X.any())}),rot=X.object({method:X.literal("eth_getFilterLogs"),params:X.array(X.any())}),sot=X.object({method:X.literal("eth_getLogs"),params:X.array(X.any())}),iot=X.object({method:X.literal("eth_getProof"),params:X.array(X.any())}),oot=X.object({method:X.literal("eth_getStorageAt"),params:X.array(X.any())}),aot=X.object({method:X.literal("eth_getTransactionByBlockHashAndIndex"),params:X.array(X.any())}),cot=X.object({method:X.literal("eth_getTransactionByBlockNumberAndIndex"),params:X.array(X.any())}),lot=X.object({method:X.literal("eth_getTransactionByHash"),params:X.array(X.any())}),uot=X.object({method:X.literal("eth_getTransactionCount"),params:X.array(X.any())}),dot=X.object({method:X.literal("eth_getTransactionReceipt"),params:X.array(X.any())}),fot=X.object({method:X.literal("eth_getUncleCountByBlockHash"),params:X.array(X.any())}),hot=X.object({method:X.literal("eth_getUncleCountByBlockNumber"),params:X.array(X.any())}),pot=X.object({method:X.literal("eth_maxPriorityFeePerGas")}),got=X.object({method:X.literal("eth_newBlockFilter")}),mot=X.object({method:X.literal("eth_newFilter"),params:X.array(X.any())}),yot=X.object({method:X.literal("eth_newPendingTransactionFilter")}),wot=X.object({method:X.literal("eth_sendRawTransaction"),params:X.array(X.any())}),bot=X.object({method:X.literal("eth_syncing"),params:X.array(X.any())}),vot=X.object({method:X.literal("eth_uninstallFilter"),params:X.array(X.any())}),xee=X.object({method:X.literal("personal_sign"),params:X.array(X.any())}),xot=X.object({method:X.literal("eth_signTypedData_v4"),params:X.array(X.any())}),Eot=X.object({method:X.literal("eth_sendTransaction"),params:X.array(X.any())}),Cot=X.object({method:X.literal("solana_signMessage"),params:X.object({message:X.string(),pubkey:X.string()})}),_ot=X.object({method:X.literal("solana_signTransaction"),params:X.object({transaction:X.string()})}),Sot=X.object({method:X.literal("solana_signAllTransactions"),params:X.object({transactions:X.array(X.string())})}),Aot=X.object({method:X.literal("solana_signAndSendTransaction"),params:X.object({transaction:X.string(),options:X.object({skipPreflight:X.boolean().optional(),preflightCommitment:X.enum(["processed","confirmed","finalized","recent","single","singleGossip","root","max"]).optional(),maxRetries:X.number().optional(),minContextSlot:X.number().optional()}).optional()})}),Iot=X.object({method:X.literal("wallet_sendCalls"),params:X.array(X.object({chainId:X.string().or(X.number()).optional(),from:X.string().optional(),version:X.string().optional(),capabilities:X.any().optional(),calls:X.array(X.object({to:X.string().startsWith("0x"),data:X.string().startsWith("0x").optional(),value:X.string().optional()}))}))}),Tot=X.object({method:X.literal("wallet_getCallsStatus"),params:X.array(X.string())}),Not=X.object({method:X.literal("wallet_getCapabilities"),params:X.array(X.string().or(X.number()).optional()).optional()}),Pot=X.object({method:X.literal("wallet_grantPermissions"),params:X.array(X.any())}),kot=X.object({method:X.literal("wallet_revokePermissions"),params:X.any()}),Rot=X.object({method:X.literal("wallet_getAssets"),params:X.any()}),Eee=X.object({token:X.string()}),Pt=X.object({id:X.string().optional()}),hD={appEvent:Pt.extend({type:Nt("APP_SWITCH_NETWORK"),payload:pit}).or(Pt.extend({type:Nt("APP_CONNECT_EMAIL"),payload:git})).or(Pt.extend({type:Nt("APP_CONNECT_DEVICE")})).or(Pt.extend({type:Nt("APP_CONNECT_OTP"),payload:mit})).or(Pt.extend({type:Nt("APP_CONNECT_SOCIAL"),payload:yit})).or(Pt.extend({type:Nt("APP_GET_FARCASTER_URI")})).or(Pt.extend({type:Nt("APP_CONNECT_FARCASTER")})).or(Pt.extend({type:Nt("APP_GET_USER"),payload:X.optional(wit)})).or(Pt.extend({type:Nt("APP_GET_SOCIAL_REDIRECT_URI"),payload:bit})).or(Pt.extend({type:Nt("APP_SIGN_OUT")})).or(Pt.extend({type:Nt("APP_IS_CONNECTED"),payload:X.optional(Eee)})).or(Pt.extend({type:Nt("APP_GET_CHAIN_ID")})).or(Pt.extend({type:Nt("APP_GET_SMART_ACCOUNT_ENABLED_NETWORKS")})).or(Pt.extend({type:Nt("APP_INIT_SMART_ACCOUNT")})).or(Pt.extend({type:Nt("APP_SET_PREFERRED_ACCOUNT"),payload:Sit})).or(Pt.extend({type:Nt("APP_RPC_REQUEST"),payload:xee.or(Rot).or(jit).or(zit).or(Wit).or(Vit).or(Hit).or(qit).or(Kit).or(Git).or(Zit).or(Yit).or(Xit).or(Qit).or(Jit).or(eot).or(tot).or(not).or(rot).or(sot).or(iot).or(oot).or(aot).or(cot).or(lot).or(uot).or(dot).or(fot).or(hot).or(pot).or(got).or(mot).or(yot).or(wot).or(bot).or(vot).or(xee).or(xot).or(Eot).or(Cot).or(_ot).or(Sot).or(Aot).or(Tot).or(Iot).or(Not).or(Pot).or(kot).and(X.object({chainId:X.string().or(X.number()).optional(),chainNamespace:X.enum(["eip155","solana","polkadot","bip122","cosmos"]).optional(),rpcUrl:X.string().optional()}))})).or(Pt.extend({type:Nt("APP_UPDATE_EMAIL"),payload:vit})).or(Pt.extend({type:Nt("APP_UPDATE_EMAIL_PRIMARY_OTP"),payload:xit})).or(Pt.extend({type:Nt("APP_UPDATE_EMAIL_SECONDARY_OTP"),payload:Eit})).or(Pt.extend({type:Nt("APP_SYNC_THEME"),payload:Cit})).or(Pt.extend({type:Nt("APP_SYNC_DAPP_DATA"),payload:_it})).or(Pt.extend({type:Nt("APP_RELOAD")})).or(Pt.extend({type:Nt("APP_RPC_ABORT")})),frameEvent:Pt.extend({type:Nt("FRAME_SWITCH_NETWORK_ERROR"),payload:Es}).or(Pt.extend({type:Nt("FRAME_SWITCH_NETWORK_SUCCESS"),payload:Dit})).or(Pt.extend({type:Nt("FRAME_CONNECT_EMAIL_SUCCESS"),payload:Ait})).or(Pt.extend({type:Nt("FRAME_CONNECT_EMAIL_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_GET_FARCASTER_URI_SUCCESS"),payload:Iit})).or(Pt.extend({type:Nt("FRAME_GET_FARCASTER_URI_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_CONNECT_FARCASTER_SUCCESS"),payload:Tit})).or(Pt.extend({type:Nt("FRAME_CONNECT_FARCASTER_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_CONNECT_OTP_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_CONNECT_OTP_SUCCESS")})).or(Pt.extend({type:Nt("FRAME_CONNECT_DEVICE_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_CONNECT_DEVICE_SUCCESS")})).or(Pt.extend({type:Nt("FRAME_CONNECT_SOCIAL_SUCCESS"),payload:Nit})).or(Pt.extend({type:Nt("FRAME_CONNECT_SOCIAL_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_GET_USER_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_GET_USER_SUCCESS"),payload:kit})).or(Pt.extend({type:Nt("FRAME_GET_SOCIAL_REDIRECT_URI_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_GET_SOCIAL_REDIRECT_URI_SUCCESS"),payload:Rit})).or(Pt.extend({type:Nt("FRAME_SIGN_OUT_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_SIGN_OUT_SUCCESS")})).or(Pt.extend({type:Nt("FRAME_IS_CONNECTED_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_IS_CONNECTED_SUCCESS"),payload:Oit})).or(Pt.extend({type:Nt("FRAME_GET_CHAIN_ID_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_GET_CHAIN_ID_SUCCESS"),payload:$it})).or(Pt.extend({type:Nt("FRAME_RPC_REQUEST_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_RPC_REQUEST_SUCCESS"),payload:Fit})).or(Pt.extend({type:Nt("FRAME_SESSION_UPDATE"),payload:Eee})).or(Pt.extend({type:Nt("FRAME_UPDATE_EMAIL_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_UPDATE_EMAIL_SUCCESS"),payload:Pit})).or(Pt.extend({type:Nt("FRAME_UPDATE_EMAIL_PRIMARY_OTP_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_UPDATE_EMAIL_PRIMARY_OTP_SUCCESS")})).or(Pt.extend({type:Nt("FRAME_UPDATE_EMAIL_SECONDARY_OTP_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_UPDATE_EMAIL_SECONDARY_OTP_SUCCESS"),payload:Mit})).or(Pt.extend({type:Nt("FRAME_SYNC_THEME_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_SYNC_THEME_SUCCESS")})).or(Pt.extend({type:Nt("FRAME_SYNC_DAPP_DATA_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_SYNC_DAPP_DATA_SUCCESS")})).or(Pt.extend({type:Nt("FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS"),payload:Lit})).or(Pt.extend({type:Nt("FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_INIT_SMART_ACCOUNT_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_SET_PREFERRED_ACCOUNT_SUCCESS"),payload:Uit})).or(Pt.extend({type:Nt("FRAME_SET_PREFERRED_ACCOUNT_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_READY"),payload:Bit})).or(Pt.extend({type:Nt("FRAME_RELOAD_ERROR"),payload:Es})).or(Pt.extend({type:Nt("FRAME_RELOAD_SUCCESS")}))};function pD(t,e={}){return typeof e?.type=="string"&&e?.type?.includes(t)}function Oot({projectId:t,chainId:e,enableLogger:n,rpcUrl:r=ye.BLOCKCHAIN_API_RPC_URL,enableCloudAuthAccount:s=!1}){const i=new URL(UBe);return i.searchParams.set("projectId",t),i.searchParams.set("chainId",String(e)),i.searchParams.set("version",jBe),i.searchParams.set("enableLogger",String(n)),i.searchParams.set("rpcUrl",r),s&&i.searchParams.set("enableCloudAuthAccount","true"),i.toString()}class $ot{constructor({projectId:e,isAppClient:n=!1,chainId:r="eip155:1",enableLogger:s=!0,enableCloudAuthAccount:i=!1,rpcUrl:o=ye.BLOCKCHAIN_API_RPC_URL}){if(this.iframe=null,this.iframeIsReady=!1,this.initFrame=()=>{const a=document.getElementById("w3m-iframe");this.iframe&&!a&&document.body.appendChild(this.iframe)},this.events={registerFrameEventHandler:(a,c,l)=>{function u({data:d}){if(!pD($t.FRAME_EVENT_KEY,d))return;const f=hD.frameEvent.safeParse(d);if(!f.success){console.warn("W3mFrame: invalid frame event",f.error.message);return}f.data?.id===a&&(c(f.data),window.removeEventListener("message",u))}kc.isClient&&(window.addEventListener("message",u),l.addEventListener("abort",()=>{window.removeEventListener("message",u)}))},onFrameEvent:a=>{kc.isClient&&window.addEventListener("message",({data:c})=>{if(!pD($t.FRAME_EVENT_KEY,c))return;const l=hD.frameEvent.safeParse(c);l.success?a(l.data):console.warn("W3mFrame: invalid frame event",l.error.message)})},onAppEvent:a=>{kc.isClient&&window.addEventListener("message",({data:c})=>{if(!pD($t.APP_EVENT_KEY,c))return;const l=hD.appEvent.safeParse(c);l.success||console.warn("W3mFrame: invalid app event",l.error.message),a(c)})},postAppEvent:a=>{if(kc.isClient){if(!this.iframe?.contentWindow)throw new Error("W3mFrame: iframe is not set");this.iframe.contentWindow.postMessage(a,"*")}},postFrameEvent:a=>{if(kc.isClient){if(!parent)throw new Error("W3mFrame: parent is not set");parent.postMessage(a,"*")}}},this.projectId=e,this.frameLoadPromise=new Promise((a,c)=>{this.frameLoadPromiseResolver={resolve:a,reject:c}}),this.rpcUrl=o,n&&(this.frameLoadPromise=new Promise((a,c)=>{this.frameLoadPromiseResolver={resolve:a,reject:c}}),kc.isClient)){const a=document.createElement("iframe");a.id="w3m-iframe",a.src=Oot({projectId:e,chainId:r,enableLogger:s,rpcUrl:this.rpcUrl,enableCloudAuthAccount:i}),a.name="w3m-secure-iframe",a.style.position="fixed",a.style.zIndex="999999",a.style.display="none",a.style.border="none",a.style.animationDelay="0s, 50ms",a.style.borderBottomLeftRadius="clamp(0px, var(--wui-border-radius-l), 44px)",a.style.borderBottomRightRadius="clamp(0px, var(--wui-border-radius-l), 44px)",this.iframe=a,this.iframe.onerror=()=>{this.frameLoadPromiseResolver?.reject("Unable to load email login dependency")},this.events.onFrameEvent(c=>{c.type==="@w3m-frame/READY"&&(this.iframeIsReady=!0,this.frameLoadPromiseResolver?.resolve(void 0))})}}get networks(){const e=["eip155:1","eip155:5","eip155:11155111","eip155:10","eip155:420","eip155:42161","eip155:421613","eip155:137","eip155:80001","eip155:42220","eip155:1313161554","eip155:1313161555","eip155:56","eip155:97","eip155:43114","eip155:43113","eip155:324","eip155:280","eip155:100","eip155:8453","eip155:84531","eip155:84532","eip155:7777777","eip155:999","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"].map(n=>({[n]:{rpcUrl:`${this.rpcUrl}/v1/?chainId=${n}&projectId=${this.projectId}`,chainId:n}}));return Object.assign({},...e)}}class Dot{constructor(e){const n=sx({level:FBe}),{logger:r,chunkLoggerController:s}=gz({opts:n});this.logger=Mo(r,this.constructor.name),this.chunkLoggerController=s,typeof window<"u"&&this.chunkLoggerController?.downloadLogsBlobInBrowser&&(window.downloadAppKitLogsBlob||(window.downloadAppKitLogsBlob={}),window.downloadAppKitLogsBlob.sdk=()=>{this.chunkLoggerController?.downloadLogsBlobInBrowser&&this.chunkLoggerController.downloadLogsBlobInBrowser({projectId:e})})}}class bge{constructor({projectId:e,chainId:n,enableLogger:r=!0,onTimeout:s,abortController:i,getActiveCaipNetwork:o,getCaipNetworks:a,enableCloudAuthAccount:c}){this.openRpcRequests=[],this.isInitialized=!1,r&&(this.w3mLogger=new Dot(e)),this.abortController=i,this.getActiveCaipNetwork=o,this.getCaipNetworks=a;const l=this.getRpcUrl(n);this.w3mFrame=new $ot({projectId:e,isAppClient:!0,chainId:n,enableLogger:r,rpcUrl:l,enableCloudAuthAccount:c}),this.onTimeout=s,this.getLoginEmailUsed()&&this.createFrame()}async createFrame(){this.w3mFrame.initFrame(),this.initPromise=new Promise(e=>{this.w3mFrame.events.onFrameEvent(n=>{n.type===$t.FRAME_READY&&setTimeout(()=>{e()},500)})}),await this.initPromise,this.isInitialized=!0,this.initPromise=void 0}async init(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}await this.createFrame()}}getLoginEmailUsed(){return!!$i.get($t.EMAIL_LOGIN_USED_KEY)}getEmail(){return $i.get($t.EMAIL)}getUsername(){return $i.get($t.SOCIAL_USERNAME)}async reload(){try{await this.appEvent({type:$t.APP_RELOAD})}catch(e){throw this.w3mLogger?.logger.error({error:e},"Error reloading iframe"),e}}async connectEmail(e){try{kc.checkIfAllowedToTriggerEmail(),await this.init();const n=await this.appEvent({type:$t.APP_CONNECT_EMAIL,payload:e});return this.setNewLastEmailLoginTime(),n}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error connecting email"),n}}async connectDevice(){try{return this.appEvent({type:$t.APP_CONNECT_DEVICE})}catch(e){throw this.w3mLogger?.logger.error({error:e},"Error connecting device"),e}}async connectOtp(e){try{return this.appEvent({type:$t.APP_CONNECT_OTP,payload:e})}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error connecting otp"),n}}async isConnected(){try{if(!this.getLoginEmailUsed())return{isConnected:!1};const e=await this.appEvent({type:$t.APP_IS_CONNECTED});return e?.isConnected||this.deleteAuthLoginCache(),e}catch(e){throw this.deleteAuthLoginCache(),this.w3mLogger?.logger.error({error:e},"Error checking connection"),e}}async getChainId(){try{const e=await this.appEvent({type:$t.APP_GET_CHAIN_ID});return this.setLastUsedChainId(e.chainId),e}catch(e){throw this.w3mLogger?.logger.error({error:e},"Error getting chain id"),e}}async getSocialRedirectUri(e){try{return await this.init(),this.appEvent({type:$t.APP_GET_SOCIAL_REDIRECT_URI,payload:e})}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error getting social redirect uri"),n}}async updateEmail(e){try{const n=await this.appEvent({type:$t.APP_UPDATE_EMAIL,payload:e});return this.setNewLastEmailLoginTime(),n}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error updating email"),n}}async updateEmailPrimaryOtp(e){try{return this.appEvent({type:$t.APP_UPDATE_EMAIL_PRIMARY_OTP,payload:e})}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error updating email primary otp"),n}}async updateEmailSecondaryOtp(e){try{const n=await this.appEvent({type:$t.APP_UPDATE_EMAIL_SECONDARY_OTP,payload:e});return this.setLoginSuccess(n.newEmail),n}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error updating email secondary otp"),n}}async syncTheme(e){try{return this.appEvent({type:$t.APP_SYNC_THEME,payload:e})}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error syncing theme"),n}}async syncDappData(e){try{return this.appEvent({type:$t.APP_SYNC_DAPP_DATA,payload:e})}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error syncing dapp data"),n}}async getSmartAccountEnabledNetworks(){try{const e=await this.appEvent({type:$t.APP_GET_SMART_ACCOUNT_ENABLED_NETWORKS});return this.persistSmartAccountEnabledNetworks(e.smartAccountEnabledNetworks),e}catch(e){throw this.persistSmartAccountEnabledNetworks([]),this.w3mLogger?.logger.error({error:e},"Error getting smart account enabled networks"),e}}async setPreferredAccount(e){try{return this.appEvent({type:$t.APP_SET_PREFERRED_ACCOUNT,payload:{type:e}})}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error setting preferred account"),n}}async connect(e){if(e?.socialUri)try{await this.init();const n=this.getRpcUrl(e.chainId),r=await this.appEvent({type:$t.APP_CONNECT_SOCIAL,payload:{uri:e.socialUri,preferredAccountType:e.preferredAccountType,chainId:e.chainId,siwxMessage:e.siwxMessage,rpcUrl:n}});return r.userName&&this.setSocialLoginSuccess(r.userName),this.setLoginSuccess(r.email),this.setLastUsedChainId(r.chainId),this.user=r,r}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error connecting social"),n}else try{const n=e?.chainId||this.getLastUsedChainId()||1,r=await this.getUser({chainId:n,preferredAccountType:e?.preferredAccountType,siwxMessage:e?.siwxMessage,rpcUrl:this.getRpcUrl(n)});return this.setLoginSuccess(r.email),this.setLastUsedChainId(r.chainId),this.user=r,r}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error connecting"),n}}async getUser(e){try{await this.init();const n=e?.chainId||this.getLastUsedChainId()||1,r=await this.appEvent({type:$t.APP_GET_USER,payload:{...e,chainId:n,rpcUrl:this.getRpcUrl(n)}});return this.user=r,r}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error connecting"),n}}async connectSocial({uri:e,chainId:n,preferredAccountType:r}){try{await this.init();const s=this.getRpcUrl(n),i=await this.appEvent({type:$t.APP_CONNECT_SOCIAL,payload:{uri:e,chainId:n,rpcUrl:s,preferredAccountType:r}});return i.userName&&this.setSocialLoginSuccess(i.userName),i}catch(s){throw this.w3mLogger?.logger.error({error:s},"Error connecting social"),s}}async getFarcasterUri(){try{return await this.init(),await this.appEvent({type:$t.APP_GET_FARCASTER_URI})}catch(e){throw this.w3mLogger?.logger.error({error:e},"Error getting farcaster uri"),e}}async connectFarcaster(){try{const e=await this.appEvent({type:$t.APP_CONNECT_FARCASTER});return e.userName&&this.setSocialLoginSuccess(e.userName),e}catch(e){throw this.w3mLogger?.logger.error({error:e},"Error connecting farcaster"),e}}async switchNetwork({chainId:e}){try{const n=this.getRpcUrl(e),r=await this.appEvent({type:$t.APP_SWITCH_NETWORK,payload:{chainId:e,rpcUrl:n}});return this.setLastUsedChainId(r.chainId),r}catch(n){throw this.w3mLogger?.logger.error({error:n},"Error switching network"),n}}async disconnect(){try{return this.deleteAuthLoginCache(),await new Promise(async n=>{const r=setTimeout(()=>{n()},3e3);await this.appEvent({type:$t.APP_SIGN_OUT}),clearTimeout(r),n()})}catch(e){throw this.w3mLogger?.logger.error({error:e},"Error disconnecting"),e}}async request(e){const n=e;try{if(_r.GET_CHAIN_ID===e.method)return this.getLastUsedChainId();const r=e.chainNamespace||"eip155",s=this.getActiveCaipNetwork(r)?.id;n.chainNamespace=r,n.chainId=s,n.rpcUrl=this.getRpcUrl(s),this.rpcRequestHandler?.(e);const i=await this.appEvent({type:$t.APP_RPC_REQUEST,payload:n});return this.rpcSuccessHandler?.(i,n),i}catch(r){throw this.rpcErrorHandler?.(r,n),this.w3mLogger?.logger.error({error:r},"Error requesting"),r}}onRpcRequest(e){this.rpcRequestHandler=e}onRpcSuccess(e){this.rpcSuccessHandler=e}onRpcError(e){this.rpcErrorHandler=e}onIsConnected(e){this.w3mFrame.events.onFrameEvent(n=>{n.type===$t.FRAME_IS_CONNECTED_SUCCESS&&n.payload.isConnected&&e()})}onNotConnected(e){this.w3mFrame.events.onFrameEvent(n=>{n.type===$t.FRAME_IS_CONNECTED_ERROR&&e(),n.type===$t.FRAME_IS_CONNECTED_SUCCESS&&!n.payload.isConnected&&e()})}onConnect(e){this.w3mFrame.events.onFrameEvent(n=>{n.type===$t.FRAME_GET_USER_SUCCESS&&e(n.payload)})}onSocialConnected(e){this.w3mFrame.events.onFrameEvent(n=>{n.type===$t.FRAME_CONNECT_SOCIAL_SUCCESS&&e(n.payload)})}async getCapabilities(){try{return await this.request({method:"wallet_getCapabilities"})||{}}catch{return{}}}onSetPreferredAccount(e){this.w3mFrame.events.onFrameEvent(n=>{n.type===$t.FRAME_SET_PREFERRED_ACCOUNT_SUCCESS?e(n.payload):n.type===$t.FRAME_SET_PREFERRED_ACCOUNT_ERROR&&e({type:_r.ACCOUNT_TYPES.EOA})})}getAvailableChainIds(){return Object.keys(this.w3mFrame.networks)}async rejectRpcRequests(){try{await Promise.all(this.openRpcRequests.map(async({abortController:e,method:n})=>{_r.SAFE_RPC_METHODS.includes(n)||e.abort(),await this.appEvent({type:$t.APP_RPC_ABORT})})),this.openRpcRequests=[]}catch(e){this.w3mLogger?.logger.error({error:e},"Error aborting RPC request")}}async appEvent(e){let n,r;function s(c){return c.replace("@w3m-app/","")}const i=[$t.APP_SYNC_DAPP_DATA,$t.APP_SYNC_THEME,$t.APP_SET_PREFERRED_ACCOUNT],o=s(e.type);return!this.w3mFrame.iframeIsReady&&!i.includes(e.type)&&(r=setTimeout(()=>{this.onTimeout?.("iframe_load_failed"),this.abortController.abort()},2e4)),await this.w3mFrame.frameLoadPromise,clearTimeout(r),[$t.APP_CONNECT_EMAIL,$t.APP_CONNECT_DEVICE,$t.APP_CONNECT_OTP,$t.APP_CONNECT_SOCIAL,$t.APP_GET_SOCIAL_REDIRECT_URI].map(s).includes(o)&&(n=setTimeout(()=>{this.onTimeout?.("iframe_request_timeout"),this.abortController.abort()},12e4)),new Promise((c,l)=>{const u=Math.random().toString(36).substring(7);this.w3mLogger?.logger.info?.({event:e,id:u},"Sending app event"),this.w3mFrame.events.postAppEvent({...e,id:u});const d=new AbortController;if(o==="RPC_REQUEST"){const p=e;this.openRpcRequests=[...this.openRpcRequests,{...p.payload,abortController:d}]}d.signal.addEventListener("abort",()=>{o==="RPC_REQUEST"?l(new Error("Request was aborted")):o!=="GET_FARCASTER_URI"&&l(new Error("Something went wrong"))});function f(p,m){p.id===u&&(m?.logger.info?.({framEvent:p,id:u},"Received frame response"),p.type===`@w3m-frame/${o}_SUCCESS`?(n&&clearTimeout(n),r&&clearTimeout(r),"payload"in p&&c(p.payload),c(void 0)):p.type===`@w3m-frame/${o}_ERROR`&&(n&&clearTimeout(n),r&&clearTimeout(r),"payload"in p&&l(new Error(p.payload?.message||"An error occurred")),l(new Error("An error occurred"))))}this.w3mFrame.events.registerFrameEventHandler(u,p=>f(p,this.w3mLogger),this.abortController.signal)})}setNewLastEmailLoginTime(){$i.set($t.LAST_EMAIL_LOGIN_TIME,Date.now().toString())}setSocialLoginSuccess(e){$i.set($t.SOCIAL_USERNAME,e)}setLoginSuccess(e){e&&$i.set($t.EMAIL,e),$i.set($t.EMAIL_LOGIN_USED_KEY,"true"),$i.delete($t.LAST_EMAIL_LOGIN_TIME)}deleteAuthLoginCache(){$i.delete($t.EMAIL_LOGIN_USED_KEY),$i.delete($t.EMAIL),$i.delete($t.LAST_USED_CHAIN_KEY),$i.delete($t.SOCIAL_USERNAME)}setLastUsedChainId(e){e&&$i.set($t.LAST_USED_CHAIN_KEY,String(e))}getLastUsedChainId(){const e=$i.get($t.LAST_USED_CHAIN_KEY)??void 0,n=Number(e);return isNaN(n)?e:n}persistSmartAccountEnabledNetworks(e){$i.set($t.SMART_ACCOUNT_ENABLED_NETWORKS,e.join(","))}getRpcUrl(e){let n=e===void 0?void 0:"eip155";typeof e=="string"&&(e.includes(":")?n=Yo.parseCaipNetworkId(e)?.chainNamespace:Number.isInteger(Number(e))?n="eip155":n="solana");const r=this.getCaipNetworks(n);return(e?r.find(i=>String(i.id)===String(e)||i.caipNetworkId===e):r[0])?.rpcUrls.default.http?.[0]}}class qm{constructor(){}static getInstance({projectId:e,chainId:n,enableLogger:r,onTimeout:s,abortController:i,getActiveCaipNetwork:o,getCaipNetworks:a}){return qm.instance||(qm.instance=new bge({projectId:e,chainId:n,enableLogger:r,onTimeout:s,abortController:i,getActiveCaipNetwork:o,getCaipNetworks:a,enableCloudAuthAccount:!!_e.state.remoteFeatures?.emailCapture})),qm.instance}}var Cee={};const Am={ACCOUNT_TABS:[{label:"Tokens"},{label:"NFTs"},{label:"Activity"}],SECURE_SITE_ORIGIN:(typeof process<"u"&&typeof Cee<"u"?Cee.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},pf={filterOutDuplicatesByRDNS(t){const e=_e.state.enableEIP6963?ke.state.connectors:[],n=Ge.getRecentWallets(),r=e.map(a=>a.info?.rdns).filter(Boolean),s=n.map(a=>a.rdns).filter(Boolean),i=r.concat(s);if(i.includes("io.metamask.mobile")&&De.isMobile()){const a=i.indexOf("io.metamask.mobile");i[a]="io.metamask"}return t.filter(a=>!(a?.rdns&&i.includes(String(a.rdns))||!a?.rdns&&e.some(l=>l.name===a.name)))},filterOutDuplicatesByIds(t){const e=ke.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),n=Ge.getRecentWallets(),r=e.map(a=>a.explorerId),s=n.map(a=>a.id),i=r.concat(s);return t.filter(a=>!i.includes(a?.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=ke.state,{featuredWalletIds:n}=_e.state,r=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>(a.info?.rdns&&(o[a.info.rdns]=!0),o),{});return t.map(o=>({...o,installed:!!o.rdns&&!!r[o.rdns??""]})).sort((o,a)=>{const c=Number(a.installed)-Number(o.installed);if(c!==0)return c;if(n?.length){const l=n.indexOf(o.id),u=n.indexOf(a.id);if(l!==-1&&u!==-1)return l-u;if(l!==-1)return-1;if(u!==-1)return 1}return 0})},getConnectOrderMethod(t,e){const n=t?.connectMethodsOrder||_e.state.features?.connectMethodsOrder,r=e||ke.state.connectors;if(n)return n;const{injected:s,announced:i}=qu.getConnectorsByType(r,mt.state.recommended,mt.state.featured),o=s.filter(qu.showConnector),a=i.filter(qu.showConnector);return o.length||a.length?["wallet","email","social"]:Am.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&mt.state.excludedWallets.some(r=>r.rdns===t.rdns),n=!!t.name&&mt.state.excludedWallets.some(r=>Jn.isLowerCaseMatch(r.name,t.name));return e||n},markWalletsWithDisplayIndex(t){return t.map((e,n)=>({...e,display_index:n}))}},qu={getConnectorsByType(t,e,n){const{customWallets:r}=_e.state,s=Ge.getRecentWallets(),i=pf.filterOutDuplicateWallets(e),o=pf.filterOutDuplicateWallets(n),a=t.filter(d=>d.type==="MULTI_CHAIN"),c=t.filter(d=>d.type==="ANNOUNCED"),l=t.filter(d=>d.type==="INJECTED"),u=t.filter(d=>d.type==="EXTERNAL");return{custom:r,recent:s,external:u,multiChain:a,announced:c,injected:l,recommended:i,featured:o}},showConnector(t){const e=t.info?.rdns,n=!!e&&mt.state.excludedWallets.some(s=>!!s.rdns&&s.rdns===e),r=!!t.name&&mt.state.excludedWallets.some(s=>Jn.isLowerCaseMatch(s.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!De.isMobile()||De.isMobile()&&!e&&!Ue.checkInstalled())||n||r)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(n||r))},getIsConnectedWithWC(){return Array.from(G.state.chains.values()).some(n=>ke.getConnectorId(n.namespace)===ye.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:n,recent:r,announced:s,injected:i,multiChain:o,external:a,overriddenConnectors:c=_e.state.features?.connectorTypeOrder??[]}){const d=[{type:"walletConnect",isEnabled:_e.state.enableWalletConnect},{type:"recent",isEnabled:r.length>0},{type:"injected",isEnabled:[...i,...s,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:n&&n.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:t.length>0}].filter(y=>y.isEnabled),f=new Set(d.map(y=>y.type)),p=c.filter(y=>f.has(y)).map(y=>({type:y,isEnabled:!0})),m=d.filter(({type:y})=>!p.some(({type:v})=>v===y));return Array.from(new Set([...p,...m].map(({type:y})=>y)))},getAuthName({email:t,socialUsername:e,socialProvider:n}){return e?n&&n==="discord"&&e.endsWith("0")?e.slice(0,-1):e:t.length>30?`${t.slice(0,-3)}...`:t},async fetchProviderData(t){try{if(t.name==="Browser Wallet"&&!De.isMobile())return{accounts:[],chainId:void 0};if(t.id===ye.CONNECTOR_ID.AUTH)return{accounts:[],chainId:void 0};const[e,n]=await Promise.all([t.provider?.request({method:"eth_accounts"}),t.provider?.request({method:"eth_chainId"}).then(r=>Number(r))]);return{accounts:e,chainId:n}}catch(e){return console.warn(`Failed to fetch provider data for ${t.name}`,e),{accounts:[],chainId:void 0}}}},VT={interpolate(t,e,n){if(t.length!==2||e.length!==2)throw new Error("inputRange and outputRange must be an array of length 2");const r=t[0]||0,s=t[1]||0,i=e[0]||0,o=e[1]||0;return ns?o:(o-i)/(s-r)*(n-r)+i}};/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const JI=globalThis,Yz=JI.ShadowRoot&&(JI.ShadyCSS===void 0||JI.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Xz=Symbol(),_ee=new WeakMap;let vge=class{constructor(e,n,r){if(this._$cssResult$=!0,r!==Xz)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=n}get styleSheet(){let e=this.o;const n=this.t;if(Yz&&e===void 0){const r=n!==void 0&&n.length===1;r&&(e=_ee.get(n)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),r&&_ee.set(n,e))}return e}toString(){return this.cssText}};const hl=t=>new vge(typeof t=="string"?t:t+"",void 0,Xz),it=(t,...e)=>{const n=t.length===1?t[0]:e.reduce((r,s,i)=>r+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+t[i+1],t[0]);return new vge(n,t,Xz)},Mot=(t,e)=>{if(Yz)t.adoptedStyleSheets=e.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of e){const r=document.createElement("style"),s=JI.litNonce;s!==void 0&&r.setAttribute("nonce",s),r.textContent=n.cssText,t.appendChild(r)}},See=Yz?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let n="";for(const r of e.cssRules)n+=r.cssText;return hl(n)})(t):t;/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const{is:Lot,defineProperty:Bot,getOwnPropertyDescriptor:Uot,getOwnPropertyNames:Fot,getOwnPropertySymbols:jot,getPrototypeOf:zot}=Object,pk=globalThis,Aee=pk.trustedTypes,Wot=Aee?Aee.emptyScript:"",Vot=pk.reactiveElementPolyfillSupport,PE=(t,e)=>t,HT={toAttribute(t,e){switch(e){case Boolean:t=t?Wot:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,e){let n=t;switch(e){case Boolean:n=t!==null;break;case Number:n=t===null?null:Number(t);break;case Object:case Array:try{n=JSON.parse(t)}catch{n=null}}return n}},Qz=(t,e)=>!Lot(t,e),Iee={attribute:!0,type:String,converter:HT,reflect:!1,useDefault:!1,hasChanged:Qz};Symbol.metadata??=Symbol("metadata"),pk.litPropertyMetadata??=new WeakMap;let _b=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,n=Iee){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(e,n),!n.noAccessor){const r=Symbol(),s=this.getPropertyDescriptor(e,r,n);s!==void 0&&Bot(this.prototype,e,s)}}static getPropertyDescriptor(e,n,r){const{get:s,set:i}=Uot(this.prototype,e)??{get(){return this[n]},set(o){this[n]=o}};return{get:s,set(o){const a=s?.call(this);i?.call(this,o),this.requestUpdate(e,a,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Iee}static _$Ei(){if(this.hasOwnProperty(PE("elementProperties")))return;const e=zot(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(PE("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(PE("properties"))){const n=this.properties,r=[...Fot(n),...jot(n)];for(const s of r)this.createProperty(s,n[s])}const e=this[Symbol.metadata];if(e!==null){const n=litPropertyMetadata.get(e);if(n!==void 0)for(const[r,s]of n)this.elementProperties.set(r,s)}this._$Eh=new Map;for(const[n,r]of this.elementProperties){const s=this._$Eu(n,r);s!==void 0&&this._$Eh.set(s,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const n=[];if(Array.isArray(e)){const r=new Set(e.flat(1/0).reverse());for(const s of r)n.unshift(See(s))}else e!==void 0&&n.push(See(e));return n}static _$Eu(e,n){const r=n.attribute;return r===!1?void 0:typeof r=="string"?r:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,n=this.constructor.elementProperties;for(const r of n.keys())this.hasOwnProperty(r)&&(e.set(r,this[r]),delete this[r]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Mot(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,n,r){this._$AK(e,r)}_$ET(e,n){const r=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,r);if(s!==void 0&&r.reflect===!0){const i=(r.converter?.toAttribute!==void 0?r.converter:HT).toAttribute(n,r.type);this._$Em=e,i==null?this.removeAttribute(s):this.setAttribute(s,i),this._$Em=null}}_$AK(e,n){const r=this.constructor,s=r._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const i=r.getPropertyOptions(s),o=typeof i.converter=="function"?{fromAttribute:i.converter}:i.converter?.fromAttribute!==void 0?i.converter:HT;this._$Em=s;const a=o.fromAttribute(n,i.type);this[s]=a??this._$Ej?.get(s)??a,this._$Em=null}}requestUpdate(e,n,r){if(e!==void 0){const s=this.constructor,i=this[e];if(r??=s.getPropertyOptions(e),!((r.hasChanged??Qz)(i,n)||r.useDefault&&r.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(s._$Eu(e,r))))return;this.C(e,n,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,n,{useDefault:r,reflect:s,wrapped:i},o){r&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,o??n??this[e]),i!==!0||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||r||(n=void 0),this._$AL.set(e,n)),s===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(n){Promise.reject(n)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[s,i]of this._$Ep)this[s]=i;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[s,i]of r){const{wrapped:o}=i,a=this[s];o!==!0||this._$AL.has(s)||a===void 0||this.C(s,void 0,i,a)}}let e=!1;const n=this._$AL;try{e=this.shouldUpdate(n),e?(this.willUpdate(n),this._$EO?.forEach(r=>r.hostUpdate?.()),this.update(n)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(n)}willUpdate(e){}_$AE(e){this._$EO?.forEach(n=>n.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(n=>this._$ET(n,this[n])),this._$EM()}updated(e){}firstUpdated(e){}};_b.elementStyles=[],_b.shadowRootOptions={mode:"open"},_b[PE("elementProperties")]=new Map,_b[PE("finalized")]=new Map,Vot?.({ReactiveElement:_b}),(pk.reactiveElementVersions??=[]).push("2.1.1");/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const Jz=globalThis,qT=Jz.trustedTypes,Tee=qT?qT.createPolicy("lit-html",{createHTML:t=>t}):void 0,xge="$lit$",Eg=`lit$${Math.random().toFixed(9).slice(2)}$`,Ege="?"+Eg,Hot=`<${Ege}>`,_y=document,d_=()=>_y.createComment(""),f_=t=>t===null||typeof t!="object"&&typeof t!="function",eW=Array.isArray,qot=t=>eW(t)||typeof t?.[Symbol.iterator]=="function",gD=`[ +\f\r]`,y2=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Nee=/-->/g,Pee=/>/g,tm=RegExp(`>|${gD}(?:([^\\s"'>=/]+)(${gD}*=${gD}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),kee=/'/g,Ree=/"/g,Cge=/^(?:script|style|textarea|title)$/i,_ge=t=>(e,...n)=>({_$litType$:t,strings:e,values:n}),K=_ge(1),Kr=_ge(2),Qh=Symbol.for("lit-noChange"),Ds=Symbol.for("lit-nothing"),Oee=new WeakMap,Im=_y.createTreeWalker(_y,129);function Sge(t,e){if(!eW(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return Tee!==void 0?Tee.createHTML(e):e}const Kot=(t,e)=>{const n=t.length-1,r=[];let s,i=e===2?"":e===3?"":"",o=y2;for(let a=0;a"?(o=s??y2,d=-1):u[1]===void 0?d=-2:(d=o.lastIndex-u[2].length,l=u[1],o=u[3]===void 0?tm:u[3]==='"'?Ree:kee):o===Ree||o===kee?o=tm:o===Nee||o===Pee?o=y2:(o=tm,s=void 0);const p=o===tm&&t[a+1].startsWith("/>")?" ":"";i+=o===y2?c+Hot:d>=0?(r.push(l),c.slice(0,d)+xge+c.slice(d)+Eg+p):c+Eg+(d===-2?a:p)}return[Sge(t,i+(t[n]||"")+(e===2?"":e===3?"":"")),r]};let cB=class Age{constructor({strings:e,_$litType$:n},r){let s;this.parts=[];let i=0,o=0;const a=e.length-1,c=this.parts,[l,u]=Kot(e,n);if(this.el=Age.createElement(l,r),Im.currentNode=this.el.content,n===2||n===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(s=Im.nextNode())!==null&&c.length0){s.textContent=qT?qT.emptyScript:"";for(let p=0;p2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=Ds}_$AI(e,n=this,r,s){const i=this.strings;let o=!1;if(i===void 0)e=Gv(this,e,n,0),o=!f_(e)||e!==this._$AH&&e!==Qh,o&&(this._$AH=e);else{const a=e;let c,l;for(e=i[0],c=0;c{const r=n?.renderBefore??e;let s=r._$litPart$;if(s===void 0){const i=n?.renderBefore??null;r._$litPart$=s=new u3(e.insertBefore(d_(),i),i,void 0,n??{})}return s._$AI(t),s};/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const tW=globalThis;let He=class extends _b{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const n=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=eat(n,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Qh}};He._$litElement$=!0,He.finalized=!0,tW.litElementHydrateSupport?.({LitElement:He});const tat=tW.litElementPolyfillSupport;tat?.({LitElement:He});(tW.litElementVersions??=[]).push("4.2.1");let kE,Qg,Jg;function PRt(t,e){kE=document.createElement("style"),Qg=document.createElement("style"),Jg=document.createElement("style"),kE.textContent=fv(t).core.cssText,Qg.textContent=fv(t).dark.cssText,Jg.textContent=fv(t).light.cssText,document.head.appendChild(kE),document.head.appendChild(Qg),document.head.appendChild(Jg),Ige(e)}function Ige(t){Qg&&Jg&&(t==="light"?(Qg.removeAttribute("media"),Jg.media="enabled"):(Jg.removeAttribute("media"),Qg.media="enabled"))}function nat(t){kE&&Qg&&Jg&&(kE.textContent=fv(t).core.cssText,Qg.textContent=fv(t).dark.cssText,Jg.textContent=fv(t).light.cssText)}function fv(t){return{core:it` + @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap'); + @keyframes w3m-shake { + 0% { + transform: scale(1) rotate(0deg); + } + 20% { + transform: scale(1) rotate(-1deg); + } + 40% { + transform: scale(1) rotate(1.5deg); + } + 60% { + transform: scale(1) rotate(-1.5deg); + } + 80% { + transform: scale(1) rotate(1deg); + } + 100% { + transform: scale(1) rotate(0deg); + } + } + @keyframes w3m-iframe-fade-out { + 0% { + opacity: 1; + } + 100% { + opacity: 0; + } + } + @keyframes w3m-iframe-zoom-in { + 0% { + transform: translateY(50px); + opacity: 0; + } + 100% { + transform: translateY(0px); + opacity: 1; + } + } + @keyframes w3m-iframe-zoom-in-mobile { + 0% { + transform: scale(0.95); + opacity: 0; + } + 100% { + transform: scale(1); + opacity: 1; + } + } + :root { + --w3m-modal-width: 360px; + --w3m-color-mix-strength: ${hl(t?.["--w3m-color-mix-strength"]?`${t["--w3m-color-mix-strength"]}%`:"0%")}; + --w3m-font-family: ${hl(t?.["--w3m-font-family"]||"Inter, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;")}; + --w3m-font-size-master: ${hl(t?.["--w3m-font-size-master"]||"10px")}; + --w3m-border-radius-master: ${hl(t?.["--w3m-border-radius-master"]||"4px")}; + --w3m-z-index: ${hl(t?.["--w3m-z-index"]||999)}; + + --wui-font-family: var(--w3m-font-family); + + --wui-font-size-mini: calc(var(--w3m-font-size-master) * 0.8); + --wui-font-size-micro: var(--w3m-font-size-master); + --wui-font-size-tiny: calc(var(--w3m-font-size-master) * 1.2); + --wui-font-size-small: calc(var(--w3m-font-size-master) * 1.4); + --wui-font-size-paragraph: calc(var(--w3m-font-size-master) * 1.6); + --wui-font-size-medium: calc(var(--w3m-font-size-master) * 1.8); + --wui-font-size-large: calc(var(--w3m-font-size-master) * 2); + --wui-font-size-title-6: calc(var(--w3m-font-size-master) * 2.2); + --wui-font-size-medium-title: calc(var(--w3m-font-size-master) * 2.4); + --wui-font-size-2xl: calc(var(--w3m-font-size-master) * 4); + + --wui-border-radius-5xs: var(--w3m-border-radius-master); + --wui-border-radius-4xs: calc(var(--w3m-border-radius-master) * 1.5); + --wui-border-radius-3xs: calc(var(--w3m-border-radius-master) * 2); + --wui-border-radius-xxs: calc(var(--w3m-border-radius-master) * 3); + --wui-border-radius-xs: calc(var(--w3m-border-radius-master) * 4); + --wui-border-radius-s: calc(var(--w3m-border-radius-master) * 5); + --wui-border-radius-m: calc(var(--w3m-border-radius-master) * 7); + --wui-border-radius-l: calc(var(--w3m-border-radius-master) * 9); + --wui-border-radius-3xl: calc(var(--w3m-border-radius-master) * 20); + + --wui-font-weight-light: 400; + --wui-font-weight-regular: 500; + --wui-font-weight-medium: 600; + --wui-font-weight-bold: 700; + + --wui-letter-spacing-2xl: -1.6px; + --wui-letter-spacing-medium-title: -0.96px; + --wui-letter-spacing-title-6: -0.88px; + --wui-letter-spacing-large: -0.8px; + --wui-letter-spacing-medium: -0.72px; + --wui-letter-spacing-paragraph: -0.64px; + --wui-letter-spacing-small: -0.56px; + --wui-letter-spacing-tiny: -0.48px; + --wui-letter-spacing-micro: -0.2px; + --wui-letter-spacing-mini: -0.16px; + + --wui-spacing-0: 0px; + --wui-spacing-4xs: 2px; + --wui-spacing-3xs: 4px; + --wui-spacing-xxs: 6px; + --wui-spacing-2xs: 7px; + --wui-spacing-xs: 8px; + --wui-spacing-1xs: 10px; + --wui-spacing-s: 12px; + --wui-spacing-m: 14px; + --wui-spacing-l: 16px; + --wui-spacing-2l: 18px; + --wui-spacing-xl: 20px; + --wui-spacing-xxl: 24px; + --wui-spacing-2xl: 32px; + --wui-spacing-3xl: 40px; + --wui-spacing-4xl: 90px; + --wui-spacing-5xl: 95px; + + --wui-icon-box-size-xxs: 14px; + --wui-icon-box-size-xs: 20px; + --wui-icon-box-size-sm: 24px; + --wui-icon-box-size-md: 32px; + --wui-icon-box-size-mdl: 36px; + --wui-icon-box-size-lg: 40px; + --wui-icon-box-size-2lg: 48px; + --wui-icon-box-size-xl: 64px; + + --wui-icon-size-inherit: inherit; + --wui-icon-size-xxs: 10px; + --wui-icon-size-xs: 12px; + --wui-icon-size-sm: 14px; + --wui-icon-size-md: 16px; + --wui-icon-size-mdl: 18px; + --wui-icon-size-lg: 20px; + --wui-icon-size-xl: 24px; + --wui-icon-size-xxl: 28px; + + --wui-wallet-image-size-inherit: inherit; + --wui-wallet-image-size-sm: 40px; + --wui-wallet-image-size-md: 56px; + --wui-wallet-image-size-lg: 80px; + + --wui-visual-size-size-inherit: inherit; + --wui-visual-size-sm: 40px; + --wui-visual-size-md: 55px; + --wui-visual-size-lg: 80px; + + --wui-box-size-md: 100px; + --wui-box-size-lg: 120px; + + --wui-ease-out-power-2: cubic-bezier(0, 0, 0.22, 1); + --wui-ease-out-power-1: cubic-bezier(0, 0, 0.55, 1); + + --wui-ease-in-power-3: cubic-bezier(0.66, 0, 1, 1); + --wui-ease-in-power-2: cubic-bezier(0.45, 0, 1, 1); + --wui-ease-in-power-1: cubic-bezier(0.3, 0, 1, 1); + + --wui-ease-inout-power-1: cubic-bezier(0.45, 0, 0.55, 1); + + --wui-duration-lg: 200ms; + --wui-duration-md: 125ms; + --wui-duration-sm: 75ms; + + --wui-path-network-sm: path( + 'M15.4 2.1a5.21 5.21 0 0 1 5.2 0l11.61 6.7a5.21 5.21 0 0 1 2.61 4.52v13.4c0 1.87-1 3.59-2.6 4.52l-11.61 6.7c-1.62.93-3.6.93-5.22 0l-11.6-6.7a5.21 5.21 0 0 1-2.61-4.51v-13.4c0-1.87 1-3.6 2.6-4.52L15.4 2.1Z' + ); + + --wui-path-network-md: path( + 'M43.4605 10.7248L28.0485 1.61089C25.5438 0.129705 22.4562 0.129705 19.9515 1.61088L4.53951 10.7248C2.03626 12.2051 0.5 14.9365 0.5 17.886V36.1139C0.5 39.0635 2.03626 41.7949 4.53951 43.2752L19.9515 52.3891C22.4562 53.8703 25.5438 53.8703 28.0485 52.3891L43.4605 43.2752C45.9637 41.7949 47.5 39.0635 47.5 36.114V17.8861C47.5 14.9365 45.9637 12.2051 43.4605 10.7248Z' + ); + + --wui-path-network-lg: path( + 'M78.3244 18.926L50.1808 2.45078C45.7376 -0.150261 40.2624 -0.150262 35.8192 2.45078L7.6756 18.926C3.23322 21.5266 0.5 26.3301 0.5 31.5248V64.4752C0.5 69.6699 3.23322 74.4734 7.6756 77.074L35.8192 93.5492C40.2624 96.1503 45.7376 96.1503 50.1808 93.5492L78.3244 77.074C82.7668 74.4734 85.5 69.6699 85.5 64.4752V31.5248C85.5 26.3301 82.7668 21.5266 78.3244 18.926Z' + ); + + --wui-width-network-sm: 36px; + --wui-width-network-md: 48px; + --wui-width-network-lg: 86px; + + --wui-height-network-sm: 40px; + --wui-height-network-md: 54px; + --wui-height-network-lg: 96px; + + --wui-icon-size-network-xs: 12px; + --wui-icon-size-network-sm: 16px; + --wui-icon-size-network-md: 24px; + --wui-icon-size-network-lg: 42px; + + --wui-color-inherit: inherit; + + --wui-color-inverse-100: #fff; + --wui-color-inverse-000: #000; + + --wui-cover: rgba(20, 20, 20, 0.8); + + --wui-color-modal-bg: var(--wui-color-modal-bg-base); + + --wui-color-accent-100: var(--wui-color-accent-base-100); + --wui-color-accent-090: var(--wui-color-accent-base-090); + --wui-color-accent-080: var(--wui-color-accent-base-080); + + --wui-color-success-100: var(--wui-color-success-base-100); + --wui-color-success-125: var(--wui-color-success-base-125); + + --wui-color-warning-100: var(--wui-color-warning-base-100); + + --wui-color-error-100: var(--wui-color-error-base-100); + --wui-color-error-125: var(--wui-color-error-base-125); + + --wui-color-blue-100: var(--wui-color-blue-base-100); + --wui-color-blue-90: var(--wui-color-blue-base-90); + + --wui-icon-box-bg-error-100: var(--wui-icon-box-bg-error-base-100); + --wui-icon-box-bg-blue-100: var(--wui-icon-box-bg-blue-base-100); + --wui-icon-box-bg-success-100: var(--wui-icon-box-bg-success-base-100); + --wui-icon-box-bg-inverse-100: var(--wui-icon-box-bg-inverse-base-100); + + --wui-all-wallets-bg-100: var(--wui-all-wallets-bg-100); + + --wui-avatar-border: var(--wui-avatar-border-base); + + --wui-thumbnail-border: var(--wui-thumbnail-border-base); + + --wui-wallet-button-bg: var(--wui-wallet-button-bg-base); + + --wui-box-shadow-blue: var(--wui-color-accent-glass-020); + } + + @supports (background: color-mix(in srgb, white 50%, black)) { + :root { + --wui-color-modal-bg: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-modal-bg-base) + ); + + --wui-box-shadow-blue: color-mix(in srgb, var(--wui-color-accent-100) 20%, transparent); + + --wui-color-accent-100: color-mix( + in srgb, + var(--wui-color-accent-base-100) 100%, + transparent + ); + --wui-color-accent-090: color-mix( + in srgb, + var(--wui-color-accent-base-100) 90%, + transparent + ); + --wui-color-accent-080: color-mix( + in srgb, + var(--wui-color-accent-base-100) 80%, + transparent + ); + --wui-color-accent-glass-090: color-mix( + in srgb, + var(--wui-color-accent-base-100) 90%, + transparent + ); + --wui-color-accent-glass-080: color-mix( + in srgb, + var(--wui-color-accent-base-100) 80%, + transparent + ); + --wui-color-accent-glass-020: color-mix( + in srgb, + var(--wui-color-accent-base-100) 20%, + transparent + ); + --wui-color-accent-glass-015: color-mix( + in srgb, + var(--wui-color-accent-base-100) 15%, + transparent + ); + --wui-color-accent-glass-010: color-mix( + in srgb, + var(--wui-color-accent-base-100) 10%, + transparent + ); + --wui-color-accent-glass-005: color-mix( + in srgb, + var(--wui-color-accent-base-100) 5%, + transparent + ); + --wui-color-accent-002: color-mix( + in srgb, + var(--wui-color-accent-base-100) 2%, + transparent + ); + + --wui-color-fg-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-100) + ); + --wui-color-fg-125: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-125) + ); + --wui-color-fg-150: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-150) + ); + --wui-color-fg-175: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-175) + ); + --wui-color-fg-200: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-200) + ); + --wui-color-fg-225: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-225) + ); + --wui-color-fg-250: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-250) + ); + --wui-color-fg-275: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-275) + ); + --wui-color-fg-300: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-300) + ); + --wui-color-fg-325: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-325) + ); + --wui-color-fg-350: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-fg-350) + ); + + --wui-color-bg-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-100) + ); + --wui-color-bg-125: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-125) + ); + --wui-color-bg-150: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-150) + ); + --wui-color-bg-175: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-175) + ); + --wui-color-bg-200: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-200) + ); + --wui-color-bg-225: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-225) + ); + --wui-color-bg-250: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-250) + ); + --wui-color-bg-275: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-275) + ); + --wui-color-bg-300: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-300) + ); + --wui-color-bg-325: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-325) + ); + --wui-color-bg-350: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-bg-350) + ); + + --wui-color-success-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-success-base-100) + ); + --wui-color-success-125: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-success-base-125) + ); + + --wui-color-warning-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-warning-base-100) + ); + + --wui-color-error-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-error-base-100) + ); + --wui-color-blue-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-blue-base-100) + ); + --wui-color-blue-90: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-blue-base-90) + ); + --wui-color-error-125: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-color-error-base-125) + ); + + --wui-icon-box-bg-error-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-icon-box-bg-error-base-100) + ); + --wui-icon-box-bg-accent-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-icon-box-bg-blue-base-100) + ); + --wui-icon-box-bg-success-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-icon-box-bg-success-base-100) + ); + --wui-icon-box-bg-inverse-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-icon-box-bg-inverse-base-100) + ); + + --wui-all-wallets-bg-100: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-all-wallets-bg-100) + ); + + --wui-avatar-border: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-avatar-border-base) + ); + + --wui-thumbnail-border: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-thumbnail-border-base) + ); + + --wui-wallet-button-bg: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--wui-wallet-button-bg-base) + ); + } + } + `,light:it` + :root { + --w3m-color-mix: ${hl(t?.["--w3m-color-mix"]||"#fff")}; + --w3m-accent: ${hl(bh(t,"dark")["--w3m-accent"])}; + --w3m-default: #fff; + + --wui-color-modal-bg-base: ${hl(bh(t,"dark")["--w3m-background"])}; + --wui-color-accent-base-100: var(--w3m-accent); + + --wui-color-blueberry-100: hsla(230, 100%, 67%, 1); + --wui-color-blueberry-090: hsla(231, 76%, 61%, 1); + --wui-color-blueberry-080: hsla(230, 59%, 55%, 1); + --wui-color-blueberry-050: hsla(231, 100%, 70%, 0.1); + + --wui-color-fg-100: #e4e7e7; + --wui-color-fg-125: #d0d5d5; + --wui-color-fg-150: #a8b1b1; + --wui-color-fg-175: #a8b0b0; + --wui-color-fg-200: #949e9e; + --wui-color-fg-225: #868f8f; + --wui-color-fg-250: #788080; + --wui-color-fg-275: #788181; + --wui-color-fg-300: #6e7777; + --wui-color-fg-325: #9a9a9a; + --wui-color-fg-350: #363636; + + --wui-color-bg-100: #141414; + --wui-color-bg-125: #191a1a; + --wui-color-bg-150: #1e1f1f; + --wui-color-bg-175: #222525; + --wui-color-bg-200: #272a2a; + --wui-color-bg-225: #2c3030; + --wui-color-bg-250: #313535; + --wui-color-bg-275: #363b3b; + --wui-color-bg-300: #3b4040; + --wui-color-bg-325: #252525; + --wui-color-bg-350: #ffffff; + + --wui-color-success-base-100: #26d962; + --wui-color-success-base-125: #30a46b; + + --wui-color-warning-base-100: #f3a13f; + + --wui-color-error-base-100: #f25a67; + --wui-color-error-base-125: #df4a34; + + --wui-color-blue-base-100: rgba(102, 125, 255, 1); + --wui-color-blue-base-90: rgba(102, 125, 255, 0.9); + + --wui-color-success-glass-001: rgba(38, 217, 98, 0.01); + --wui-color-success-glass-002: rgba(38, 217, 98, 0.02); + --wui-color-success-glass-005: rgba(38, 217, 98, 0.05); + --wui-color-success-glass-010: rgba(38, 217, 98, 0.1); + --wui-color-success-glass-015: rgba(38, 217, 98, 0.15); + --wui-color-success-glass-020: rgba(38, 217, 98, 0.2); + --wui-color-success-glass-025: rgba(38, 217, 98, 0.25); + --wui-color-success-glass-030: rgba(38, 217, 98, 0.3); + --wui-color-success-glass-060: rgba(38, 217, 98, 0.6); + --wui-color-success-glass-080: rgba(38, 217, 98, 0.8); + + --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2); + + --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2); + + --wui-color-error-glass-001: rgba(242, 90, 103, 0.01); + --wui-color-error-glass-002: rgba(242, 90, 103, 0.02); + --wui-color-error-glass-005: rgba(242, 90, 103, 0.05); + --wui-color-error-glass-010: rgba(242, 90, 103, 0.1); + --wui-color-error-glass-015: rgba(242, 90, 103, 0.15); + --wui-color-error-glass-020: rgba(242, 90, 103, 0.2); + --wui-color-error-glass-025: rgba(242, 90, 103, 0.25); + --wui-color-error-glass-030: rgba(242, 90, 103, 0.3); + --wui-color-error-glass-060: rgba(242, 90, 103, 0.6); + --wui-color-error-glass-080: rgba(242, 90, 103, 0.8); + + --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2); + + --wui-color-gray-glass-001: rgba(255, 255, 255, 0.01); + --wui-color-gray-glass-002: rgba(255, 255, 255, 0.02); + --wui-color-gray-glass-005: rgba(255, 255, 255, 0.05); + --wui-color-gray-glass-010: rgba(255, 255, 255, 0.1); + --wui-color-gray-glass-015: rgba(255, 255, 255, 0.15); + --wui-color-gray-glass-020: rgba(255, 255, 255, 0.2); + --wui-color-gray-glass-025: rgba(255, 255, 255, 0.25); + --wui-color-gray-glass-030: rgba(255, 255, 255, 0.3); + --wui-color-gray-glass-060: rgba(255, 255, 255, 0.6); + --wui-color-gray-glass-080: rgba(255, 255, 255, 0.8); + --wui-color-gray-glass-090: rgba(255, 255, 255, 0.9); + + --wui-color-dark-glass-100: rgba(42, 42, 42, 1); + + --wui-icon-box-bg-error-base-100: #3c2426; + --wui-icon-box-bg-blue-base-100: #20303f; + --wui-icon-box-bg-success-base-100: #1f3a28; + --wui-icon-box-bg-inverse-base-100: #243240; + + --wui-all-wallets-bg-100: #222b35; + + --wui-avatar-border-base: #252525; + + --wui-thumbnail-border-base: #252525; + + --wui-wallet-button-bg-base: var(--wui-color-bg-125); + + --w3m-card-embedded-shadow-color: rgb(17 17 18 / 25%); + } + `,dark:it` + :root { + --w3m-color-mix: ${hl(t?.["--w3m-color-mix"]||"#000")}; + --w3m-accent: ${hl(bh(t,"light")["--w3m-accent"])}; + --w3m-default: #000; + + --wui-color-modal-bg-base: ${hl(bh(t,"light")["--w3m-background"])}; + --wui-color-accent-base-100: var(--w3m-accent); + + --wui-color-blueberry-100: hsla(231, 100%, 70%, 1); + --wui-color-blueberry-090: hsla(231, 97%, 72%, 1); + --wui-color-blueberry-080: hsla(231, 92%, 74%, 1); + + --wui-color-fg-100: #141414; + --wui-color-fg-125: #2d3131; + --wui-color-fg-150: #474d4d; + --wui-color-fg-175: #636d6d; + --wui-color-fg-200: #798686; + --wui-color-fg-225: #828f8f; + --wui-color-fg-250: #8b9797; + --wui-color-fg-275: #95a0a0; + --wui-color-fg-300: #9ea9a9; + --wui-color-fg-325: #9a9a9a; + --wui-color-fg-350: #d0d0d0; + + --wui-color-bg-100: #ffffff; + --wui-color-bg-125: #f5fafa; + --wui-color-bg-150: #f3f8f8; + --wui-color-bg-175: #eef4f4; + --wui-color-bg-200: #eaf1f1; + --wui-color-bg-225: #e5eded; + --wui-color-bg-250: #e1e9e9; + --wui-color-bg-275: #dce7e7; + --wui-color-bg-300: #d8e3e3; + --wui-color-bg-325: #f3f3f3; + --wui-color-bg-350: #202020; + + --wui-color-success-base-100: #26b562; + --wui-color-success-base-125: #30a46b; + + --wui-color-warning-base-100: #f3a13f; + + --wui-color-error-base-100: #f05142; + --wui-color-error-base-125: #df4a34; + + --wui-color-blue-base-100: rgba(102, 125, 255, 1); + --wui-color-blue-base-90: rgba(102, 125, 255, 0.9); + + --wui-color-success-glass-001: rgba(38, 181, 98, 0.01); + --wui-color-success-glass-002: rgba(38, 181, 98, 0.02); + --wui-color-success-glass-005: rgba(38, 181, 98, 0.05); + --wui-color-success-glass-010: rgba(38, 181, 98, 0.1); + --wui-color-success-glass-015: rgba(38, 181, 98, 0.15); + --wui-color-success-glass-020: rgba(38, 181, 98, 0.2); + --wui-color-success-glass-025: rgba(38, 181, 98, 0.25); + --wui-color-success-glass-030: rgba(38, 181, 98, 0.3); + --wui-color-success-glass-060: rgba(38, 181, 98, 0.6); + --wui-color-success-glass-080: rgba(38, 181, 98, 0.8); + + --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2); + + --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2); + + --wui-color-error-glass-001: rgba(240, 81, 66, 0.01); + --wui-color-error-glass-002: rgba(240, 81, 66, 0.02); + --wui-color-error-glass-005: rgba(240, 81, 66, 0.05); + --wui-color-error-glass-010: rgba(240, 81, 66, 0.1); + --wui-color-error-glass-015: rgba(240, 81, 66, 0.15); + --wui-color-error-glass-020: rgba(240, 81, 66, 0.2); + --wui-color-error-glass-025: rgba(240, 81, 66, 0.25); + --wui-color-error-glass-030: rgba(240, 81, 66, 0.3); + --wui-color-error-glass-060: rgba(240, 81, 66, 0.6); + --wui-color-error-glass-080: rgba(240, 81, 66, 0.8); + + --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2); + + --wui-icon-box-bg-error-base-100: #f4dfdd; + --wui-icon-box-bg-blue-base-100: #d9ecfb; + --wui-icon-box-bg-success-base-100: #daf0e4; + --wui-icon-box-bg-inverse-base-100: #dcecfc; + + --wui-all-wallets-bg-100: #e8f1fa; + + --wui-avatar-border-base: #f3f4f4; + + --wui-thumbnail-border-base: #eaefef; + + --wui-wallet-button-bg-base: var(--wui-color-bg-125); + + --wui-color-gray-glass-001: rgba(0, 0, 0, 0.01); + --wui-color-gray-glass-002: rgba(0, 0, 0, 0.02); + --wui-color-gray-glass-005: rgba(0, 0, 0, 0.05); + --wui-color-gray-glass-010: rgba(0, 0, 0, 0.1); + --wui-color-gray-glass-015: rgba(0, 0, 0, 0.15); + --wui-color-gray-glass-020: rgba(0, 0, 0, 0.2); + --wui-color-gray-glass-025: rgba(0, 0, 0, 0.25); + --wui-color-gray-glass-030: rgba(0, 0, 0, 0.3); + --wui-color-gray-glass-060: rgba(0, 0, 0, 0.6); + --wui-color-gray-glass-080: rgba(0, 0, 0, 0.8); + --wui-color-gray-glass-090: rgba(0, 0, 0, 0.9); + + --wui-color-dark-glass-100: rgba(233, 233, 233, 1); + + --w3m-card-embedded-shadow-color: rgb(224 225 233 / 25%); + } + `}}const Ht=it` + *, + *::after, + *::before, + :host { + margin: 0; + padding: 0; + box-sizing: border-box; + font-style: normal; + text-rendering: optimizeSpeed; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -webkit-tap-highlight-color: transparent; + font-family: var(--wui-font-family); + backface-visibility: hidden; + } +`,lr=it` + button, + a { + cursor: pointer; + display: flex; + justify-content: center; + align-items: center; + position: relative; + transition: + color var(--wui-duration-lg) var(--wui-ease-out-power-1), + background-color var(--wui-duration-lg) var(--wui-ease-out-power-1), + border var(--wui-duration-lg) var(--wui-ease-out-power-1), + border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1), + box-shadow var(--wui-duration-lg) var(--wui-ease-out-power-1); + will-change: background-color, color, border, box-shadow, border-radius; + outline: none; + border: none; + column-gap: var(--wui-spacing-3xs); + background-color: transparent; + text-decoration: none; + } + + wui-flex { + transition: border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1); + will-change: border-radius; + } + + button:disabled > wui-wallet-image, + button:disabled > wui-all-wallets-image, + button:disabled > wui-network-image, + button:disabled > wui-image, + button:disabled > wui-transaction-visual, + button:disabled > wui-logo { + filter: grayscale(1); + } + + @media (hover: hover) and (pointer: fine) { + button:hover:enabled { + background-color: var(--wui-color-gray-glass-005); + } + + button:active:enabled { + background-color: var(--wui-color-gray-glass-010); + } + } + + button:disabled > wui-icon-box { + opacity: 0.5; + } + + input { + border: none; + outline: none; + appearance: none; + } +`,mk=it` + .wui-color-inherit { + color: var(--wui-color-inherit); + } + + .wui-color-accent-100 { + color: var(--wui-color-accent-100); + } + + .wui-color-error-100 { + color: var(--wui-color-error-100); + } + + .wui-color-blue-100 { + color: var(--wui-color-blue-100); + } + + .wui-color-blue-90 { + color: var(--wui-color-blue-90); + } + + .wui-color-error-125 { + color: var(--wui-color-error-125); + } + + .wui-color-success-100 { + color: var(--wui-color-success-100); + } + + .wui-color-success-125 { + color: var(--wui-color-success-125); + } + + .wui-color-inverse-100 { + color: var(--wui-color-inverse-100); + } + + .wui-color-inverse-000 { + color: var(--wui-color-inverse-000); + } + + .wui-color-fg-100 { + color: var(--wui-color-fg-100); + } + + .wui-color-fg-200 { + color: var(--wui-color-fg-200); + } + + .wui-color-fg-300 { + color: var(--wui-color-fg-300); + } + + .wui-color-fg-325 { + color: var(--wui-color-fg-325); + } + + .wui-color-fg-350 { + color: var(--wui-color-fg-350); + } + + .wui-bg-color-inherit { + background-color: var(--wui-color-inherit); + } + + .wui-bg-color-blue-100 { + background-color: var(--wui-color-accent-100); + } + + .wui-bg-color-error-100 { + background-color: var(--wui-color-error-100); + } + + .wui-bg-color-error-125 { + background-color: var(--wui-color-error-125); + } + + .wui-bg-color-success-100 { + background-color: var(--wui-color-success-100); + } + + .wui-bg-color-success-125 { + background-color: var(--wui-color-success-100); + } + + .wui-bg-color-inverse-100 { + background-color: var(--wui-color-inverse-100); + } + + .wui-bg-color-inverse-000 { + background-color: var(--wui-color-inverse-000); + } + + .wui-bg-color-fg-100 { + background-color: var(--wui-color-fg-100); + } + + .wui-bg-color-fg-200 { + background-color: var(--wui-color-fg-200); + } + + .wui-bg-color-fg-300 { + background-color: var(--wui-color-fg-300); + } + + .wui-color-fg-325 { + background-color: var(--wui-color-fg-325); + } + + .wui-color-fg-350 { + background-color: var(--wui-color-fg-350); + } +`,qr={getSpacingStyles(t,e){if(Array.isArray(t))return t[e]?`var(--wui-spacing-${t[e]})`:void 0;if(typeof t=="string")return`var(--wui-spacing-${t})`},getFormattedDate(t){return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}).format(t)},getHostName(t){try{return new URL(t).hostname}catch{return""}},getTruncateString({string:t,charsStart:e,charsEnd:n,truncate:r}){return t.length<=e+n?t:r==="end"?`${t.substring(0,e)}...`:r==="start"?`...${t.substring(t.length-n)}`:`${t.substring(0,Math.floor(e))}...${t.substring(t.length-Math.floor(n))}`},generateAvatarColors(t){const n=t.toLowerCase().replace(/^0x/iu,"").replace(/[^a-f0-9]/gu,"").substring(0,6).padEnd(6,"0"),r=this.hexToRgb(n),s=getComputedStyle(document.documentElement).getPropertyValue("--w3m-border-radius-master"),o=100-3*Number(s?.replace("px","")),a=`${o}% ${o}% at 65% 40%`,c=[];for(let l=0;l<5;l+=1){const u=this.tintColor(r,.15*l);c.push(`rgb(${u[0]}, ${u[1]}, ${u[2]})`)}return` + --local-color-1: ${c[0]}; + --local-color-2: ${c[1]}; + --local-color-3: ${c[2]}; + --local-color-4: ${c[3]}; + --local-color-5: ${c[4]}; + --local-radial-circle: ${a} + `},hexToRgb(t){const e=parseInt(t,16),n=e>>16&255,r=e>>8&255,s=e&255;return[n,r,s]},tintColor(t,e){const[n,r,s]=t,i=Math.round(n+(255-n)*e),o=Math.round(r+(255-r)*e),a=Math.round(s+(255-s)*e);return[i,o,a]},isNumber(t){return{number:/^[0-9]+$/u}.number.test(t)},getColorTheme(t){return t||(typeof window<"u"&&window.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)")?.matches?"dark":"light":"dark")},splitBalance(t){const e=t.split(".");return e.length===2?[e[0],e[1]]:["0","00"]},roundNumber(t,e,n){return t.toString().length>=e?Number(t).toFixed(n):t},formatNumberToLocalString(t,e=2){return t===void 0?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})}},rat=3,sat=["receive","deposit","borrow","claim"],iat=["withdraw","repay","burn"],zb={getTransactionGroupTitle(t,e){const n=e7.getYear(),r=e7.getMonthNameByIndex(e);return t===n?r:`${r} ${t}`},getTransactionImages(t){const[e,n]=t,r=!!e&&t?.every(o=>!!o.nft_info),s=t?.length>1;return t?.length===2&&!r?[this.getTransactionImage(n),this.getTransactionImage(e)]:s?t.map(o=>this.getTransactionImage(o)):[this.getTransactionImage(e)]},getTransactionImage(t){return{type:zb.getTransactionTransferTokenType(t),url:zb.getTransactionImageURL(t)}},getTransactionImageURL(t){let e;const n=!!t?.nft_info,r=!!t?.fungible_info;return t&&n?e=t?.nft_info?.content?.preview?.url:t&&r&&(e=t?.fungible_info?.icon?.url),e},getTransactionTransferTokenType(t){if(t?.fungible_info)return"FUNGIBLE";if(t?.nft_info)return"NFT"},getTransactionDescriptions(t){const e=t?.metadata?.operationType,n=t?.transfers,r=t?.transfers?.length>0,s=t?.transfers?.length>1,i=r&&n?.every(d=>!!d?.fungible_info),[o,a]=n;let c=this.getTransferDescription(o),l=this.getTransferDescription(a);if(!r)return(e==="send"||e==="receive")&&i?(c=qr.getTruncateString({string:t?.metadata.sentFrom,charsStart:4,charsEnd:6,truncate:"middle"}),l=qr.getTruncateString({string:t?.metadata.sentTo,charsStart:4,charsEnd:6,truncate:"middle"}),[c,l]):[t.metadata.status];if(s)return n.map(d=>this.getTransferDescription(d)).reverse();let u="";return sat.includes(e)?u="+":iat.includes(e)&&(u="-"),c=u.concat(c),[c]},getTransferDescription(t){let e="";return t&&(t?.nft_info?e=t?.nft_info?.name||"-":t?.fungible_info&&(e=this.getFungibleTransferDescription(t)||"-")),e},getFungibleTransferDescription(t){return t?[this.getQuantityFixedValue(t?.quantity.numeric),t?.fungible_info?.symbol].join(" ").trim():null},getQuantityFixedValue(t){return t?parseFloat(t).toFixed(rat):null}};function oat(t,e){const{kind:n,elements:r}=e;return{kind:n,elements:r,finisher(s){customElements.get(t)||customElements.define(t,s)}}}function aat(t,e){return customElements.get(t)||customElements.define(t,e),e}function We(t){return function(n){return typeof n=="function"?aat(t,n):oat(t,n)}}const e6={hexStringToNumber(t){const e=t.startsWith("0x")?t.slice(2):t;return parseInt(e,16)},numberToHexString(t){return`0x${t.toString(16)}`},async getUserInfo(t){const[e,n]=await Promise.all([e6.getAddresses(t),e6.getChainId(t)]);return{chainId:n,addresses:e}},async getChainId(t){const e=await t.request({method:"eth_chainId"});return Number(e)},async getAddress(t){const[e]=await t.request({method:"eth_accounts"});return e},async getAddresses(t){return await t.request({method:"eth_accounts"})},async addEthereumChain(t,e){const n=e.rpcUrls.chainDefault?.http||[];await t.request({method:"wallet_addEthereumChain",params:[{chainId:e6.numberToHexString(e.id),rpcUrls:[...n],chainName:e.name,nativeCurrency:{name:e.nativeCurrency.name,decimals:e.nativeCurrency.decimals,symbol:e.nativeCurrency.symbol},blockExplorerUrls:[e.blockExplorers?.default.url],iconUrls:[vo.NetworkImageIds[e.id]]}]})}},Al={ACCOUNT_INDEXES:{PAYMENT:0,ORDINAL:1}},cat=P9e({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}});function d3(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const $ee=d3({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"}),Dee=d3({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"});d3({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"});const Jh=d3({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}}),lw=d3({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0}),lat={solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"]},Ml={getMethodsByChainNamespace(t){return lat[t]||[]},createDefaultNamespace(t){return{methods:this.getMethodsByChainNamespace(t),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(t,e){if(!e)return{...t};const n={...t},r=new Set;if(e.methods&&Object.keys(e.methods).forEach(s=>r.add(s)),e.chains&&Object.keys(e.chains).forEach(s=>r.add(s)),e.events&&Object.keys(e.events).forEach(s=>r.add(s)),e.rpcMap&&Object.keys(e.rpcMap).forEach(s=>{const[i]=s.split(":");i&&r.add(i)}),r.forEach(s=>{n[s]||(n[s]=this.createDefaultNamespace(s))}),e.methods&&Object.entries(e.methods).forEach(([s,i])=>{n[s]&&(n[s].methods=i)}),e.chains&&Object.entries(e.chains).forEach(([s,i])=>{n[s]&&(n[s].chains=i)}),e.events&&Object.entries(e.events).forEach(([s,i])=>{n[s]&&(n[s].events=i)}),e.rpcMap){const s=new Set;Object.entries(e.rpcMap).forEach(([i,o])=>{const[a,c]=i.split(":");!a||!c||!n[a]||(n[a].rpcMap||(n[a].rpcMap={}),s.has(a)||(n[a].rpcMap={},s.add(a)),n[a].rpcMap[c]=o)})}return n},createNamespaces(t,e){const n=t.reduce((r,s)=>{const{id:i,chainNamespace:o,rpcUrls:a}=s,c=a.default.http[0];r[o]||(r[o]=this.createDefaultNamespace(o));const l=`${o}:${i}`,u=r[o];switch(u.chains.push(l),l){case $ee.caipNetworkId:u.chains.push($ee.deprecatedCaipNetworkId);break;case Dee.caipNetworkId:u.chains.push(Dee.deprecatedCaipNetworkId);break}return u?.rpcMap&&c&&(u.rpcMap[i]=c),r},{});return this.applyNamespaceOverrides(n,e)},resolveReownName:async t=>{const e=await vE.resolveName(t);return(Object.values(e?.addresses)||[])[0]?.address||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const n=e.chains||[],r=e.accounts.map(s=>{const[i,o]=s.split(":");return`${i}:${o}`});return Array.from(new Set([...n,...r]))})},isSessionEventData(t){return typeof t=="object"&&t!==null&&"id"in t&&"topic"in t&&"params"in t&&typeof t.params=="object"&&t.params!==null&&"chainId"in t.params&&"event"in t.params&&typeof t.params.event=="object"&&t.params.event!==null},isOriginAllowed(t,e,n){for(const r of[...e,...n])if(r.includes("*")){const i=`^${r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(i,"u").test(t))return!0}else try{if(new URL(r).origin===t)return!0}catch{if(r===t)return!0}return!1},listenWcProvider({universalProvider:t,namespace:e,onConnect:n,onDisconnect:r,onAccountsChanged:s,onChainChanged:i,onDisplayUri:o}){n&&t.on("connect",()=>{const a=Ml.getWalletConnectAccounts(t,e);n(a)}),r&&t.on("disconnect",()=>{r()}),s&&t.on("session_event",a=>{if(Ml.isSessionEventData(a)){const{name:c,data:l}=a.params.event;if(c==="accountsChanged"&&Array.isArray(l)){const u=l.filter(d=>De.isCaipAddress(d)).map(d=>Yo.parseCaipAddress(d)).filter(d=>d.chainNamespace===e);s(u)}}}),i&&t.on("chainChanged",a=>{i(a)}),o&&t.on("display_uri",a=>{o(a)})},getWalletConnectAccounts(t,e){const n=new Set,r=t?.session?.namespaces?.[e]?.accounts?.map(s=>Yo.parseCaipAddress(s)).filter(({address:s})=>n.has(s.toLowerCase())?!1:(n.add(s.toLowerCase()),!0));return r&&r.length>0?r:[]}};let uat=class{constructor(e){this.namespace=e.namespace}async syncConnections(e){switch(this.namespace){case ye.CHAIN.EVM:await this.syncEVMConnections(e);break;case ye.CHAIN.SOLANA:await this.syncSolanaConnections(e);break;case ye.CHAIN.BITCOIN:await this.syncBitcoinConnections(e);break;default:throw new Error(`Unsupported chain namespace: ${this.namespace}`)}}async syncEVMConnections({connectors:e,caipNetworks:n,universalProvider:r,getConnectionStatusInfo:s,onConnection:i,onListenProvider:o}){await Promise.all(e.filter(a=>{const{hasDisconnected:c,hasConnected:l}=s(a.id);return!c&&l}).map(async a=>{if(a.id===ye.CONNECTOR_ID.WALLET_CONNECT){const c=Ml.getWalletConnectAccounts(r,this.namespace),l=n.find(u=>u.chainNamespace===this.namespace&&u.id.toString()===c[0]?.chainId?.toString());c.length>0&&i({connectorId:a.id,accounts:c.map(u=>({address:u.address})),caipNetwork:l})}else{const{accounts:c,chainId:l}=await qu.fetchProviderData(a);if(c.length>0&&l){const u=n.find(d=>d.chainNamespace===this.namespace&&d.id.toString()===l.toString());i({connectorId:a.id,accounts:c.map(d=>({address:d})),caipNetwork:u}),a.provider&&a.id!==ye.CONNECTOR_ID.AUTH&&a.id!==ye.CONNECTOR_ID.WALLET_CONNECT&&o(a.id,a.provider)}}}))}async syncSolanaConnections({connectors:e,caipNetwork:n,universalProvider:r,getConnectionStatusInfo:s,onConnection:i,onListenProvider:o}){await Promise.all(e.filter(a=>{const{hasDisconnected:c,hasConnected:l}=s(a.id);return!c&&l}).map(async a=>{if(a.id===ye.CONNECTOR_ID.WALLET_CONNECT){const c=Ml.getWalletConnectAccounts(r,this.namespace);c.length>0&&i({connectorId:a.id,accounts:c.map(l=>({address:l.address})),caipNetwork:n})}else{const c=await a.connect({chainId:n?.id});c&&(i({connectorId:a.id,accounts:[{address:c}],caipNetwork:n}),o(a.id,a.provider))}}))}async syncBitcoinConnections({connectors:e,caipNetwork:n,universalProvider:r,getConnectionStatusInfo:s,onConnection:i,onListenProvider:o}){await Promise.all(e.filter(a=>{const{hasDisconnected:c,hasConnected:l}=s(a.id);return!c&&l}).map(async a=>{if(a.id===ye.CONNECTOR_ID.WALLET_CONNECT){const f=Ml.getWalletConnectAccounts(r,this.namespace);f.length>0&&i({connectorId:a.id,accounts:f.map(p=>({address:p.address})),caipNetwork:n});return}const c=await a.connect();let u=(await a.getAccountAddresses())?.map(f=>De.createAccount(ye.CHAIN.BITCOIN,f.address,f.purpose||"payment",f.publicKey,f.path));if(u&&u.length>1&&(u=[{namespace:ye.CHAIN.BITCOIN,publicKey:u[Al.ACCOUNT_INDEXES.PAYMENT]?.publicKey??"",path:u[Al.ACCOUNT_INDEXES.PAYMENT]?.path??"",address:u[Al.ACCOUNT_INDEXES.PAYMENT]?.address??"",type:"payment"},{namespace:ye.CHAIN.BITCOIN,publicKey:u[Al.ACCOUNT_INDEXES.ORDINAL]?.publicKey??"",path:u[Al.ACCOUNT_INDEXES.ORDINAL]?.path??"",address:u[Al.ACCOUNT_INDEXES.ORDINAL]?.address??"",type:"ordinal"}]),!(a.chains.find(f=>f.id===n?.id)||a.chains[0]))throw new Error("The connector does not support any of the requested chains");c&&(o(a.id,a.provider),i({connectorId:a.id,accounts:u.map(f=>({address:f.address,type:f.type})),caipNetwork:n}))}))}getConnection({address:e,connectorId:n,connections:r,connectors:s}){if(n){const o=r.find(l=>Jn.isLowerCaseMatch(l.connectorId,n));if(!o)return null;const a=s.find(l=>Jn.isLowerCaseMatch(l.id,o.connectorId)),c=e?o.accounts.find(l=>Jn.isLowerCaseMatch(l.address,e)):o.accounts[0];return{...o,account:c,connector:a}}const i=r.find(o=>o.accounts.length>0&&s.some(a=>Jn.isLowerCaseMatch(a.id,o.connectorId)));if(i){const[o]=i.accounts,a=s.find(c=>Jn.isLowerCaseMatch(c.id,i.connectorId));return{...i,account:o,connector:a}}return null}};const K2={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]};class yk{constructor({provider:e,namespace:n}){this.id=ye.CONNECTOR_ID.WALLET_CONNECT,this.name=vo.ConnectorNamesMap[ye.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=vo.ConnectorImageIds[ye.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=G.getCaipNetworks.bind(G),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=n}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const n=this.getCaipNetworks(),r=_e.state.universalProviderConfigOverride,s=Ml.createNamespaces(n,r);await this.provider.connect({optionalNamespaces:s})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(n=>n.caipNetworkId);return Da.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:dat})}}const dat=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],fat=[ye.CONNECTOR_ID.AUTH,ye.CONNECTOR_ID.WALLET_CONNECT];class nW{constructor(e){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=n=>G.getCaipNetworks(n),this.getConnectorId=n=>ke.getConnectorId(n),e&&this.construct(e),e?.namespace&&(this.connectionManager=new uat({namespace:e.namespace}))}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get connections(){return this.availableConnections}get networks(){return this.getCaipNetworks(this.namespace)}onAuthConnected({accounts:e,chainId:n}){const r=this.getCaipNetworks().filter(s=>s.chainNamespace===this.namespace).find(s=>s.id.toString()===n?.toString());e&&r&&this.addConnection({connectorId:ye.CONNECTOR_ID.AUTH,accounts:e,caipNetwork:r})}setAuthProvider(e){e.onConnect(this.onAuthConnected.bind(this)),e.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:ye.CONNECTOR_ID.AUTH,type:"AUTH",name:ye.CONNECTOR_NAMES.AUTH,provider:e,imageId:vo.ConnectorImageIds[ye.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const n=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(r=>n.has(r.id)?!1:(n.add(r.id),!0)),this.emit("connectors",this.availableConnectors)}addConnection(...e){const n=new Set;this.availableConnections=[...e,...this.availableConnections].filter(r=>n.has(r.connectorId.toLowerCase())?!1:(n.add(r.connectorId.toLowerCase()),!0)),this.emit("connections",this.availableConnections)}deleteConnection(e){this.availableConnections=this.availableConnections.filter(n=>!Jn.isLowerCaseMatch(n.connectorId,e)),this.emit("connections",this.availableConnections)}clearConnections(e=!1){this.availableConnections=[],e&&this.emit("connections",this.availableConnections)}setStatus(e,n){nt.setStatus(e,n)}on(e,n){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(n)}off(e,n){const r=this.eventListeners.get(e);r&&r.delete(n)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,n){const r=this.eventListeners.get(e);r&&r.forEach(s=>s(n))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:n,providerType:r}=e;if(!e.provider)return;const s="provider"in e.provider?e.provider.provider:e.provider;if(r==="WALLET_CONNECT"){s.setDefaultChain(n.caipNetworkId);return}if(s&&r==="AUTH"){const i=s,o=Ss(n.chainNamespace);await i.switchNetwork({chainId:n.caipNetworkId});const a=await i.getUser({chainId:n.caipNetworkId,preferredAccountType:o});this.emit("switchNetwork",a)}}getWalletConnectConnector(){const e=this.connectors.find(n=>n instanceof yk);if(!e)throw new Error("WalletConnectConnector not found");return e}onConnect(e,n){if(e.length>0){const{address:r,chainId:s}=De.getAccount(e[0]),i=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===s?.toString()),o=this.connectors.find(a=>a.id===n);r&&(this.emit("accountChanged",{address:r,chainId:s,connector:o}),this.addConnection({connectorId:n,accounts:e.map(a=>{const{address:c}=De.getAccount(a);return{address:c}}),caipNetwork:i}))}}onAccountsChanged(e,n,r=!0){if(e.length>0){const{address:s}=De.getAccount(e[0]),i=this.connectionManager?.getConnection({connectorId:n,connections:this.connections,connectors:this.connectors});s&&Jn.isLowerCaseMatch(this.getConnectorId(ye.CHAIN.EVM),n)&&this.emit("accountChanged",{address:s,chainId:i?.caipNetwork?.id,connector:i?.connector}),this.addConnection({connectorId:n,accounts:e.map(o=>{const{address:a}=De.getAccount(o);return{address:a}}),caipNetwork:i?.caipNetwork})}else r&&this.onDisconnect(n)}onDisconnect(e){this.removeProviderListeners(e),this.deleteConnection(e),Jn.isLowerCaseMatch(this.getConnectorId(ye.CHAIN.EVM),e)&&this.emitFirstAvailableConnection(),this.connections.length===0&&this.emit("disconnect")}onChainChanged(e,n){const r=typeof e=="string"&&e.startsWith("0x")?e6.hexStringToNumber(e).toString():e.toString(),s=this.connectionManager?.getConnection({connectorId:n,connections:this.connections,connectors:this.connectors}),i=this.getCaipNetworks().filter(o=>o.chainNamespace===this.namespace).find(o=>o.id.toString()===r);s&&this.addConnection({connectorId:n,accounts:s.accounts,caipNetwork:i}),Jn.isLowerCaseMatch(this.getConnectorId(ye.CHAIN.EVM),n)&&this.emit("switchNetwork",{chainId:r})}listenProviderEvents(e,n){if(fat.includes(e))return;const r=o=>this.onAccountsChanged(o,e),s=o=>this.onChainChanged(o,e),i=()=>this.onDisconnect(e);this.providerHandlers[e]||(n.on("disconnect",i),n.on("accountsChanged",r),n.on("chainChanged",s),this.providerHandlers[e]={provider:n,disconnect:i,accountsChanged:r,chainChanged:s})}removeProviderListeners(e){if(this.providerHandlers[e]){const{provider:n,disconnect:r,accountsChanged:s,chainChanged:i}=this.providerHandlers[e];n.removeListener("disconnect",r),n.removeListener("accountsChanged",s),n.removeListener("chainChanged",i),this.providerHandlers[e]=null}}emitFirstAvailableConnection(){const e=this.connectionManager?.getConnection({connections:this.connections,connectors:this.connectors});if(e){const[n]=e.accounts;this.emit("accountChanged",{address:n?.address,chainId:e.caipNetwork?.id,connector:e.connector})}}}class hat extends nW{async setUniversalProvider(e){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new yk({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect(),this.emit("disconnect")}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}return{connections:[]}}syncConnections(){return Promise.resolve()}async getAccounts({namespace:e}){const r=this.provider?.session?.namespaces?.[e]?.accounts?.map(s=>{const[,,i]=s.split(":");return i}).filter((s,i,o)=>o.indexOf(s)===i)||[];return Promise.resolve({accounts:r.map(s=>De.createAccount(e,s,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!(e.caipNetwork&&wn.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};if(nt.state.balanceLoading&&e.chainId===G.state.activeCaipNetwork?.id)return{balance:nt.state.balance||"0.00",symbol:nt.state.balanceSymbol||""};const s=(await nt.fetchTokenBalance()).find(i=>i.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&i.symbol===e.caipNetwork?.nativeCurrency.symbol);return{balance:s?.quantity.numeric||"0.00",symbol:s?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:n,message:r,address:s}=e;if(!n)throw new Error("UniversalAdapter:signMessage - provider is undefined");let i="";return G.state.activeCaipNetwork?.chainNamespace===ye.CHAIN.SOLANA?i=(await n.request({method:"solana_signMessage",params:{message:ux.encode(new TextEncoder().encode(r)),pubkey:s}},G.state.activeCaipNetwork?.caipNetworkId)).signature:i=await n.request({method:"personal_sign",params:[r,s]},G.state.activeCaipNetwork?.caipNetworkId),{signature:i}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}emitFirstAvailableConnection(){}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){const{caipNetwork:n}=e,r=this.getWalletConnectConnector();if(n.chainNamespace===ye.CHAIN.EVM)try{await r.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:Ov(n.id)}]})}catch(s){if(s.code===K2.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||s.code===K2.ERROR_INVALID_CHAIN_ID||s.code===K2.ERROR_CODE_DEFAULT||s?.data?.originalError?.code===K2.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await r.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:Ov(n.id),rpcUrls:[n?.rpcUrls.chainDefault?.http],chainName:n.name,nativeCurrency:n.nativeCurrency,blockExplorerUrls:[n.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}r.provider.setDefaultChain(n.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(r=>r.type==="WALLET_CONNECT")?.provider}}const pat=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture"],FA={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?wn.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e.filter(n=>n!=="email"):!1},processFallback:t=>t===void 0?wn.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?wn.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?wn.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?wn.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?wn.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?wn.DEFAULT_REMOTE_FEATURES.onramp:!1:t},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?wn.DEFAULT_REMOTE_FEATURES.activity:!!t},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?wn.DEFAULT_REMOTE_FEATURES.reownBranding:!!t},emailCapture:{apiFeatureName:"email_capture",localFeatureName:"emailCapture",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>t.isEnabled&&(t.config??[]),processFallback:t=>!1},multiWallet:{apiFeatureName:"multi_wallet",localFeatureName:"multiWallet",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>wn.DEFAULT_REMOTE_FEATURES.multiWallet}},gat={localSettingsOverridden:new Set,getApiConfig(t,e){return e?.find(n=>n.id===t)},addWarning(t,e){if(t!==void 0){const n=FA[e],r=n.isLegacy?`"features.${n.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(r)}},processFeature(t,e,n,r,s){const i=FA[t],o=e[i.localFeatureName];if(s&&!i.isAvailableOnBasic)return!1;if(r){const a=this.getApiConfig(i.apiFeatureName,n);return a?.config===null?this.processFallbackFeature(t,o):a?.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return FA[t].processApi(e)},processFallbackFeature(t,e){return FA[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,n=t.features||{};this.localSettingsOverridden.clear();let r=null,s=!1;try{r=await mt.fetchProjectConfig(),s=r!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const i=s&&!e?wn.DEFAULT_REMOTE_FEATURES:wn.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of pat){const a=this.processFeature(o,n,r,s,e);Object.assign(i,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),wn.DEFAULT_REMOTE_FEATURES}if(s&&this.localSettingsOverridden.size>0){const o=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;Xr.open({debugMessage:fs.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(o)},"warning")}return i}};class mat{constructor(e){this.chainNamespaces=[],this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(n,r)=>{if(n){const s=G.getCaipNetworks(n)?.find(a=>a.id===r);if(s)return s;const i=G.getNetworkData(n)?.caipNetwork;return i||G.getRequestedCaipNetworks(n).filter(a=>a.chainNamespace===n)?.[0]}return G.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const n=this.getCaipNetwork();if(n)return n.id},this.getCaipNetworks=n=>G.getCaipNetworks(n),this.getActiveChainNamespace=()=>G.state.activeChain,this.setRequestedCaipNetworks=(n,r)=>{G.setRequestedCaipNetworks(n,r)},this.getApprovedCaipNetworkIds=()=>G.getAllApprovedCaipNetworkIds(),this.getCaipAddress=n=>G.state.activeChain===n||!n?G.state.activeCaipAddress:G.state.chains.get(n)?.accountState?.caipAddress,this.setClientId=n=>{Qt.setClientId(n)},this.getProvider=n=>Fr.getProvider(n),this.getProviderType=n=>Fr.getProviderId(n),this.getPreferredAccountType=n=>Ss(n),this.setCaipAddress=(n,r)=>{nt.setCaipAddress(n,r)},this.setBalance=(n,r,s)=>{nt.setBalance(n,r,s)},this.setProfileName=(n,r)=>{nt.setProfileName(n,r)},this.setProfileImage=(n,r)=>{nt.setProfileImage(n,r)},this.setUser=(n,r)=>{nt.setUser(n,r)},this.resetAccount=n=>{nt.resetAccount(n)},this.setCaipNetwork=n=>{G.setActiveCaipNetwork(n)},this.setCaipNetworkOfNamespace=(n,r)=>{G.setChainNetworkData(r,{caipNetwork:n})},this.setStatus=(n,r)=>{nt.setStatus(n,r),ke.isConnected()?Ge.setConnectionStatus("connected"):Ge.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=n=>G.state.chains.get(n)?.accountState?.address,this.setConnectors=n=>{const r=[...ke.state.allConnectors,...n];ke.setConnectors(r)},this.setConnections=(n,r)=>{Ge.setConnections(n,r),Ue.setConnections(n,r)},this.fetchIdentity=n=>Qt.fetchIdentity(n),this.getReownName=n=>vE.getNamesForAddress(n),this.getConnectors=()=>ke.getConnectors(),this.getConnectorImage=n=>nr.getConnectorImage(n),this.getConnections=n=>this.remoteFeatures.multiWallet?Sl.getConnectionsData(n).connections:(Xr.open(ye.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=n=>this.remoteFeatures.multiWallet?Sl.getConnectionsData(n).recentConnections:(Xr.open(ye.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async n=>{if(!this.remoteFeatures.multiWallet){Xr.open(ye.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await Ue.switchConnection(n)},this.deleteConnection=n=>{if(!this.remoteFeatures.multiWallet){Xr.open(ye.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}Ge.deleteAddressFromConnection(n),Ue.syncStorageConnections()},this.setConnectedWalletInfo=(n,r)=>{const s=Fr.getProviderId(r),i=n?{...n,type:s}:void 0;nt.setConnectedWalletInfo(i,r)},this.getIsConnectedState=()=>!!G.state.activeCaipAddress,this.addAddressLabel=(n,r,s)=>{nt.addAddressLabel(n,r,s)},this.removeAddressLabel=(n,r)=>{nt.removeAddressLabel(n,r)},this.getAddress=n=>G.state.activeChain===n||!n?nt.state.address:G.state.chains.get(n)?.accountState?.address,this.setApprovedCaipNetworksData=n=>G.setApprovedCaipNetworksData(n),this.resetNetwork=n=>{G.resetNetwork(n)},this.addConnector=n=>{ke.addConnector(n)},this.resetWcConnection=()=>{Ue.resetWcConnection()},this.setAddressExplorerUrl=(n,r)=>{nt.setAddressExplorerUrl(n,r)},this.setSmartAccountDeployed=(n,r)=>{nt.setSmartAccountDeployed(n,r)},this.setPreferredAccountType=(n,r)=>{G.setAccountProp("preferredAccountType",n,r)},this.setEIP6963Enabled=n=>{_e.setEIP6963Enabled(n)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,n){const r=e?.map(i=>i.namespace).filter(i=>!!i);if(r?.length)return[...new Set(r)];const s=n?.map(i=>i.chainNamespace);return[...new Set(s)]}async initialize(e){this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),_e.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),this.remoteFeatures=await gat.fetchRemoteFeatures(e),_e.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&r7.setOnrampProviders(this.remoteFeatures.onramp),(_e.state.remoteFeatures?.email||Array.isArray(_e.state.remoteFeatures?.socials)&&_e.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){try{const e=await mt.fetchAllowedOrigins();if(!e||!De.isClient()){Xr.open(fs.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}const n=window.location.origin;Ml.isOriginAllowed(n,e,K2.DEFAULT_ALLOWED_ANCESTORS)||Xr.open(fs.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(e){if(!(e instanceof Error)){Xr.open(fs.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}switch(e.message){case"RATE_LIMITED":Xr.open(fs.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const n=e.cause instanceof Error?e.cause:e;Xr.open({displayMessage:fs.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:fs.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(n.message)},"error");break}default:Xr.open(fs.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}}}sendInitializeEvent(e){const{...n}=e;delete n.adapters,delete n.universalProvider,Lt.sendEvent({type:"track",event:"INITIALIZE",properties:{...n,networks:e.networks.map(r=>r.id),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&Bi.setThemeMode(e.themeMode),e.themeVariables&&Bi.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");G.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const n=this.getDefaultNetwork();n&&G.setActiveCaipNetwork(n)}initializeConnectionController(e){Ue.initialize(e.adapters??[]),Ue.setWcBasic(e.basic??!1)}initializeConnectorController(){ke.initialize(this.chainNamespaces)}initializeProjectSettings(e){_e.setProjectId(e.projectId),_e.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){_e.setDebug(e.debug!==!1),_e.setEnableWalletConnect(e.enableWalletConnect!==!1),_e.setEnableWalletGuide(e.enableWalletGuide!==!1),_e.setEnableWallets(e.enableWallets!==!1),_e.setEIP6963Enabled(e.enableEIP6963!==!1),_e.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),_e.setEnableReconnect(e.enableReconnect!==!1),_e.setEnableAuthLogger(e.enableAuthLogger!==!1),_e.setCustomRpcUrls(e.customRpcUrls),_e.setEnableEmbedded(e.enableEmbedded),_e.setAllWallets(e.allWallets),_e.setIncludeWalletIds(e.includeWalletIds),_e.setExcludeWalletIds(e.excludeWalletIds),_e.setFeaturedWalletIds(e.featuredWalletIds),_e.setTokens(e.tokens),_e.setTermsConditionsUrl(e.termsConditionsUrl),_e.setPrivacyPolicyUrl(e.privacyPolicyUrl),_e.setCustomWallets(e.customWallets),_e.setFeatures(e.features),_e.setAllowUnsupportedChain(e.allowUnsupportedChain),_e.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),_e.setPreferUniversalLinks(e.experimental_preferUniversalLinks),_e.setDefaultAccountTypes(e.defaultAccountTypes);const n=this.getDefaultMetaData();if(!e.metadata&&n&&(e.metadata=n),_e.setMetadata(e.metadata),_e.setDisableAppend(e.disableAppend),_e.setEnableEmbedded(e.enableEmbedded),_e.setSIWX(e.siwx),!e.projectId){Xr.open(fs.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(e.adapters?.find(s=>s.namespace===ye.CHAIN.EVM)&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");_e.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return De.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const n=this.getActiveChainNamespace();if(n){const r=Du.getUnsupportedNetwork(`${n}:${e}`);G.setActiveCaipNetwork(r)}}getDefaultNetwork(){return Du.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,n){return Du.extendCaipNetwork(e,{customNetworkImageUrls:n.chainImages,projectId:n.projectId})}extendCaipNetworks(e){return Du.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const n=e.networks.find(s=>s.id===e.defaultNetwork?.id);return n?Du.extendCaipNetwork(n,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectNamespace(e,n){try{this.setLoading(!0,e);let r={connections:[]};const s=this.getAdapter(e);return(G.state.chains.get(e)?.accountState?.caipAddress||!_e.state.enableReconnect)&&s?.disconnect&&(r=await s.disconnect({id:n})),this.setLoading(!1,e),r}catch(r){throw this.setLoading(!1,e),new Error(`Failed to disconnect chains: ${r.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const e=G.state.activeChain,n=this.getAdapter(e),r=this.getCaipNetwork(e)?.id,s=Ue.getConnections(e),i=this.remoteFeatures.multiWallet,o=s.length>0;if(!n)throw new Error("Adapter not found");const a=await n.connectWalletConnect(r);(!o||!i)&&this.close(),this.setClientId(a?.clientId||null),Ge.setConnectedNamespaces([...G.state.chains.keys()]),await this.syncWalletConnectAccount(),await Da.initializeIfEnabled()},connectExternal:async({id:e,address:n,info:r,type:s,provider:i,chain:o,caipNetwork:a,socialUri:c})=>{const l=G.state.activeChain,u=o||l,d=this.getAdapter(u);if(o&&o!==l&&!a){const m=this.getCaipNetworks().find(y=>y.chainNamespace===o);m&&this.setCaipNetwork(m)}if(!u)throw new Error("connectExternal: namespace not found");if(!d)throw new Error("connectExternal: adapter not found");const f=this.getCaipNetwork(u),p=await d.connect({id:e,address:n,info:r,type:s,provider:i,socialUri:c,chainId:a?.id||f?.id,rpcUrl:a?.rpcUrls?.default?.http?.[0]||f?.rpcUrls?.default?.http?.[0]});if(p)return Ge.addConnectedNamespace(u),this.syncProvider({...p,chainNamespace:u}),this.setStatus("connected",u),this.syncConnectedWalletInfo(u),Ge.removeDisconnectedConnectorId(e,u),{address:p.address}},reconnectExternal:async({id:e,info:n,type:r,provider:s})=>{const i=G.state.activeChain,o=this.getAdapter(i);if(!i)throw new Error("reconnectExternal: namespace not found");if(!o)throw new Error("reconnectExternal: adapter not found");o?.reconnect&&(await o?.reconnect({id:e,info:n,type:r,provider:s,chainId:this.getCaipNetwork()?.id}),Ge.addConnectedNamespace(i),this.syncConnectedWalletInfo(i))},disconnect:async e=>{const{id:n,chainNamespace:r,initialDisconnect:s}=e||{},i=r||G.state.activeChain,o=ke.getConnectorId(i),a=n===ye.CONNECTOR_ID.AUTH||o===ye.CONNECTOR_ID.AUTH,c=n===ye.CONNECTOR_ID.WALLET_CONNECT||o===ye.CONNECTOR_ID.WALLET_CONNECT;try{const l=Array.from(G.state.chains.keys());let u=r?[r]:l;(c||a)&&(u=l);const d=u.map(async m=>{const y=ke.getConnectorId(m),b=await this.disconnectNamespace(m,n||y);b&&(a&&Ge.deleteConnectedSocialProvider(),b.connections.forEach(v=>{Ge.addDisconnectedConnectorId(v.connectorId,m)})),s&&this.onDisconnectNamespace({chainNamespace:m,closeModal:!1})}),f=await Promise.allSettled(d);gr.resetSend(),Ue.resetWcConnection(),Da.getSIWX()?.signOutOnDisconnect&&await Da.clearSessions(),ke.setFilterByNamespace(void 0),Ue.syncStorageConnections();const p=f.filter(m=>m.status==="rejected");if(p.length>0)throw new Error(p.map(m=>m.reason.message).join(", "));Lt.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:r||"all"}})}catch(l){throw new Error(`Failed to disconnect chains: ${l.message}`)}},checkInstalled:e=>e?e.some(n=>!!window.ethereum?.[String(n)]):!!window.ethereum,signMessage:async e=>{const n=G.state.activeChain,r=this.getAdapter(G.state.activeChain);if(!n)throw new Error("signMessage: namespace not found");if(!r)throw new Error("signMessage: adapter not found");return(await r?.signMessage({message:e,address:nt.state.address,provider:Fr.getProvider(n)}))?.signature||""},sendTransaction:async e=>{const n=e.chainNamespace;if(!n)throw new Error("sendTransaction: namespace not found");if(wn.SEND_SUPPORTED_NAMESPACES.includes(n)){const r=this.getAdapter(n);if(!r)throw new Error("sendTransaction: adapter not found");const s=Fr.getProvider(n);return(await r?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:s}))?.hash||""}return""},estimateGas:async e=>{const n=e.chainNamespace;if(n===ye.CHAIN.EVM){const r=this.getAdapter(n);if(!r)throw new Error("estimateGas: adapter is required but got undefined");const s=Fr.getProvider(n),i=this.getCaipNetwork();if(!i)throw new Error("estimateGas: caipNetwork is required but got undefined");return(await r?.estimateGas({...e,provider:s,caipNetwork:i}))?.gas||0n}return 0n},getEnsAvatar:async()=>{const e=G.state.activeChain;if(!e)throw new Error("getEnsAvatar: namespace is required but got undefined");return await this.syncIdentity({address:nt.state.address,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:e}),nt.state.profileImage||!1},getEnsAddress:async e=>await Ml.resolveReownName(e),writeContract:async e=>{const n=G.state.activeChain,r=this.getAdapter(n);if(!n)throw new Error("writeContract: namespace is required but got undefined");if(!r)throw new Error("writeContract: adapter is required but got undefined");const s=this.getCaipNetwork(),i=this.getCaipAddress(),o=Fr.getProvider(n);if(!s||!i)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");return(await r?.writeContract({...e,caipNetwork:s,provider:o,caipAddress:i}))?.hash},parseUnits:(e,n)=>{const r=this.getAdapter(G.state.activeChain);if(!r)throw new Error("parseUnits: adapter is required but got undefined");return r?.parseUnits({value:e,decimals:n})??0n},formatUnits:(e,n)=>{const r=this.getAdapter(G.state.activeChain);if(!r)throw new Error("formatUnits: adapter is required but got undefined");return r?.formatUnits({value:e,decimals:n})??"0"},getCapabilities:async e=>{const n=this.getAdapter(G.state.activeChain);if(!n)throw new Error("getCapabilities: adapter is required but got undefined");return await n?.getCapabilities(e)},grantPermissions:async e=>{const n=this.getAdapter(G.state.activeChain);if(!n)throw new Error("grantPermissions: adapter is required but got undefined");return await n?.grantPermissions(e)},revokePermissions:async e=>{const n=this.getAdapter(G.state.activeChain);if(!n)throw new Error("revokePermissions: adapter is required but got undefined");return n?.revokePermissions?await n.revokePermissions(e):"0x"},walletGetAssets:async e=>{const n=this.getAdapter(G.state.activeChain);if(!n)throw new Error("walletGetAssets: adapter is required but got undefined");return await n?.walletGetAssets(e)??{}},updateBalance:e=>{const n=this.getCaipNetwork(e);!n||!nt.state.address||this.updateNativeBalance(nt.state.address,n?.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Ue.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){if(Fr.getProviderId(G.state.activeChain)===Jr.CONNECTOR_TYPE_WALLET_CONNECT){const n=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(n)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const n=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const s=Fr.getProvider(n),i=Fr.getProviderId(n);if(e.chainNamespace===G.state.activeChain)await this.getAdapter(n)?.switchNetwork({caipNetwork:e,provider:s,providerType:i});else if(this.setCaipNetwork(e),i===Jr.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(n);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:n})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(n=>{const r=n.chains||[],s=n.accounts.map(i=>{const{chainId:o,chainNamespace:a}=Yo.parseCaipAddress(i);return`${a}:${o}`});return Array.from(new Set([...r,...s]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((n,r)=>{const s=e?.find(i=>i.namespace===r);return s?(s.construct({namespace:r,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),n[r]=s):n[r]=new hat({namespace:r,networks:this.getCaipNetworks()}),n},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e),await this.chainAdapters?.[e].syncConnectors(this.options,this),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){this.getAdapter(e)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const n=this.getAdapter(e);if(!n)return;const r=Ge.getConnectionStatus();_e.state.enableReconnect===!1?this.setStatus("disconnected",e):r==="connected"?this.setStatus("connecting",e):r==="disconnected"?(Ge.clearAddressCache(),this.setStatus(r,e)):this.setStatus(r,e),n.on("switchNetwork",({address:s,chainId:i})=>{const o=this.getCaipNetworks().find(l=>l.id.toString()===i.toString()||l.caipNetworkId.toString()===i.toString()),a=G.state.activeChain===e,c=G.state.chains.get(e)?.accountState?.address;if(o){const l=a&&s?s:c;l&&this.syncAccount({address:l,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(i)}),n.on("disconnect",()=>{const s=this.remoteFeatures.multiWallet,i=Array.from(Ue.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:e,closeModal:!s||i.length===0})}),n.on("connections",s=>{this.setConnections(s,e)}),n.on("pendingTransactions",()=>{const s=nt.state.address,i=G.state.activeCaipNetwork;!s||!i?.id||this.updateNativeBalance(s,i.id,i.chainNamespace)}),n.on("accountChanged",({address:s,chainId:i,connector:o})=>{const a=G.state.activeChain===e;o?.provider&&(this.syncProvider({id:o.id,type:o.type,provider:o.provider,chainNamespace:e}),this.syncConnectedWalletInfo(e)),a&&i?this.syncAccount({address:s,chainId:i,chainNamespace:e}):a&&G.state.activeCaipNetwork?.id?this.syncAccount({address:s,chainId:G.state.activeCaipNetwork?.id,chainNamespace:e}):this.syncAccountInfo(s,i,e),Ge.addConnectedNamespace(e)})}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&await this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(e=>Ue.disconnect({namespace:e,initialDisconnect:!0})))}catch(e){console.error("Error disconnecting existing connections:",e)}}async syncNamespaceConnection(e){try{e===ye.CHAIN.EVM&&De.isSafeApp()&&ke.setConnectorId(ye.CONNECTOR_ID.SAFE,e);const n=ke.getConnectorId(e);switch(this.setStatus("connecting",e),n){case ye.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case ye.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(n){console.warn("AppKit couldn't sync existing connection",n),this.setStatus("disconnected",e)}}onDisconnectNamespace(e){const{chainNamespace:n,closeModal:r}=e||{};G.resetAccount(n),G.resetNetwork(n),Ge.removeConnectedNamespace(n);const s=Array.from(G.state.chains.keys());(n?[n]:s).forEach(o=>Ge.addDisconnectedConnectorId(ke.getConnectorId(o)||"",o)),ke.removeConnectorId(n),Fr.resetChain(n),this.setUser(void 0,n),this.setStatus("disconnected",n),this.setConnectedWalletInfo(void 0,n),r!==!1&&tn.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map(e=>{const n=this.getCaipAddress(e),r=this.getCaipNetwork(e);return this.chainAdapters?.[e].syncConnections({connectToFirstConnector:!n,caipNetwork:r,getConnectorStorageInfo(s){const o=Ge.getConnections()[e]??[];return{hasDisconnected:Ge.isConnectorDisconnected(s,e),hasConnected:o.some(a=>Jn.isLowerCaseMatch(a.connectorId,s))}}})}))}async syncAdapterConnection(e){const n=this.getAdapter(e),r=ke.getConnectorId(e),s=this.getCaipNetwork(e),o=ke.getConnectors(e).find(a=>a.id===r);try{if(!n||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!s?.id)throw new Error("CaipNetwork not found");const a=await n?.syncConnection({namespace:e,id:o.id,chainId:s.id,rpcUrl:s?.rpcUrls?.default?.http?.[0]});a?(this.syncProvider({...a,chainNamespace:e}),await this.syncAccount({...a,chainNamespace:e}),this.setStatus("connected",e)):this.setStatus("disconnected",e)}catch{this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})}}async syncWalletConnectAccount(){const e=Object.keys(this.universalProvider?.session?.namespaces||{}),n=this.chainNamespaces.map(async r=>{const s=this.getAdapter(r);if(!s)return;const i=this.universalProvider?.session?.namespaces?.[r]?.accounts||[],o=G.state.activeCaipNetwork?.id,a=i.find(c=>{const{chainId:l}=Yo.parseCaipAddress(c);return l===o?.toString()})||i[0];if(a){const c=Yo.validateCaipAddress(a),{chainId:l,address:u}=Yo.parseCaipAddress(c);if(Fr.setProviderId(r,Jr.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&G.state.activeCaipNetwork&&s.namespace!==ye.CHAIN.EVM){const d=s.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:G.state.activeCaipNetwork});Fr.setProvider(r,d)}else Fr.setProvider(r,this.universalProvider);ke.setConnectorId(ye.CONNECTOR_ID.WALLET_CONNECT,r),Ge.addConnectedNamespace(r),await this.syncAccount({address:u,chainId:l,chainNamespace:r})}else e.includes(r)&&this.setStatus("disconnected",r);this.syncConnectedWalletInfo(r),await G.setApprovedCaipNetworksData(r)});await Promise.all(n)}syncProvider({type:e,provider:n,id:r,chainNamespace:s}){Fr.setProviderId(s,e),Fr.setProvider(s,n),ke.setConnectorId(r,s)}async syncAccount(e){const n=e.chainNamespace===G.state.activeChain,r=G.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:s,chainId:i,chainNamespace:o}=e,{chainId:a}=Ge.getActiveNetworkProps(),c=i||a,l=G.state.activeCaipNetwork?.name===ye.UNSUPPORTED_NETWORK_NAME,u=G.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!u)&&c){let d=this.getCaipNetworks().find(m=>m.id.toString()===c.toString()),f=this.getCaipNetworks().find(m=>m.chainNamespace===o);if(!u&&!d&&!f){const m=this.getApprovedCaipNetworkIds()||[],y=m.find(v=>Yo.parseCaipNetworkId(v)?.chainId===c.toString()),b=m.find(v=>Yo.parseCaipNetworkId(v)?.chainNamespace===o);d=this.getCaipNetworks().find(v=>v.caipNetworkId===y),f=this.getCaipNetworks().find(v=>v.caipNetworkId===b||"deprecatedCaipNetworkId"in v&&v.deprecatedCaipNetworkId===b)}const p=d||f;p?.chainNamespace===G.state.activeChain?_e.state.enableNetworkSwitch&&!_e.state.allowUnsupportedChain&&G.state.activeCaipNetwork?.name===ye.UNSUPPORTED_NETWORK_NAME?G.showUnsupportedChainUI():this.setCaipNetwork(p):n||r&&this.setCaipNetworkOfNamespace(r,o),this.syncConnectedWalletInfo(o),Jn.isLowerCaseMatch(s,nt.state.address)||this.syncAccountInfo(s,p?.id,o),n?await this.syncBalance({address:s,chainId:p?.id,chainNamespace:o}):await this.syncBalance({address:s,chainId:r?.id,chainNamespace:o})}}async syncAccountInfo(e,n,r){const s=this.getCaipAddress(r),i=n||s?.split(":")[1];if(!i)return;const o=`${r}:${i}:${e}`;this.setCaipAddress(o,r),await this.syncIdentity({address:e,chainId:i,chainNamespace:r})}async syncReownName(e,n){try{const r=await this.getReownName(e);if(r[0]){const s=r[0];this.setProfileName(s.name,n)}else this.setProfileName(null,n)}catch{this.setProfileName(null,n)}}syncConnectedWalletInfo(e){const n=ke.getConnectorId(e),r=Fr.getProviderId(e);if(r===Jr.CONNECTOR_TYPE_ANNOUNCED||r===Jr.CONNECTOR_TYPE_INJECTED){if(n){const i=this.getConnectors().find(o=>{const a=o.id===n,c=o.info?.rdns===n,l=o.connectors?.some(u=>u.id===n||u.info?.rdns===n);return a||c||!!l});if(i){const{info:o,name:a,imageUrl:c}=i,l=c||this.getConnectorImage(i);this.setConnectedWalletInfo({name:a,icon:l,...o},e)}}}else if(r===Jr.CONNECTOR_TYPE_WALLET_CONNECT){const s=Fr.getProvider(e);s?.session&&this.setConnectedWalletInfo({...s.session.peer.metadata,name:s.session.peer.metadata.name,icon:s.session.peer.metadata.icons?.[0]},e)}else if(n&&(n===ye.CONNECTOR_ID.COINBASE_SDK||n===ye.CONNECTOR_ID.COINBASE)){const s=this.getConnectors().find(c=>c.id===n),i=s?.name||"Coinbase Wallet",o=s?.imageUrl||this.getConnectorImage(s),a=s?.info;this.setConnectedWalletInfo({...a,name:i,icon:o},e)}}async syncBalance(e){!jC.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(r=>r.id.toString()===e.chainId?.toString())||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,n,r){const s=this.getAdapter(r),i=G.getCaipNetworkByNamespace(r,n);if(s){const o=await s.getBalance({address:e,chainId:n,caipNetwork:i,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,r),o}}async initializeUniversalAdapter(){const e=pst.createLogger((r,...s)=>{r&&this.handleAlertError(r),console.error(...s)}),n={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};_e.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await fst.init(n),_e.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(e=>{Ml.listenWcProvider({universalProvider:this.universalProvider,namespace:e,onDisplayUri:n=>{Ue.setUri(n)},onConnect:()=>{Ue.finalizeWcConnection()},onDisconnect:()=>{G.state.noAdapters&&this.resetAccount(e),Ue.resetWcConnection()},onChainChanged:n=>{const r=G.state.activeChain,s=r&&ke.state.activeConnectorIds[r]===ye.CONNECTOR_ID.WALLET_CONNECT;if(r===e&&(G.state.noAdapters||s)){const i=this.getCaipNetworks().find(a=>a.id.toString()===n.toString()||a.caipNetworkId.toString()===n.toString()),o=this.getCaipNetwork();if(!i){this.setUnsupportedNetwork(n);return}o?.id.toString()!==i?.id.toString()&&o?.chainNamespace===i?.chainNamespace&&this.setCaipNetwork(i)}},onAccountsChanged:n=>{const r=G.state.activeChain,s=r&&ke.state.activeConnectorIds[r]===ye.CONNECTOR_ID.WALLET_CONNECT;if(r===e&&(G.state.noAdapters||s)&&n.length>0){const i=n[0];this.syncAccount({address:i.address,chainId:i.chainId,chainNamespace:i.chainNamespace})}}})})}createUniversalProvider(){return!this.universalProviderInitPromise&&De.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){Lt.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const n=Object.entries(fs.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[r,s]=n??[],{message:i,alertErrorKey:o}=s??{};if(r&&i&&!this.reportedAlertErrors[r]){const a=fs.ALERT_ERRORS[o];a&&(Xr.open(a,"error"),this.reportedAlertErrors[r]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const n=e.namespace;if(!n)return;this.createClients();const r=e;r.namespace=n,r.construct({namespace:n,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),this.chainNamespaces.includes(n)||this.chainNamespaces.push(n),this.chainAdapters&&(this.chainAdapters[n]=r)}async open(e){if(await this.injectModalUi(),e?.uri&&Ue.setUri(e.uri),e?.arguments)switch(e?.view){case"Swap":return tn.open({...e,data:{swap:e.arguments}})}return tn.open(e)}async close(){await this.injectModalUi(),tn.close()}setLoading(e,n){tn.setLoading(e,n)}async disconnect(e){await Ue.disconnect({namespace:e})}getSIWX(){return _e.state.siwx}getError(){return""}getChainId(){return G.state.activeCaipNetwork?.id}async switchNetwork(e){const n=this.getCaipNetworks().find(r=>r.id===e.id);if(!n){Xr.open(fs.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await G.switchActiveNetwork(n)}getWalletProvider(){return G.state.activeChain?Fr.state.providers[G.state.activeChain]:null}getWalletProviderType(){return Fr.getProviderId(G.state.activeChain)}subscribeProviders(e){return Fr.subscribeProviders(e)}getThemeMode(){return Bi.state.themeMode}getThemeVariables(){return Bi.state.themeVariables}setThemeMode(e){Bi.setThemeMode(e),Ige(Bi.state.themeMode)}setTermsConditionsUrl(e){_e.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){_e.setPrivacyPolicyUrl(e)}setThemeVariables(e){Bi.setThemeVariables(e),nat(Bi.state.themeVariables)}subscribeTheme(e){return Bi.subscribe(e)}subscribeConnections(e){return this.remoteFeatures.multiWallet?Ue.subscribe(e):(Xr.open(ye.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(e){return e?G.state.chains.get(e)?.accountState?.connectedWalletInfo:nt.state.connectedWalletInfo}getAccount(e){const n=e||G.state.activeChain,r=ke.getAuthConnector(n),s=G.getAccountData(n),i=Ge.getConnectedConnectorId(G.state.activeChain),o=Ue.getConnections(n);if(!n)throw new Error("AppKit:getAccount - namespace is required");const a=o.flatMap(c=>c.accounts.map(({address:l,type:u})=>De.createAccount(n,l,u||"eoa")));if(s)return{allAccounts:a,caipAddress:s.caipAddress,address:De.getPlainAddress(s.caipAddress),isConnected:!!s.caipAddress,status:s.status,embeddedWalletInfo:r&&i===ye.CONNECTOR_ID.AUTH?{user:s.user?{...s.user,username:Ge.getConnectedSocialUsername()}:void 0,authProvider:s.socialProvider||"email",accountType:Ss(n),isSmartAccountDeployed:!!s.smartAccountDeployed}:void 0}}subscribeAccount(e,n){const r=()=>{const s=this.getAccount(n);s&&e(s)};n?G.subscribeChainProp("accountState",r,n):G.subscribe(r),ke.subscribe(r)}subscribeNetwork(e){return G.subscribe(({activeCaipNetwork:n})=>{e({caipNetwork:n,chainId:n?.id,caipNetworkId:n?.caipNetworkId})})}subscribeWalletInfo(e,n){return n?nt.subscribeKey("connectedWalletInfo",e,n):nt.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){nt.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){G.subscribeKey("activeCaipNetwork",e)}getState(){return Lu.state}getRemoteFeatures(){return _e.state.remoteFeatures}subscribeState(e){return Lu.subscribe(e)}subscribeRemoteFeatures(e){return _e.subscribeKey("remoteFeatures",e)}showErrorMessage(e){Wn.showError(e)}showSuccessMessage(e){Wn.showSuccess(e)}getEvent(){return{...Lt.state}}subscribeEvents(e){return Lt.subscribe(e)}replace(e){ze.replace(e)}redirect(e){ze.push(e)}popTransactionStack(e){ze.popTransactionStack(e)}isOpen(){return tn.state.open}isTransactionStackEmpty(){return ze.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){_e.setFeatures(e)}updateRemoteFeatures(e){_e.setRemoteFeatures(e)}updateOptions(e){const r={..._e.state||{},...e};_e.setOptions(r)}setConnectMethodsOrder(e){_e.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){_e.setWalletFeaturesOrder(e)}setCollapseWallets(e){_e.setCollapseWallets(e)}setSocialsOrder(e){_e.setSocialsOrder(e)}getConnectMethodsOrder(){return pf.getConnectOrderMethod(_e.state.features,ke.getConnectors())}addNetwork(e,n){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const r=this.extendCaipNetwork(n,this.options);this.getCaipNetworks().find(s=>s.id===r.id)||G.addNetwork(r)}removeNetwork(e,n){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(s=>s.id===n)&&G.removeNetwork(e,n)}}let Mee=!1;class yat extends mat{async onAuthProviderConnected(e){e.message&&e.signature&&e.siwxMessage&&await Da.addEmbeddedWalletSession({chainId:e.siwxMessage.chainId,accountAddress:e.address,notBefore:e.siwxMessage.notBefore,statement:e.siwxMessage.statement,resources:e.siwxMessage.resources,requestId:e.siwxMessage.requestId,issuedAt:e.siwxMessage.issuedAt,domain:e.siwxMessage.domain,uri:e.siwxMessage.uri,version:e.siwxMessage.version,nonce:e.siwxMessage.nonce},e.message,e.signature);const n=G.state.activeChain;if(!n)throw new Error("AppKit:onAuthProviderConnected - namespace is required");const r=n===ye.CHAIN.EVM?`eip155:${e.chainId}:${e.address}`:`${e.chainId}:${e.address}`,s=_e.state.defaultAccountTypes[n],i=Ss(n),o=e.preferredAccountType||i||s;Jn.isLowerCaseMatch(e.address,nt.state.address)||this.syncIdentity({address:e.address,chainId:e.chainId,chainNamespace:n}),this.setCaipAddress(r,n);const{signature:a,siwxMessage:c,message:l,...u}=e;this.setUser({...nt.state.user||{},...u},n),this.setSmartAccountDeployed(!!e.smartAccountDeployed,n),this.setPreferredAccountType(o,n),this.setLoading(!1,n)}setupAuthConnectorListeners(e){e.onRpcRequest(n=>{kc.checkIfRequestExists(n)?kc.checkIfRequestIsSafe(n)||this.handleUnsafeRPCRequest():(this.open(),console.error(_r.RPC_METHOD_NOT_ALLOWED_MESSAGE,{method:n.method}),setTimeout(()=>{this.showErrorMessage(_r.RPC_METHOD_NOT_ALLOWED_UI_MESSAGE)},300),e.rejectRpcRequests())}),e.onRpcError(()=>{this.isOpen()&&(this.isTransactionStackEmpty()?this.close():this.popTransactionStack("error"))}),e.onRpcSuccess((n,r)=>{const s=kc.checkIfRequestIsSafe(r),i=nt.state.address,o=G.state.activeCaipNetwork;s||(i&&o?.id&&this.updateNativeBalance(i,o.id,o.chainNamespace),this.isTransactionStackEmpty()?this.close():this.popTransactionStack("success"))}),e.onNotConnected(()=>{const n=G.state.activeChain;if(!n)throw new Error("AppKit:onNotConnected - namespace is required");ke.getConnectorId(n)===ye.CONNECTOR_ID.AUTH&&(this.setCaipAddress(void 0,n),this.setLoading(!1,n))}),e.onConnect(this.onAuthProviderConnected.bind(this)),e.onSocialConnected(this.onAuthProviderConnected.bind(this)),e.onSetPreferredAccount(({address:n,type:r})=>{const s=G.state.activeChain;if(!s)throw new Error("AppKit:onSetPreferredAccount - namespace is required");n&&this.setPreferredAccountType(r,s)})}async syncAuthConnectorTheme(e){if(!e)return;const n=Bi.getSnapshot(),r=_e.getSnapshot();await Promise.all([e.syncDappData({metadata:r.metadata,sdkVersion:r.sdkVersion,projectId:r.projectId,sdkType:r.sdkType}),e.syncTheme({themeMode:n.themeMode,themeVariables:n.themeVariables,w3mThemeVariables:bh(n.themeVariables,n.themeMode)})])}async syncAuthConnector(e,n){const r=ye.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(n),s=n===G.state.activeChain;if(!r)return;this.setLoading(!0,n);const i=e.getLoginEmailUsed();this.setLoading(i,n),i&&this.setStatus("connecting",n);const o=e.getEmail(),a=e.getUsername();this.setUser({...nt.state?.user||{},username:a,email:o},n),this.setupAuthConnectorListeners(e);const{isConnected:c}=await e.isConnected();if(await this.syncAuthConnectorTheme(e),n&&r&&s){const l=await e.getSmartAccountEnabledNetworks();G.setSmartAccountEnabledNetworks(l?.smartAccountEnabledNetworks||[],n),c&&this.connectionControllerClient?.connectExternal?(await this.connectionControllerClient?.connectExternal({id:ye.CONNECTOR_ID.AUTH,info:{name:ye.CONNECTOR_ID.AUTH},type:Jr.CONNECTOR_TYPE_AUTH,provider:e,chainId:G.state.activeCaipNetwork?.id,chain:n}),this.setStatus("connected",n)):ke.getConnectorId(n)===ye.CONNECTOR_ID.AUTH&&(this.setStatus("disconnected",n),Ge.removeConnectedNamespace(n))}this.setLoading(!1,n)}async checkExistingTelegramSocialConnection(e){try{if(!De.isTelegram())return;const n=Ge.getTelegramSocialProvider();if(!n||!De.isClient())return;const s=new URL(window.location.href).searchParams.get("result_uri");if(!s)return;nt.setSocialProvider(n,e),await this.authProvider?.init();const i=ke.getAuthConnector();n&&i&&(this.setLoading(!0,e),await Ue.connectExternal({id:i.id,type:i.type,socialUri:s},i.chain),Ge.setConnectedSocialProvider(n),Ge.removeTelegramSocialProvider(),Lt.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:n,caipNetworkId:G.getActiveCaipNetwork()?.caipNetworkId}}))}catch(n){this.setLoading(!1,e),console.error("checkExistingSTelegramocialConnection error",n)}try{const n=new URL(window.location.href);n.searchParams.delete("result_uri"),window.history.replaceState({},document.title,n.toString())}catch(n){console.error("tma social login failed",n)}}createAuthProvider(e){if(!ye.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(e))return;const r=this.remoteFeatures?.email,s=Array.isArray(this.remoteFeatures?.socials)&&this.remoteFeatures.socials.length>0,i=r||s,a=Jn.getActiveNamespaceConnectedToAuth()||e;!this.authProvider&&this.options?.projectId&&i&&(this.authProvider=qm.getInstance({projectId:this.options.projectId,enableLogger:this.options.enableAuthLogger,chainId:this.getCaipNetwork(a)?.caipNetworkId,abortController:fs.EmbeddedWalletAbortController,onTimeout:l=>{l==="iframe_load_failed"?Xr.open(fs.ALERT_ERRORS.IFRAME_LOAD_FAILED,"error"):l==="iframe_request_timeout"?Xr.open(fs.ALERT_ERRORS.IFRAME_REQUEST_TIMEOUT,"error"):l==="unverified_domain"&&Xr.open(fs.ALERT_ERRORS.UNVERIFIED_DOMAIN,"error")},getActiveCaipNetwork:l=>vm(l),getCaipNetworks:l=>G.getCaipNetworks(l)}),Lu.subscribeOpen(l=>{!l&&this.isTransactionStackEmpty()&&this.authProvider?.rejectRpcRequests()}));const c=e===G.state.activeChain&&_e.state.enableReconnect;_e.state.enableReconnect===!1?this.syncAuthConnectorTheme(this.authProvider):this.authProvider&&c&&(this.syncAuthConnector(this.authProvider,e),this.checkExistingTelegramSocialConnection(e))}createAuthProviderForAdapter(e){this.createAuthProvider(e),this.authProvider&&this.chainAdapters?.[e]?.setAuthProvider?.(this.authProvider)}initControllers(e){super.initControllers(e),this.options.excludeWalletIds&&mt.initializeExcludedWallets({ids:this.options.excludeWalletIds})}async switchCaipNetwork(e){if(!e)return;const n=G.state.activeChain,r=e.chainNamespace,s=this.getAddressByChainNamespace(r);if(r===n&&s){const o=this.getAdapter(r),a=Fr.getProvider(r),c=Fr.getProviderId(r);await o?.switchNetwork({caipNetwork:e,provider:a,providerType:c}),this.setCaipNetwork(e)}else{const a=Fr.getProviderId(n)===Jr.CONNECTOR_TYPE_AUTH,c=Fr.getProviderId(r),l=c===Jr.CONNECTOR_TYPE_AUTH,u=ye.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(r);if(!r)throw new Error("AppKit:switchCaipNetwork - networkNamespace is required");if((a&&c===void 0||l)&&u)try{G.state.activeChain=e.chainNamespace,s?await this.getAdapter(r)?.switchNetwork({caipNetwork:e,provider:this.authProvider,providerType:c}):await this.connectionControllerClient?.connectExternal?.({id:ye.CONNECTOR_ID.AUTH,provider:this.authProvider,chain:r,chainId:e.id,type:Jr.CONNECTOR_TYPE_AUTH,caipNetwork:e}),this.setCaipNetwork(e)}catch{await this.getAdapter(r)?.switchNetwork({caipNetwork:e,provider:this.authProvider,providerType:c})}else if(c===Jr.CONNECTOR_TYPE_WALLET_CONNECT){if(!G.state.noAdapters){const d=this.getAdapter(r),f=Fr.getProvider(r),p=Fr.getProviderId(r);await d?.switchNetwork({caipNetwork:e,provider:f,providerType:p})}this.setCaipNetwork(e),this.syncWalletConnectAccount()}else this.setCaipNetwork(e),s&&this.syncAccount({address:s,chainId:e.id,chainNamespace:r})}}async initialize(e){await super.initialize(e),this.chainNamespaces?.forEach(n=>{this.createAuthProviderForAdapter(n)}),await this.injectModalUi(),Lu.set({initialized:!0})}async syncIdentity({address:e,chainId:n,chainNamespace:r}){const s=`${r}:${n}`,i=this.caipNetworks?.find(o=>o.caipNetworkId===s);if(r!==ye.CHAIN.EVM||i?.testnet){this.setProfileName(null,r),this.setProfileImage(null,r);return}try{const{name:o,avatar:a}=await this.fetchIdentity({address:e,caipNetworkId:s});this.setProfileName(o,r),this.setProfileImage(a,r)}catch{await this.syncReownName(e,r),n!==1&&this.setProfileImage(null,r)}}syncConnectedWalletInfo(e){const n=Fr.getProviderId(e);if(n===Jr.CONNECTOR_TYPE_AUTH){const r=this.authProvider;if(r){const s=Ge.getConnectedSocialProvider()??"email",i=r.getEmail()??r.getUsername();this.setConnectedWalletInfo({name:n,identifier:i,social:s},e)}}else super.syncConnectedWalletInfo(e)}async injectModalUi(){if(De.isClient()&&!Mee)try{const e={...wn.DEFAULT_FEATURES,...this.options.features},n=this.remoteFeatures;if(await this.loadModalComponents(e,n),De.isClient()&&!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!_e.state.disableAppend&&!_e.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}Mee=!0}catch(e){console.error("Error injecting modal UI:",e)}}async loadModalComponents(e,n){if(!De.isClient())return;const r=[];(n.email||n.socials&&n.socials.length>0)&&r.push(et(()=>import("./embedded-wallet-Axuw_fFm.js"),[])),n.email&&r.push(et(()=>import("./email-OHUMhOV6.js"),[])),n.socials&&r.push(et(()=>import("./socials-DtOZCIFp.js"),[])),n.swaps&&n.swaps.length>0&&r.push(et(()=>import("./swaps-2zeCrlxq.js"),__vite__mapDeps([0,1]))),e.send&&r.push(et(()=>import("./send-Ncb2jADE.js"),__vite__mapDeps([2,1]))),e.receive&&r.push(et(()=>import("./receive-dL28-83Q.js"),[])),n.onramp&&n.onramp.length>0&&r.push(et(()=>import("./onramp-BiRdNRiA.js"),[])),n.activity&&r.push(et(()=>import("./transactions-QUhMMh8E.js"),[])),e.pay&&r.push(et(()=>import("./index-BGGOaaWA.js"),[])),n.emailCapture&&r.push(et(()=>import("./ui-CTdGiFlJ.js"),__vite__mapDeps([3,4]))),await Promise.all([...r,et(()=>Promise.resolve().then(()=>ypt),void 0),et(()=>import("./w3m-modal-BNMiKa3F.js"),[])])}}const wat="1.7.17";var bat={},Zv={},Xo={};Object.defineProperty(Xo,"__esModule",{value:!0});Xo.decode=Xo.encode=Xo.unescape=Xo.escape=Xo.pad=void 0;const Tge=rx;function rW(t){return`${t}${"=".repeat(4-(t.length%4||4))}`}Xo.pad=rW;function Nge(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}Xo.escape=Nge;function Pge(t){return rW(t).replace(/-/g,"+").replace(/_/g,"/")}Xo.unescape=Pge;function vat(t){return Nge((0,Tge.fromByteArray)(new TextEncoder().encode(t)))}Xo.encode=vat;function xat(t){return new TextDecoder().decode((0,Tge.toByteArray)(rW(Pge(t))))}Xo.decode=xat;var wk={},bk={};const Eat=Zy(oLe),kge=Zy(s9e);var Yv={};const Cat={},_at=Object.freeze(Object.defineProperty({__proto__:null,default:Cat},Symbol.toStringTag,{value:"Module"})),Rge=Zy(_at);(function(t){/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */Object.defineProperty(t,"__esModule",{value:!0}),t.utils=t.schnorr=t.verify=t.signSync=t.sign=t.getSharedSecret=t.recoverPublicKey=t.getPublicKey=t.hexToBytes=t.bytesToHex=t.Signature=t.Point=t.CURVE=void 0;const e=Rge,n=BigInt(0),r=BigInt(1),s=BigInt(2),i=BigInt(3),o=BigInt(8),a=Object.freeze({a:n,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:r,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")});t.CURVE=a;const c=(ce,se)=>(ce+se/s)/se,l={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(ce){const{n:se}=a,ue=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),Ce=-r*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),Le=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),Qe=ue,ht=BigInt("0x100000000000000000000000000000000"),pt=c(Qe*ce,se),zt=c(-Ce*ce,se);let Ut=oe(ce-pt*ue-zt*Le,se),on=oe(-pt*Ce-zt*Qe,se);const kn=Ut>ht,Mn=on>ht;if(kn&&(Ut=se-Ut),Mn&&(on=se-on),Ut>ht||on>ht)throw new Error("splitScalarEndo: Endomorphism failed, k="+ce);return{k1neg:kn,k1:Ut,k2neg:Mn,k2:on}}},u=32,d=32,f=32,p=u+1,m=2*u+1;function y(ce){const{a:se,b:ue}=a,Ce=oe(ce*ce),Le=oe(Ce*ce);return oe(Le+se*ce+ue)}const b=a.a===n;class v extends Error{constructor(se){super(se)}}function x(ce){if(!(ce instanceof E))throw new TypeError("JacobianPoint expected")}class E{constructor(se,ue,Ce){this.x=se,this.y=ue,this.z=Ce}static fromAffine(se){if(!(se instanceof k))throw new TypeError("JacobianPoint#fromAffine: expected Point");return se.equals(k.ZERO)?E.ZERO:new E(se.x,se.y,r)}static toAffineBatch(se){const ue=we(se.map(Ce=>Ce.z));return se.map((Ce,Le)=>Ce.toAffine(ue[Le]))}static normalizeZ(se){return E.toAffineBatch(se).map(E.fromAffine)}equals(se){x(se);const{x:ue,y:Ce,z:Le}=this,{x:Qe,y:ht,z:pt}=se,zt=oe(Le*Le),Ut=oe(pt*pt),on=oe(ue*Ut),kn=oe(Qe*zt),Mn=oe(oe(Ce*pt)*Ut),zr=oe(oe(ht*Le)*zt);return on===kn&&Mn===zr}negate(){return new E(this.x,oe(-this.y),this.z)}double(){const{x:se,y:ue,z:Ce}=this,Le=oe(se*se),Qe=oe(ue*ue),ht=oe(Qe*Qe),pt=se+Qe,zt=oe(s*(oe(pt*pt)-Le-ht)),Ut=oe(i*Le),on=oe(Ut*Ut),kn=oe(on-s*zt),Mn=oe(Ut*(zt-kn)-o*ht),zr=oe(s*ue*Ce);return new E(kn,Mn,zr)}add(se){x(se);const{x:ue,y:Ce,z:Le}=this,{x:Qe,y:ht,z:pt}=se;if(Qe===n||ht===n)return this;if(ue===n||Ce===n)return se;const zt=oe(Le*Le),Ut=oe(pt*pt),on=oe(ue*Ut),kn=oe(Qe*zt),Mn=oe(oe(Ce*pt)*Ut),zr=oe(oe(ht*Le)*zt),Wr=oe(kn-on),ci=oe(zr-Mn);if(Wr===n)return ci===n?this.double():E.ZERO;const cc=oe(Wr*Wr),lc=oe(Wr*cc),uc=oe(on*cc),au=oe(ci*ci-lc-s*uc),dc=oe(ci*(uc-au)-Mn*lc),Jc=oe(Le*pt*Wr);return new E(au,dc,Jc)}subtract(se){return this.add(se.negate())}multiplyUnsafe(se){const ue=E.ZERO;if(typeof se=="bigint"&&se===n)return ue;let Ce=Ee(se);if(Ce===r)return this;if(!b){let kn=ue,Mn=this;for(;Ce>n;)Ce&r&&(kn=kn.add(Mn)),Mn=Mn.double(),Ce>>=r;return kn}let{k1neg:Le,k1:Qe,k2neg:ht,k2:pt}=l.splitScalar(Ce),zt=ue,Ut=ue,on=this;for(;Qe>n||pt>n;)Qe&r&&(zt=zt.add(on)),pt&r&&(Ut=Ut.add(on)),on=on.double(),Qe>>=r,pt>>=r;return Le&&(zt=zt.negate()),ht&&(Ut=Ut.negate()),Ut=new E(oe(Ut.x*l.beta),Ut.y,Ut.z),zt.add(Ut)}precomputeWindow(se){const ue=b?128/se+1:256/se+1,Ce=[];let Le=this,Qe=Le;for(let ht=0;ht>=kn,Wr>zt&&(Wr-=on,se+=r);const ci=zr,cc=zr+Math.abs(Wr)-1,lc=Mn%2!==0,uc=Wr<0;Wr===0?ht=ht.add(A(lc,Le[ci])):Qe=Qe.add(A(uc,Le[cc]))}return{p:Qe,f:ht}}multiply(se,ue){let Ce=Ee(se),Le,Qe;if(b){const{k1neg:ht,k1:pt,k2neg:zt,k2:Ut}=l.splitScalar(Ce);let{p:on,f:kn}=this.wNAF(pt,ue),{p:Mn,f:zr}=this.wNAF(Ut,ue);on=A(ht,on),Mn=A(zt,Mn),Mn=new E(oe(Mn.x*l.beta),Mn.y,Mn.z),Le=on.add(Mn),Qe=kn.add(zr)}else{const{p:ht,f:pt}=this.wNAF(Ce,ue);Le=ht,Qe=pt}return E.normalizeZ([Le,Qe])[0]}toAffine(se){const{x:ue,y:Ce,z:Le}=this,Qe=this.equals(E.ZERO);se==null&&(se=Qe?o:V(Le));const ht=se,pt=oe(ht*ht),zt=oe(pt*ht),Ut=oe(ue*pt),on=oe(Ce*zt),kn=oe(Le*ht);if(Qe)return k.ZERO;if(kn!==r)throw new Error("invZ was invalid");return new k(Ut,on)}}E.BASE=new E(a.Gx,a.Gy,r),E.ZERO=new E(n,r,n);function A(ce,se){const ue=se.negate();return ce?ue:se}const _=new WeakMap;class k{constructor(se,ue){this.x=se,this.y=ue}_setWindowSize(se){this._WINDOW_SIZE=se,_.delete(this)}hasEvenY(){return this.y%s===n}static fromCompressedHex(se){const ue=se.length===32,Ce=fe(ue?se:se.subarray(1));if(!J(Ce))throw new Error("Point is not on curve");const Le=y(Ce);let Qe=je(Le);const ht=(Qe&r)===r;ue?ht&&(Qe=oe(-Qe)):(se[0]&1)===1!==ht&&(Qe=oe(-Qe));const pt=new k(Ce,Qe);return pt.assertValidity(),pt}static fromUncompressedHex(se){const ue=fe(se.subarray(1,u+1)),Ce=fe(se.subarray(u+1,u*2+1)),Le=new k(ue,Ce);return Le.assertValidity(),Le}static fromHex(se){const ue=ve(se),Ce=ue.length,Le=ue[0];if(Ce===u)return this.fromCompressedHex(ue);if(Ce===p&&(Le===2||Le===3))return this.fromCompressedHex(ue);if(Ce===m&&Le===4)return this.fromUncompressedHex(ue);throw new Error(`Point.fromHex: received invalid point. Expected 32-${p} compressed bytes or ${m} uncompressed bytes, not ${Ce}`)}static fromPrivateKey(se){return k.BASE.multiply(ae(se))}static fromSignature(se,ue,Ce){const{r:Le,s:Qe}=$e(ue);if(![0,1,2,3].includes(Ce))throw new Error("Cannot recover: invalid recovery bit");const ht=Ie(ve(se)),{n:pt}=a,zt=Ce===2||Ce===3?Le+pt:Le,Ut=V(zt,pt),on=oe(-ht*Ut,pt),kn=oe(Qe*Ut,pt),Mn=Ce&1?"03":"02",zr=k.fromHex(Mn+H(zt)),Wr=k.BASE.multiplyAndAddUnsafe(zr,on,kn);if(!Wr)throw new Error("Cannot recover signature: point at infinify");return Wr.assertValidity(),Wr}toRawBytes(se=!1){return L(this.toHex(se))}toHex(se=!1){const ue=H(this.x);return se?`${this.hasEvenY()?"02":"03"}${ue}`:`04${ue}${H(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const se="Point is not on elliptic curve",{x:ue,y:Ce}=this;if(!J(ue)||!J(Ce))throw new Error(se);const Le=oe(Ce*Ce),Qe=y(ue);if(oe(Le-Qe)!==n)throw new Error(se)}equals(se){return this.x===se.x&&this.y===se.y}negate(){return new k(this.x,oe(-this.y))}double(){return E.fromAffine(this).double().toAffine()}add(se){return E.fromAffine(this).add(E.fromAffine(se)).toAffine()}subtract(se){return this.add(se.negate())}multiply(se){return E.fromAffine(this).multiply(se,this).toAffine()}multiplyAndAddUnsafe(se,ue,Ce){const Le=E.fromAffine(this),Qe=ue===n||ue===r||this!==k.BASE?Le.multiplyUnsafe(ue):Le.multiply(ue),ht=E.fromAffine(se).multiplyUnsafe(Ce),pt=Qe.add(ht);return pt.equals(E.ZERO)?void 0:pt.toAffine()}}t.Point=k,k.BASE=new k(a.Gx,a.Gy),k.ZERO=new k(n,n);function B(ce){return Number.parseInt(ce[0],16)>=8?"00"+ce:ce}function W(ce){if(ce.length<2||ce[0]!==2)throw new Error(`Invalid signature integer tag: ${N(ce)}`);const se=ce[1],ue=ce.subarray(2,se+2);if(!se||ue.length!==se)throw new Error("Invalid signature integer: wrong length");if(ue[0]===0&&ue[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:fe(ue),left:ce.subarray(se+2)}}function S(ce){if(ce.length<2||ce[0]!=48)throw new Error(`Invalid signature tag: ${N(ce)}`);if(ce[1]!==ce.length-2)throw new Error("Invalid signature: incorrect length");const{data:se,left:ue}=W(ce.subarray(2)),{data:Ce,left:Le}=W(ue);if(Le.length)throw new Error(`Invalid signature: left bytes after parsing: ${N(Le)}`);return{r:se,s:Ce}}class ${constructor(se,ue){this.r=se,this.s=ue,this.assertValidity()}static fromCompact(se){const ue=R(se),Ce="Signature.fromCompact";if(typeof se!="string"&&!ue)throw new TypeError(`${Ce}: Expected string or Uint8Array`);const Le=ue?N(se):se;if(Le.length!==128)throw new Error(`${Ce}: Expected 64-byte hex`);return new $(de(Le.slice(0,64)),de(Le.slice(64,128)))}static fromDER(se){const ue=R(se);if(typeof se!="string"&&!ue)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:Ce,s:Le}=S(ue?se:L(se));return new $(Ce,Le)}static fromHex(se){return this.fromDER(se)}assertValidity(){const{r:se,s:ue}=this;if(!pe(se))throw new Error("Invalid Signature: r must be 0 < r < n");if(!pe(ue))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const se=a.n>>r;return this.s>se}normalizeS(){return this.hasHighS()?new $(this.r,oe(-this.s,a.n)):this}toDERRawBytes(){return L(this.toDERHex())}toDERHex(){const se=B(re(this.s)),ue=B(re(this.r)),Ce=se.length/2,Le=ue.length/2,Qe=re(Ce),ht=re(Le);return`30${re(Le+Ce+4)}02${ht}${ue}02${Qe}${se}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return L(this.toCompactHex())}toCompactHex(){return H(this.r)+H(this.s)}}t.Signature=$;function R(ce){return ce instanceof Uint8Array||ArrayBuffer.isView(ce)&&ce.constructor.name==="Uint8Array"}function M(ce){if(!R(ce))throw new Error("Uint8Array expected")}function j(...ce){if(ce.every(M),ce.length===1)return ce[0];const se=ce.reduce((Ce,Le)=>Ce+Le.length,0),ue=new Uint8Array(se);for(let Ce=0,Le=0;Cese.toString(16).padStart(2,"0"));function N(ce){M(ce);let se="";for(let ue=0;ue=T._0&&ce<=T._9)return ce-T._0;if(ce>=T.A&&ce<=T.F)return ce-(T.A-10);if(ce>=T.a&&ce<=T.f)return ce-(T.a-10)}function L(ce){if(typeof ce!="string")throw new Error("hex string expected, got "+typeof ce);const se=ce.length,ue=se/2;if(se%2)throw new Error("hex string expected, got unpadded hex of length "+se);const Ce=new Uint8Array(ue);for(let Le=0,Qe=0;Le0)return BigInt(ce);if(typeof ce=="bigint"&&pe(ce))return ce;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function oe(ce,se=a.P){const ue=ce%se;return ue>=n?ue:se+ue}function Oe(ce,se){const{P:ue}=a;let Ce=ce;for(;se-- >n;)Ce*=Ce,Ce%=ue;return Ce}function je(ce){const{P:se}=a,ue=BigInt(6),Ce=BigInt(11),Le=BigInt(22),Qe=BigInt(23),ht=BigInt(44),pt=BigInt(88),zt=ce*ce*ce%se,Ut=zt*zt*ce%se,on=Oe(Ut,i)*Ut%se,kn=Oe(on,i)*Ut%se,Mn=Oe(kn,s)*zt%se,zr=Oe(Mn,Ce)*Mn%se,Wr=Oe(zr,Le)*zr%se,ci=Oe(Wr,ht)*Wr%se,cc=Oe(ci,pt)*ci%se,lc=Oe(cc,ht)*Wr%se,uc=Oe(lc,i)*Ut%se,au=Oe(uc,Qe)*zr%se,dc=Oe(au,ue)*zt%se,Jc=Oe(dc,s);if(Jc*Jc%se!==ce)throw new Error("Cannot find square root");return Jc}function V(ce,se=a.P){if(ce===n||se<=n)throw new Error(`invert: expected positive integers, got n=${ce} mod=${se}`);let ue=oe(ce,se),Ce=se,Le=n,Qe=r;for(;ue!==n;){const pt=Ce/ue,zt=Ce%ue,Ut=Le-Qe*pt;Ce=ue,ue=zt,Le=Qe,Qe=Ut}if(Ce!==r)throw new Error("invert: does not exist");return oe(Le,se)}function we(ce,se=a.P){const ue=new Array(ce.length),Ce=ce.reduce((Qe,ht,pt)=>ht===n?Qe:(ue[pt]=Qe,oe(Qe*ht,se)),r),Le=V(Ce,se);return ce.reduceRight((Qe,ht,pt)=>ht===n?Qe:(ue[pt]=oe(Qe*ue[pt],se),oe(Qe*ht,se)),Le),ue}function Ae(ce){const se=ce.length*8-d*8,ue=fe(ce);return se>0?ue>>BigInt(se):ue}function Ie(ce,se=!1){const ue=Ae(ce);if(se)return ue;const{n:Ce}=a;return ue>=Ce?ue-Ce:ue}let ge,Me;class be{constructor(se,ue){if(this.hashLen=se,this.qByteLen=ue,typeof se!="number"||se<2)throw new Error("hashLen must be a number");if(typeof ue!="number"||ue<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(se).fill(1),this.k=new Uint8Array(se).fill(0),this.counter=0}hmac(...se){return t.utils.hmacSha256(this.k,...se)}hmacSync(...se){return Me(this.k,...se)}checkSync(){if(typeof Me!="function")throw new v("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(se=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),se),this.v=await this.hmac(this.v),se.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),se),this.v=await this.hmac(this.v))}reseedSync(se=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),se),this.v=this.hmacSync(this.v),se.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),se),this.v=this.hmacSync(this.v))}async generate(){this.incr();let se=0;const ue=[];for(;se0)se=BigInt(ce);else if(typeof ce=="string"){if(ce.length!==2*d)throw new Error("Expected 32 bytes of private key");se=de(ce)}else if(R(ce)){if(ce.length!==d)throw new Error("Expected 32 bytes of private key");se=fe(ce)}else throw new TypeError("Expected valid private key");if(!pe(se))throw new Error("Expected private key: 0 < key < n");return se}function Pe(ce){return ce instanceof k?(ce.assertValidity(),ce):k.fromHex(ce)}function $e(ce){if(ce instanceof $)return ce.assertValidity(),ce;try{return $.fromDER(ce)}catch{return $.fromCompact(ce)}}function Re(ce,se=!1){return k.fromPrivateKey(ce).toRawBytes(se)}t.getPublicKey=Re;function ut(ce,se,ue,Ce=!1){return k.fromSignature(ce,se,ue).toRawBytes(Ce)}t.recoverPublicKey=ut;function Je(ce){const se=R(ce),ue=typeof ce=="string",Ce=(se||ue)&&ce.length;return se?Ce===p||Ce===m:ue?Ce===p*2||Ce===m*2:ce instanceof k}function ft(ce,se,ue=!1){if(Je(ce))throw new TypeError("getSharedSecret: first arg must be private key");if(!Je(se))throw new TypeError("getSharedSecret: second arg must be public key");const Ce=Pe(se);return Ce.assertValidity(),Ce.multiply(ae(ce)).toRawBytes(ue)}t.getSharedSecret=ft;function Z(ce){const se=ce.length>u?ce.slice(0,u):ce;return fe(se)}function O(ce){const se=Z(ce),ue=oe(se,a.n);return F(ue{ce=ve(ce);const se=d+8;if(ce.length1024)throw new Error("Expected valid bytes of private key as per FIPS 186");const ue=oe(fe(ce),a.n-r)+r;return Y(ue)},randomBytes:(ce=32)=>{if(Bs.web)return Bs.web.getRandomValues(new Uint8Array(ce));if(Bs.node){const{randomBytes:se}=Bs.node;return Uint8Array.from(se(ce))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>t.utils.hashToPrivateKey(t.utils.randomBytes(d+8)),precompute(ce=8,se=k.BASE){const ue=se===k.BASE?se:new k(se.x,se.y);return ue._setWindowSize(ce),ue.multiply(i),ue},sha256:async(...ce)=>{if(Bs.web){const se=await Bs.web.subtle.digest("SHA-256",j(...ce));return new Uint8Array(se)}else if(Bs.node){const{createHash:se}=Bs.node,ue=se("sha256");return ce.forEach(Ce=>ue.update(Ce)),Uint8Array.from(ue.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(ce,...se)=>{if(Bs.web){const ue=await Bs.web.subtle.importKey("raw",ce,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),Ce=j(...se),Le=await Bs.web.subtle.sign("HMAC",ue,Ce);return new Uint8Array(Le)}else if(Bs.node){const{createHmac:ue}=Bs.node,Ce=ue("sha256",ce);return se.forEach(Le=>Ce.update(Le)),Uint8Array.from(Ce.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(ce,...se)=>{let ue=ou[ce];if(ue===void 0){const Ce=await t.utils.sha256(Uint8Array.from(ce,Le=>Le.charCodeAt(0)));ue=j(Ce,Ce),ou[ce]=ue}return t.utils.sha256(ue,...se)},taggedHashSync:(ce,...se)=>{if(typeof ge!="function")throw new v("sha256Sync is undefined, you need to set it");let ue=ou[ce];if(ue===void 0){const Ce=ge(Uint8Array.from(ce,Le=>Le.charCodeAt(0)));ue=j(Ce,Ce),ou[ce]=ue}return ge(ue,...se)},_JacobianPoint:E},Object.defineProperties(t.utils,{sha256Sync:{configurable:!1,get(){return ge},set(ce){ge||(ge=ce)}},hmacSha256Sync:{configurable:!1,get(){return Me},set(ce){Me||(Me=ce)}}})})(Yv);var Xv={};Object.defineProperty(Xv,"__esModule",{value:!0});Xv.joseToDer=Xv.derToJose=void 0;const Oge=rx,$ge=Xo;function mD(t){return(t/8|0)+(t%8===0?0:1)}const Sat={ES256:mD(256),ES384:mD(384),ES512:mD(521)};function Dge(t){const e=Sat[t];if(e)return e;throw new Error(`Unknown algorithm "${t}"`)}const KT=128,Mge=0,Aat=32,Iat=16,Tat=2,Lge=Iat|Aat|Mge<<6,GT=Tat|Mge<<6;function Bge(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")return(0,Oge.toByteArray)((0,$ge.pad)(t));throw new TypeError("ECDSA signature must be a Base64 string or a Uint8Array")}function Nat(t,e){const n=Bge(t),r=Dge(e),s=r+1,i=n.length;let o=0;if(n[o++]!==Lge)throw new Error('Could not find expected "seq"');let a=n[o++];if(a===(KT|1)&&(a=n[o++]),i-o=KT&&--r,r}function Pat(t,e){t=Bge(t);const n=Dge(e),r=t.length;if(r!==n*2)throw new TypeError(`"${e}" signatures must be "${n*2}" bytes, saw "${r}"`);const s=Lee(t,0,n),i=Lee(t,n,t.length),o=n-s,a=n-i,c=2+o+1+1+a,l=c{const n=Oat.hmac.create($at.sha256,t);return e.forEach(r=>n.update(r)),n.digest()};class Uge{static derivePublicKey(e,n=!0){return e.length===66&&(e=e.slice(0,64)),e.length<64&&(e=e.padStart(64,"0")),(0,Fee.bytesToHex)(t6.getPublicKey(e,n))}static signHash(e,n,r="jose"){if(!e||!n)throw new Uee.MissingParametersError("a signing input hash and private key are all required");const s=t6.signSync(e,n.slice(0,64),{der:!0,canonical:!1});if(r==="der")return(0,Fee.bytesToHex)(s);if(r==="jose")return(0,Bee.derToJose)(s,"ES256");throw Error("Invalid signature format")}static loadSignature(e){return(0,Bee.joseToDer)(e,"ES256")}static verifyHash(e,n,r){if(!e||!n||!r)throw new Uee.MissingParametersError("a signing input hash, der signature, and public key are all required");return t6.verify(n,e,r,{strict:!1})}}bk.SECP256K1Client=Uge;Uge.algorithmName="ES256K";(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.cryptoClients=t.SECP256K1Client=void 0;const e=bk;Object.defineProperty(t,"SECP256K1Client",{enumerable:!0,get:function(){return e.SECP256K1Client}});const n={ES256K:e.SECP256K1Client};t.cryptoClients=n})(wk);var Sy={},Dat=kr&&kr.__awaiter||function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((r=r.apply(t,e||[])).next())})};Object.defineProperty(Sy,"__esModule",{value:!0});Sy.hashSha256Async=Sy.hashSha256=void 0;const Mat=kge;function Fge(t){return(0,Mat.sha256)(t)}Sy.hashSha256=Fge;function Lat(t){return Dat(this,void 0,void 0,function*(){try{if(typeof crypto<"u"&&typeof crypto.subtle<"u"){const n=typeof t=="string"?new TextEncoder().encode(t):t,r=yield crypto.subtle.digest("SHA-256",n);return new Uint8Array(r)}else{const n=Rge;if(!n.createHash)throw new Error("`crypto` module does not contain `createHash`");return Promise.resolve(n.createHash("sha256").update(t).digest())}}catch(e){return console.log(e),console.log('Crypto lib not found. Neither the global `crypto.subtle` Web Crypto API, nor the or the Node.js `require("crypto").createHash` module is available. Falling back to JS implementation.'),Promise.resolve(Fge(t))}})}Sy.hashSha256Async=Lat;var Bat=kr&&kr.__awaiter||function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((r=r.apply(t,e||[])).next())})};Object.defineProperty(Zv,"__esModule",{value:!0});Zv.TokenSigner=Zv.createUnsecuredToken=void 0;const lB=Xo,jee=wk,Uat=ep,zee=Sy;function uB(t,e){const n=[],r=lB.encode(JSON.stringify(e));n.push(r);const s=lB.encode(JSON.stringify(t));return n.push(s),n.join(".")}function Fat(t){return uB(t,{typ:"JWT",alg:"none"})+"."}Zv.createUnsecuredToken=Fat;class jat{constructor(e,n){if(!(e&&n))throw new Uat.MissingParametersError("a signing algorithm and private key are required");if(typeof e!="string")throw new Error("signing algorithm parameter must be a string");if(e=e.toUpperCase(),!jee.cryptoClients.hasOwnProperty(e))throw new Error("invalid signing algorithm");this.tokenType="JWT",this.cryptoClient=jee.cryptoClients[e],this.rawPrivateKey=n}header(e={}){const n={typ:this.tokenType,alg:this.cryptoClient.algorithmName};return Object.assign({},n,e)}sign(e,n=!1,r={}){const s=this.header(r),i=uB(e,s),o=(0,zee.hashSha256)(i);return this.createWithSignedHash(e,n,s,i,o)}signAsync(e,n=!1,r={}){return Bat(this,void 0,void 0,function*(){const s=this.header(r),i=uB(e,s),o=yield(0,zee.hashSha256Async)(i);return this.createWithSignedHash(e,n,s,i,o)})}createWithSignedHash(e,n,r,s,i){const o=this.cryptoClient.signHash(i,this.rawPrivateKey);return n?{header:[lB.encode(JSON.stringify(r))],payload:JSON.stringify(e),signature:[o]}:[s,o].join(".")}}Zv.TokenSigner=jat;var vk={};Object.defineProperty(vk,"__esModule",{value:!0});vk.TokenVerifier=void 0;const zat=Xo,Wee=wk,Wat=ep,jA=Sy;class Vat{constructor(e,n){if(!(e&&n))throw new Wat.MissingParametersError("a signing algorithm and public key are required");if(typeof e!="string")throw"signing algorithm parameter must be a string";if(e=e.toUpperCase(),!Wee.cryptoClients.hasOwnProperty(e))throw"invalid signing algorithm";this.tokenType="JWT",this.cryptoClient=Wee.cryptoClients[e],this.rawPublicKey=n}verify(e){return typeof e=="string"?this.verifyCompact(e,!1):typeof e=="object"?this.verifyExpanded(e,!1):!1}verifyAsync(e){return typeof e=="string"?this.verifyCompact(e,!0):typeof e=="object"?this.verifyExpanded(e,!0):Promise.resolve(!1)}verifyCompact(e,n){const r=e.split("."),s=r[0]+"."+r[1],i=o=>{const a=this.cryptoClient.loadSignature(r[2]);return this.cryptoClient.verifyHash(o,a,this.rawPublicKey)};if(n)return(0,jA.hashSha256Async)(s).then(o=>i(o));{const o=(0,jA.hashSha256)(s);return i(o)}}verifyExpanded(e,n){const r=[e.header.join("."),zat.encode(e.payload)].join(".");let s=!0;const i=o=>(e.signature.map(a=>{const c=this.cryptoClient.loadSignature(a);this.cryptoClient.verifyHash(o,c,this.rawPublicKey)||(s=!1)}),s);if(n)return(0,jA.hashSha256Async)(r).then(o=>i(o));{const o=(0,jA.hashSha256)(r);return i(o)}}}vk.TokenVerifier=Vat;var xk={};Object.defineProperty(xk,"__esModule",{value:!0});xk.decodeToken=void 0;const zA=Xo;function Hat(t){if(typeof t=="string"){const e=t.split("."),n=JSON.parse(zA.decode(e[0])),r=JSON.parse(zA.decode(e[1])),s=e[2];return{header:n,payload:r,signature:s}}else if(typeof t=="object"){if(typeof t.payload!="string")throw new Error("Expected token payload to be a base64 or json string");let e=t.payload;t.payload[0]!=="{"&&(e=zA.decode(e));const n=[];return t.header.map(r=>{const s=JSON.parse(zA.decode(r));n.push(s)}),{header:n,payload:JSON.parse(e),signature:t.signature}}}xk.decodeToken=Hat;(function(t){var e=kr&&kr.__createBinding||(Object.create?function(r,s,i,o){o===void 0&&(o=i);var a=Object.getOwnPropertyDescriptor(s,i);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[i]}}),Object.defineProperty(r,o,a)}:function(r,s,i,o){o===void 0&&(o=i),r[o]=s[i]}),n=kr&&kr.__exportStar||function(r,s){for(var i in r)i!=="default"&&!Object.prototype.hasOwnProperty.call(s,i)&&e(s,r,i)};Object.defineProperty(t,"__esModule",{value:!0}),n(Zv,t),n(vk,t),n(xk,t),n(ep,t),n(wk,t)})(bat);var qat;function Kat(t){return qat?.get(t)}var Gat;function Zat(t){return Gat?.get(t)}var Yat;function Xat(t,e){return Yat?.get(t)?.get(e)}function Ek(t){const e=typeof t;return e==="string"?`"${t}"`:e==="number"||e==="bigint"||e==="boolean"?`${t}`:e==="object"||e==="function"?(t&&Object.getPrototypeOf(t)?.constructor?.name)??"null":e}function oi(t,e,n,r,s){const i=s&&"input"in s?s.input:n.value,o=s?.expected??t.expects??null,a=s?.received??Ek(i),c={kind:t.kind,type:t.type,input:i,expected:o,received:a,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:t.requirement,path:s?.path,issues:s?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},l=t.kind==="schema",u=s?.message??t.message??Xat(t.reference,c.lang)??(l?Zat(c.lang):null)??r.message??Kat(c.lang);u&&(c.message=typeof u=="function"?u(c):u),l&&(n.typed=!1),n.issues?n.issues.push(c):n.issues=[c]}function jge(t,e){return Object.hasOwn(t,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}function Ck(t,e){const n=[...new Set(t)];return n.length>1?`(${n.join(` ${e} `)})`:n[0]??"never"}function zge(t,e){return{kind:"validation",type:"check",reference:zge,async:!1,expects:null,requirement:t,message:e,_run(n,r){return n.typed&&!this.requirement(n.value)&&oi(this,"input",n,r),n}}}function Wge(t,e){return{kind:"validation",type:"max_length",reference:Wge,async:!1,expects:`<=${t}`,requirement:t,message:e,_run(n,r){return n.typed&&n.value.length>this.requirement&&oi(this,"length",n,r,{received:`${n.value.length}`}),n}}}function Vge(t,e){return{kind:"validation",type:"min_length",reference:Vge,async:!1,expects:`>=${t}`,requirement:t,message:e,_run(n,r){return n.typed&&n.value.lengthisNaN(+r)).map(([,r])=>r);return{kind:"schema",type:"enum",reference:Qa,expects:Ck(n.map(Ek),"|"),async:!1,enum:t,options:n,message:e,_run(r,s){return this.options.includes(r.value)?r.typed=!0:oi(this,"type",r,s),r}}}function bn(t,e){return{kind:"schema",type:"literal",reference:bn,expects:Ek(t),async:!1,literal:t,message:e,_run(n,r){return n.value===this.literal?n.typed=!0:oi(this,"type",n,r),n}}}function qge(t,e){return{kind:"schema",type:"loose_object",reference:qge,expects:"Object",async:!1,entries:t,message:e,_run(n,r){const s=n.value;if(s&&typeof s=="object"){n.typed=!0,n.value={};for(const i in this.entries){const o=s[i],a=this.entries[i]._run({typed:!1,value:o},r);if(a.issues){const c={type:"object",origin:"value",input:s,key:i,value:o};for(const l of a.issues)l.path?l.path.unshift(c):l.path=[c],n.issues?.push(l);if(n.issues||(n.issues=a.issues),r.abortEarly){n.typed=!1;break}}a.typed||(n.typed=!1),(a.value!==void 0||i in s)&&(n.value[i]=a.value)}if(!n.issues||!r.abortEarly)for(const i in s)jge(s,i)&&!(i in this.entries)&&(n.value[i]=s[i])}else oi(this,"type",n,r);return n}}}function sW(t,e){return{kind:"schema",type:"non_optional",reference:sW,expects:"!undefined",async:!1,wrapped:t,message:e,_run(n,r){return n.value===void 0?(oi(this,"type",n,r),n):this.wrapped._run(n,r)}}}function Lo(t){return{kind:"schema",type:"null",reference:Lo,expects:"null",async:!1,message:t,_run(e,n){return e.value===null?e.typed=!0:oi(this,"type",e,n),e}}}function xi(t,...e){const n={kind:"schema",type:"nullish",reference:xi,expects:`(${t.expects} | null | undefined)`,async:!1,wrapped:t,_run(r,s){return(r.value===null||r.value===void 0)&&("default"in this&&(r.value=Hge(this,r,s)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped._run(r,s)}};return 0 in e&&(n.default=e[0]),n}function Ws(t){return{kind:"schema",type:"number",reference:Ws,expects:"number",async:!1,message:t,_run(e,n){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:oi(this,"type",e,n),e}}}function Ye(t,e){return{kind:"schema",type:"object",reference:Ye,expects:"Object",async:!1,entries:t,message:e,_run(n,r){const s=n.value;if(s&&typeof s=="object"){n.typed=!0,n.value={};for(const i in this.entries){const o=s[i],a=this.entries[i]._run({typed:!1,value:o},r);if(a.issues){const c={type:"object",origin:"value",input:s,key:i,value:o};for(const l of a.issues)l.path?l.path.unshift(c):l.path=[c],n.issues?.push(l);if(n.issues||(n.issues=a.issues),r.abortEarly){n.typed=!1;break}}a.typed||(n.typed=!1),(a.value!==void 0||i in s)&&(n.value[i]=a.value)}}else oi(this,"type",n,r);return n}}}function sn(t,...e){const n={kind:"schema",type:"optional",reference:sn,expects:`(${t.expects} | undefined)`,async:!1,wrapped:t,_run(r,s){return r.value===void 0&&("default"in this&&(r.value=Hge(this,r,s)),r.value===void 0)?(r.typed=!0,r):this.wrapped._run(r,s)}};return 0 in e&&(n.default=e[0]),n}function Kge(t,e){return{kind:"schema",type:"picklist",reference:Kge,expects:Ck(t.map(Ek),"|"),async:!1,options:t,message:e,_run(n,r){return this.options.includes(n.value)?n.typed=!0:oi(this,"type",n,r),n}}}function Gge(t,e,n){return{kind:"schema",type:"record",reference:Gge,expects:"Object",async:!1,key:t,value:e,message:n,_run(r,s){const i=r.value;if(i&&typeof i=="object"){r.typed=!0,r.value={};for(const o in i)if(jge(i,o)){const a=i[o],c=this.key._run({typed:!1,value:o},s);if(c.issues){const u={type:"object",origin:"key",input:i,key:o,value:a};for(const d of c.issues)d.path=[u],r.issues?.push(d);if(r.issues||(r.issues=c.issues),s.abortEarly){r.typed=!1;break}}const l=this.value._run({typed:!1,value:a},s);if(l.issues){const u={type:"object",origin:"value",input:i,key:o,value:a};for(const d of l.issues)d.path?d.path.unshift(u):d.path=[u],r.issues?.push(d);if(r.issues||(r.issues=l.issues),s.abortEarly){r.typed=!1;break}}(!c.typed||!l.typed)&&(r.typed=!1),c.typed&&(r.value[c.value]=l.value)}}else oi(this,"type",r,s);return r}}}function Ke(t){return{kind:"schema",type:"string",reference:Ke,expects:"string",async:!1,message:t,_run(e,n){return typeof e.value=="string"?e.typed=!0:oi(this,"type",e,n),e}}}function Vee(t){let e;if(t)for(const n of t)e?e.push(...n.issues):e=n.issues;return e}function dw(t,e){return{kind:"schema",type:"union",reference:dw,expects:Ck(t.map(n=>n.expects),"|"),async:!1,options:t,message:e,_run(n,r){let s,i,o;for(const a of this.options){const c=a._run({typed:!1,value:n.value},r);if(c.typed)if(c.issues)i?i.push(c):i=[c];else{s=c;break}else o?o.push(c):o=[c]}if(s)return s;if(i){if(i.length===1)return i[0];oi(this,"type",n,r,{issues:Vee(i)}),n.typed=!0}else{if(o?.length===1)return o[0];oi(this,"type",n,r,{issues:Vee(o)})}return n}}}function _k(){return{kind:"schema",type:"unknown",reference:_k,expects:"unknown",async:!1,_run(t){return t.typed=!0,t}}}function Zge(t,e,n){return{kind:"schema",type:"variant",reference:Zge,expects:"Object",async:!1,key:t,options:e,message:n,_run(r,s){const i=r.value;if(i&&typeof i=="object"){let o,a=0,c=this.key,l=[];const u=(d,f)=>{for(const p of d.options){if(p.type==="variant")u(p,new Set(f).add(p.key));else{let m=!0,y=0;for(const b of f){if(p.entries[b]._run({typed:!1,value:i[b]},s).issues){m=!1,c!==b&&(a{const t=Array(256).fill(-1);for(let e=0;e>25;return(33554431&d)<<5^996825010&-(f>>0&1)^642813549&-(f>>1&1)^513874426&-(f>>2&1)^1027748829&-(f>>3&1)^705979059&-(f>>4&1)}function i(d){let f=1;for(let p=0;p126)return"Invalid prefix ("+d+")";f=s(f)^m>>5}f=s(f);for(let p=0;p=p;)b-=p,x.push(y>>b&v);if(m)b>0&&x.push(y<=f)return"Excess padding";if(y<y)return"Exceeds length limit";const b=m.toLowerCase(),v=m.toUpperCase();if(m!==b&&m!==v)return"Mixed-case string "+m;const x=(m=b).lastIndexOf("1");if(x===-1)return"No separator character for "+m;if(x===0)return"Missing prefix for "+m;const E=m.slice(0,x),A=m.slice(x+1);if(A.length<6)return"Data too short";let _=i(E);if(typeof _=="string")return _;const k=[];for(let B=0;B=A.length||k.push(S)}return _!==f?"Invalid checksum for "+m:{prefix:E,words:k}}return f=d==="bech32"?1:734539939,{decodeUnsafe:function(m,y){const b=p(m,y);if(typeof b=="object")return b},decode:function(m,y){const b=p(m,y);if(typeof b=="object")return b;throw new Error(b)},encode:function(m,y,b){if(b=b||90,m.length+7+y.length>b)throw new TypeError("Exceeds length limit");let v=i(m=m.toLowerCase());if(typeof v=="string")throw new Error(v);let x=m+"1";for(let E=0;E>5)throw new Error("Non 5-bit word");v=s(v)^A,x+=n.charAt(A)}for(let E=0;E<6;++E)v=s(v);v^=f;for(let E=0;E<6;++E)x+=n.charAt(v>>5*(5-E)&31);return x},toWords:a,fromWordsUnsafe:c,fromWords:l}}e.bech32=u("bech32"),e.bech32m=u("bech32m")},Kee(yD={exports:{}},yD.exports),yD.exports);(WA=iW)&&WA.__esModule&&Object.prototype.hasOwnProperty.call(WA,"default")&&WA.default;iW.bech32m;iW.bech32;new Uint8Array(new Uint16Array([65279]).buffer)[0];var Wb,Vb;(function(t){t.mainnet="mainnet",t.testnet="testnet",t.regtest="regtest"})(Wb||(Wb={})),function(t){t.p2pkh="p2pkh",t.p2sh="p2sh",t.p2wpkh="p2wpkh",t.p2wsh="p2wsh",t.p2tr="p2tr"}(Vb||(Vb={}));Vb.p2pkh,Wb.mainnet,Vb.p2pkh,Wb.testnet,Vb.p2sh,Wb.mainnet,Vb.p2sh,Wb.testnet;var Jat=["software","ledger","keystone"],Yge=Kge(Jat),Ku=(t=>(t.Ordinals="ordinals",t.Payment="payment",t.Stacks="stacks",t))(Ku||{}),Xge=(t=>(t.p2pkh="p2pkh",t.p2sh="p2sh",t.p2wpkh="p2wpkh",t.p2wsh="p2wsh",t.p2tr="p2tr",t.stacks="stacks",t))(Xge||{}),Qge=Ye({address:Ke(),publicKey:Ke(),purpose:Qa(Ku),addressType:Qa(Xge),walletType:Yge}),id=(t=>(t.Mainnet="Mainnet",t.Testnet="Testnet",t.Testnet4="Testnet4",t.Signet="Signet",t.Regtest="Regtest",t))(id||{}),oW=sn(dw([Ke(),Ws(),Lo()])),Ar=Ye({jsonrpc:bn("2.0"),method:Ke(),params:sn(dw([bs(_k()),qge({}),Lo()])),id:Qat(oW)}),ect=Ye({jsonrpc:bn("2.0"),result:sW(_k()),id:oW}),tct=Ye({jsonrpc:bn("2.0"),error:sW(_k()),id:oW});dw([ect,tct]);var nct="accountChange";Ye({type:bn(nct),addresses:sn(bs(Qge))});var rct="networkChange";Ye({type:bn(rct),bitcoin:Ye({name:Qa(id)}),stacks:Ye({name:Ke()})});var sct="disconnect";Ye({type:bn(sct)});function Gee(){return window.btc_providers||(window.btc_providers=[]),window.btc_providers}function ict(t){return t?.split(".").reduce((e,n)=>e?.[n],window)}var oct="stx_callContract",act=Ye({contract:Ke(),functionName:Ke(),arguments:sn(bs(Ke())),functionArgs:sn(bs(Ke())),postConditions:sn(bs(Ke())),postConditionMode:sn(dw([bn("allow"),bn("deny")]))});Ye({...Ar.entries,...Ye({method:bn(oct),params:act,id:Ke()}).entries});var cct="stx_deployContract",lct=Ye({name:Ke(),clarityCode:Ke(),clarityVersion:sn(Ke()),postConditions:sn(bs(Ke())),postConditionMode:sn(dw([bn("allow"),bn("deny")]))});Ye({...Ar.entries,...Ye({method:bn(cct),params:lct,id:Ke()}).entries});var uct=Ye({read:sn(uw())}),dct=Ye({readNetwork:sn(uw())}),fct=Ye({type:bn("account"),resourceId:Ke(),clientId:Ke(),actions:uct}),hct=Ye({type:bn("wallet"),resourceId:Ke(),clientId:Ke(),actions:dct}),Jge=Zge("type",[Ye({...Hee(fct,["clientId"]).entries}),Ye({...Hee(hct,["clientId"]).entries})]),pct="wallet_requestPermissions",gct=xi(bs(Jge));bn(!0);Ye({...Ar.entries,...Ye({method:bn(pct),params:gct,id:Ke()}).entries});var mct="wallet_renouncePermissions",yct=xi(Lo());xi(Lo());Ye({...Ar.entries,...Ye({method:bn(mct),params:yct,id:Ke()}).entries});var wct="wallet_disconnect",bct=xi(Lo());xi(Lo());Ye({...Ar.entries,...Ye({method:bn(wct),params:bct,id:Ke()}).entries});var vct="wallet_getWalletType",xct=xi(Lo());Ye({...Ar.entries,...Ye({method:bn(vct),params:xct,id:Ke()}).entries});var Ect="wallet_getCurrentPermissions",Cct=xi(Lo());Ye({...Ar.entries,...Ye({method:bn(Ect),params:Cct,id:Ke()}).entries});var _ct="wallet_getNetwork",Sct=xi(Lo());Ye({bitcoin:Ye({name:Qa(id)}),stacks:Ye({name:Ke()})});Ye({...Ar.entries,...Ye({method:bn(_ct),params:Sct,id:Ke()}).entries});var Act="wallet_changeNetwork",Ict=Ye({name:Qa(id)});xi(Lo());Ye({...Ar.entries,...Ye({method:bn(Act),params:Ict,id:Ke()}).entries});var Tct="wallet_getAccount",Nct=xi(Lo());Ye({...Ar.entries,...Ye({method:bn(Tct),params:Nct,id:Ke()}).entries});var Pct="wallet_connect",kct=xi(Ye({permissions:sn(bs(Jge)),addresses:sn(bs(Qa(Ku))),message:sn(dB(Ke(),Wge(80,"The message must not exceed 80 characters."))),network:sn(Qa(id))}));Ye({...Ar.entries,...Ye({method:bn(Pct),params:kct,id:Ke()}).entries});var Rct="stx_getAccounts",Oct=xi(Lo());Ye({...Ar.entries,...Ye({method:bn(Rct),params:Oct,id:Ke()}).entries});var $ct="stx_getAddresses",Dct=xi(Ye({message:sn(Ke())}));Ye({...Ar.entries,...Ye({method:bn($ct),params:Dct,id:Ke()}).entries});var Mct="stx_signMessage",Lct=Ye({message:Ke()});Ye({...Ar.entries,...Ye({method:bn(Mct),params:Lct,id:Ke()}).entries});var Bct="stx_signStructuredMessage",Uct=Ye({domain:Ke(),message:Ke(),publicKey:sn(Ke())});Ye({...Ar.entries,...Ye({method:bn(Bct),params:Uct,id:Ke()}).entries});var Fct="stx_signTransaction",jct=Ye({transaction:Ke(),pubkey:sn(Ke()),broadcast:sn(uw())});Ye({...Ar.entries,...Ye({method:bn(Fct),params:jct,id:Ke()}).entries});var zct="stx_signTransactions",Wct=Ye({transactions:dB(bs(dB(Ke(),zge(t=>!0,"Invalid hex-encoded Stacks transaction."))),Vge(1)),broadcast:sn(uw())});Ye({...Ar.entries,...Ye({method:bn(zct),params:Wct,id:Ke()}).entries});var Vct="stx_transferStx",Hct=Ye({amount:dw([Ws(),Ke()]),recipient:Ke(),memo:sn(Ke()),version:sn(Ke()),postConditionMode:sn(Ws()),postConditions:sn(bs(Ke())),pubkey:sn(Ke())});Ye({...Ar.entries,...Ye({method:bn(Vct),params:Hct,id:Ke()}).entries});var qct="getInfo",Kct=xi(Lo());Ye({version:Ke(),methods:sn(bs(Ke())),supports:bs(Ke())});Ye({...Ar.entries,...Ye({method:bn(qct),params:Kct,id:Ke()}).entries});var Gct="getAddresses",Zct=Ye({purposes:bs(Qa(Ku)),message:sn(Ke())});Ye({...Ar.entries,...Ye({method:bn(Gct),params:Zct,id:Ke()}).entries});var Yct="signMessage",aW=(t=>(t.ECDSA="ECDSA",t.BIP322="BIP322",t))(aW||{}),Xct=Ye({address:Ke(),message:Ke(),protocol:sn(Qa(aW))});Ye({signature:Ke(),messageHash:Ke(),address:Ke(),protocol:Qa(aW)});Ye({...Ar.entries,...Ye({method:bn(Yct),params:Xct,id:Ke()}).entries});var Qct="sendTransfer",Jct=Ye({recipients:bs(Ye({address:Ke(),amount:Ws()}))});Ye({...Ar.entries,...Ye({method:bn(Qct),params:Jct,id:Ke()}).entries});var elt="signPsbt",tlt=Ye({psbt:Ke(),signInputs:Gge(Ke(),bs(Ws())),broadcast:sn(uw())});Ye({psbt:Ke(),txid:sn(Ke())});Ye({...Ar.entries,...Ye({method:bn(elt),params:tlt,id:Ke()}).entries});var nlt="getAccounts",rlt=Ye({purposes:bs(Qa(Ku)),message:sn(Ke())});bs(Ye({...Qge.entries,...Ye({walletType:Yge}).entries}));Ye({...Ar.entries,...Ye({method:bn(nlt),params:rlt,id:Ke()}).entries});var slt="getBalance";xi(Lo());Ye({...Ar.entries,...Ye({method:bn(slt),id:Ke()}).entries});var ilt="runes_etch",olt=Ye({amount:Ke(),cap:Ke(),heightStart:sn(Ke()),heightEnd:sn(Ke()),offsetStart:sn(Ke()),offsetEnd:sn(Ke())}),alt=Ye({contentType:Ke(),contentBase64:Ke()}),clt=Ye({runeName:Ke(),divisibility:sn(Ws()),symbol:sn(Ke()),premine:sn(Ke()),isMintable:uw(),delegateInscriptionId:sn(Ke()),destinationAddress:Ke(),refundAddress:Ke(),feeRate:Ws(),appServiceFee:sn(Ws()),appServiceFeeAddress:sn(Ke()),terms:sn(olt),inscriptionDetails:sn(alt),network:sn(Qa(id))});Ye({...Ar.entries,...Ye({method:bn(ilt),params:clt,id:Ke()}).entries});var llt="runes_getBalance",ult=xi(Lo());Ye({balances:bs(Ye({runeName:Ke(),amount:Ke(),divisibility:Ws(),symbol:Ke(),inscriptionId:xi(Ke()),spendableBalance:Ke()}))});Ye({...Ar.entries,...Ye({method:bn(llt),params:ult,id:Ke()}).entries});var dlt="runes_mint",flt=Ye({appServiceFee:sn(Ws()),appServiceFeeAddress:sn(Ke()),destinationAddress:Ke(),feeRate:Ws(),refundAddress:Ke(),repeats:Ws(),runeName:Ke(),network:sn(Qa(id))});Ye({...Ar.entries,...Ye({method:bn(dlt),params:flt,id:Ke()}).entries});var hlt="runes_transfer",plt=Ye({recipients:bs(Ye({runeName:Ke(),amount:Ke(),address:Ke()}))});Ye({...Ar.entries,...Ye({method:bn(hlt),params:plt,id:Ke()}).entries});var glt="ord_getInscriptions",mlt=Ye({offset:Ws(),limit:Ws()});Ye({total:Ws(),limit:Ws(),offset:Ws(),inscriptions:bs(Ye({inscriptionId:Ke(),inscriptionNumber:Ke(),address:Ke(),collectionName:sn(Ke()),postage:Ke(),contentLength:Ke(),contentType:Ke(),timestamp:Ws(),offset:Ws(),genesisTransaction:Ke(),output:Ke()}))});Ye({...Ar.entries,...Ye({method:bn(glt),params:mlt,id:Ke()}).entries});var ylt="ord_sendInscriptions",wlt=Ye({transfers:bs(Ye({address:Ke(),inscriptionId:Ke()}))});Ye({...Ar.entries,...Ye({method:bn(ylt),params:wlt,id:Ke()}).entries});var nf;(function(t){t.Ordinal="ordinal",t.Payment="payment",t.Stacks="stx"})(nf||(nf={}));function Zee(t){switch(t){case Ku.Payment:return nf.Payment;case Ku.Ordinals:return nf.Ordinal;case Ku.Stacks:return nf.Stacks;default:return}}class f3{constructor(){this.listeners={accountsChanged:[],chainChanged:[],connect:[],disconnect:[],display_uri:[],message:[]}}on(e,n){this.listeners[e].push(n)}removeListener(e,n){e in this.listeners&&(this.listeners[e]=this.listeners[e].filter(r=>r!==n))}emit(e,n){e in this.listeners&&this.listeners[e].forEach(r=>r(n))}}class Yee extends yk{constructor({provider:e,chains:n,getActiveChain:r}){super({provider:e,caipNetworks:n,namespace:"bip122"}),this.eventEmitter=new f3,this.emit=this.eventEmitter.emit.bind(this.eventEmitter),this.on=this.eventEmitter.on.bind(this.eventEmitter),this.removeListener=this.eventEmitter.removeListener.bind(this.eventEmitter),this.getActiveChain=r}get chains(){return this.sessionChains.map(e=>this.caipNetworks.find(n=>n.caipNetworkId===e)).filter(Boolean)}async connect(){return Promise.reject(new Error("Connection of WalletConnectProvider should be done via UniversalAdapter"))}async signMessage({message:e,address:n,protocol:r}){this.checkIfMethodIsSupported("signMessage");const s=await this.internalRequest({method:"signMessage",params:{message:e,account:n,address:n,protocol:r}});return Buffer.from(s.signature,"hex").toString("base64")}async sendTransfer({recipient:e,amount:n}){this.checkIfMethodIsSupported("sendTransfer");const r=this.getAccount(!0);return(await this.internalRequest({method:"sendTransfer",params:{account:r,recipientAddress:e,amount:n}})).txid}async getAccountAddresses(){return this.checkIfMethodIsSupported("getAccountAddresses"),(await this.internalRequest({method:"getAccountAddresses",params:void 0})).map(n=>({address:n,purpose:nf.Payment}))}async signPSBT(e){this.checkIfMethodIsSupported("signPsbt");const n=this.getAccount(!0),r=await this.internalRequest({method:"signPsbt",params:{account:n,psbt:e.psbt,signInputs:e.signInputs,broadcast:e.broadcast}});return{psbt:r.psbt,txid:r.txid}}async switchNetwork(e){return Promise.resolve()}request(e){return this.internalRequest(e)}get sessionChains(){return Ml.getChainsFromNamespaces(this.provider.session?.namespaces)}getAccount(e){const n=this.provider.session?.namespaces.bip122?.accounts[0];if(!n){if(e)throw new Error("Account not found");return}const r=n.split(":")[2];if(!r){if(e)throw new Error("Address not found");return}return r}checkIfMethodIsSupported(e){if(!this.provider.session?.namespaces.bip122?.methods.includes(e))throw new Error(`Method ${e} is not supported`)}async internalRequest({method:e,params:n}){const r=this.getActiveChain();if(!r)throw new Error("Chain not found");return await this.provider.request({method:e,params:n},r.caipNetworkId)}}function Xee(t){if(!t)throw new Error("mapCaipNetworkToXverseName: Invalid caipNetworkId provided");switch(t){case Jh.caipNetworkId:return id.Mainnet;case lw.caipNetworkId:return id.Testnet4;default:throw new Error(`Network ${t} not supported by Xverse wallet`)}}function blt(t){switch(t){case id.Mainnet:return Jh.caipNetworkId;case id.Testnet4:return lw.caipNetworkId;default:throw new Error(`Network ${t} not supported by Xverse wallet`)}}class h_ extends f3{constructor({provider:e,requestedChains:n,getActiveNetwork:r}){super(),this.chain="bip122",this.type="ANNOUNCED",this.requestedChains=[],this.walletUnsubscribes=[],this.wallet=e,this.requestedChains=n,this.provider=this,this.getActiveNetwork=r}get id(){return this.name}get name(){return this.wallet.name}get explorerId(){return vo.ConnectorExplorerIds[this.wallet.name]}get imageUrl(){return this.wallet.icon}get chains(){return this.requestedChains.filter(e=>e.chainNamespace==="bip122")}async request(e){return this.internalRequest(e.method,e.params)}async connect(){const e=this.getActiveNetwork(),n=Xee(e?.caipNetworkId),r=await this.getAccountAddresses().then(s=>s[0]?.address).catch(()=>this.internalRequest("wallet_connect",{network:n}).then(s=>s?.addresses.map(i=>({...i,purpose:Zee(i.purpose)})).find(i=>i.purpose===nf.Payment)?.address));if(!r)throw new Error("No address available");return this.bindEvents(),this.emit("accountsChanged",[r]),r}async disconnect(){await this.internalRequest("wallet_disconnect",null),this.unbindEvents()}async getAccountAddresses(){const e=await this.internalRequest("getAddresses",{purposes:[Ku.Payment,Ku.Ordinals,Ku.Stacks],message:"Connect to your wallet"});if(e.addresses.length===0)throw new Error("No address available");return e.addresses.map(n=>({...n,purpose:Zee(n.purpose)}))}static hasProviders(){return De.isClient()?Gee().length>0:!1}static async getWallets({requestedChains:e,getActiveNetwork:n}){return De.isClient()?(await Jn.withRetry({conditionFn:()=>h_.hasProviders(),intervalMs:200,maxRetries:3}),Gee().map(s=>new h_({provider:s,requestedChains:e,getActiveNetwork:n}))):[]}async signMessage(e){const n=e.protocol?.toUpperCase();return(await this.internalRequest("signMessage",{...e,protocol:n})).signature}async signPSBT(e){const n=e.signInputs.reduce((s,i)=>{const o=s[i.address]||[];return o.push(i.index),{...s,[i.address]:o}},{});return await this.internalRequest("signPsbt",{psbt:e.psbt,broadcast:e.broadcast,signInputs:n})}async switchNetwork(e){const n=Xee(e);await this.internalRequest("wallet_changeNetwork",{name:n})}async sendTransfer({amount:e,recipient:n}){const r=Number(e);if(isNaN(r))throw new Error("Invalid amount");return(await this.internalRequest("sendTransfer",{recipients:[{address:n,amount:r}]})).txid}getWalletProvider(){return ict(this.wallet.id)}async internalRequest(e,n){const r=await this.getWalletProvider().request(e,n).catch(s=>{if("jsonrpc"in s&&"error"in s)return s;throw s});if("result"in r)return r.result;throw{...r.error,name:"RPCError"}}bindEvents(){this.unbindEvents();const e=this.getWalletProvider();if(typeof e.addListener!="function"){console.warn(`SatsConnectConnector:bindEvents - wallet provider "${this.name}" does not support events`);return}this.walletUnsubscribes.push(e.addListener("accountChange",async n=>{const r=await this.connect();this.emit("accountsChanged",[r])}),e.addListener("disconnect",n=>{this.emit("disconnect")}),e.addListener("networkChange",n=>{const r=blt(n.stacks.name);this.emit("chainChanged",r)}))}unbindEvents(){this.walletUnsubscribes.forEach(e=>e()),this.walletUnsubscribes=[]}}class p_ extends h_{constructor({connector:e}){if(e.wallet.id!==p_.ProviderId)throw new Error("LeatherConnector: wallet must be a LeatherProvider");super({provider:e.wallet,requestedChains:e.requestedChains,getActiveNetwork:e.getActiveNetwork})}get imageUrl(){return this.wallet?.icon?.replace("data:image/svg","data:image/svg+xml")}async getAccountAddresses(){return this.connectedAccounts?this.connectedAccounts:(this.connectedAccounts=await super.getAccountAddresses(),this.connectedAccounts)}disconnect(){return this.connectedAccounts=void 0,Promise.resolve()}async sendTransfer({amount:e,recipient:n}){const r={address:n,amount:e};return(await this.internalRequest("sendTransfer",r)).txid}async signPSBT({psbt:e,broadcast:n=!1}){const r={hex:Buffer.from(e,"base64").toString("hex"),network:this.getNetwork(),broadcast:n},s=await this.internalRequest("signPsbt",r);return{psbt:Buffer.from(s.hex,"hex").toString("base64"),txid:s.txid}}getNetwork(){switch(this.getActiveNetwork()?.caipNetworkId){case Jh.caipNetworkId:return"mainnet";case lw.caipNetworkId:return"testnet";default:throw new Error("LeatherConnector: unsupported network")}}}p_.ProviderId="LeatherProvider";class Hb extends Error{constructor(e,n,r){super("Wallet call is not supported"),this.name="MethodNotSupported",this.method=n,this.walletId=e,console.error(`BitcoinAdapter:MethodNotSupportedError:${e} - The connected wallet doesn't support the method "${n}".${r?` ${r}`:""}`)}}const cW={parseSatoshis(t,e){const n=parseFloat(t)/10**e.nativeCurrency.decimals;return Intl.NumberFormat("en-US",{maximumFractionDigits:e.nativeCurrency.decimals}).format(n)}},vlt={[Jh.caipNetworkId]:"bitcoin",[lw.caipNetworkId]:"bitcoinTestnet"};class ZT extends f3{constructor({wallet:e,requestedChains:n,getActiveNetwork:r,imageUrl:s,requestedCaipNetworkId:i}){super(),this.id="OKX",this.name="OKX Wallet",this.chain="bip122",this.type="ANNOUNCED",this.explorerId=vo.ConnectorExplorerIds[ye.CONNECTOR_ID.OKX],this.provider=this,this.requestedChains=[],this.wallet=e,this.requestedChains=n,this.getActiveNetwork=r,this.imageUrl=s,this.requestedCaipNetworkId=i}get chains(){return this.requestedChains.filter(e=>e.caipNetworkId===this.getActiveNetwork()?.caipNetworkId)}async connect(){const e=await this.wallet.connect();return this.bindEvents(),this.emit("accountsChanged",[e.address]),e.address}async disconnect(){this.unbindEvents(),await this.wallet.disconnect()}async getAccountAddresses(){const e=await this.wallet.getAccounts(),n=await this.wallet.getPublicKey();return e.map(s=>({address:s,purpose:nf.Payment,publicKey:n}))}async signMessage(e){const n=e.protocol==="bip322"?"bip322-simple":e.protocol;return this.wallet.signMessage(e.message,n)}async sendTransfer(e){const n=this.getActiveNetwork();if(!n)throw new Error("No active network available");const r=(await this.wallet.getAccounts())[0];if(!r)throw new Error("No account available");return(await this.wallet.send({from:r,to:e.recipient,value:cW.parseSatoshis(e.amount,n)})).txhash}async signPSBT(e){const n=Buffer.from(e.psbt,"base64").toString("hex"),r=await this.wallet.signPsbt(n);let s;return e.broadcast&&(s=await this.wallet.pushPsbt(r)),{psbt:Buffer.from(r,"hex").toString("base64"),txid:s}}async switchNetwork(e){const n=ZT.getWallet({requestedChains:this.requestedChains,getActiveNetwork:this.getActiveNetwork,requestedCaipNetworkId:e});if(!n)throw new Error(`${this.name} wallet does not support network switching`);this.unbindEvents(),this.wallet=n.wallet;try{await this.connect()}catch{throw new Error(`${this.name} wallet does not support network switching`)}}request(e){return Promise.reject(new Hb(this.id,"request"))}bindEvents(){this.unbindEvents(),this.wallet.on("accountChanged",e=>{typeof e=="object"&&e&&"address"in e&&this.emit("accountsChanged",[e.address])}),this.wallet.on("disconnect",()=>{this.emit("disconnect")})}unbindEvents(){this.wallet.removeAllListeners()}static getWallet(e){if(!De.isClient())return;let n;const r=window?.okxwallet,s=vlt[e.requestedCaipNetworkId];n=r?.[s]||r?.bitcoin;const i=r?.cardano?.icon||"";if(n)return new ZT({wallet:n,imageUrl:i,...e})}async getPublicKey(){return this.wallet.getPublicKey()}}class lW extends f3{constructor({id:e,name:n,wallet:r,requestedChains:s,getActiveNetwork:i,imageUrl:o}){super(),this.chain="bip122",this.type="ANNOUNCED",this.provider=this,this.requestedChains=[],this.id=e,this.name=n,this.wallet=r,this.requestedChains=s,this.getActiveNetwork=i,this.imageUrl=o}get chains(){return this.id==="unisat"?this.requestedChains.filter(e=>e.caipNetworkId===Jh.caipNetworkId):this.requestedChains.filter(e=>e.chainNamespace===ye.CHAIN.BITCOIN)}async connect(){const[e]=await this.wallet.requestAccounts();if(!e)throw new Error("No account found");return this.bindEvents(),this.emit("accountsChanged",[e]),e}async disconnect(){return this.unbindEvents(),Promise.resolve()}async getAccountAddresses(){const e=await this.wallet.requestAccounts(),n=await this.wallet.getPublicKey();return e.map(s=>({address:s,purpose:nf.Payment,publicKey:n}))}async signMessage(e){const n=e.protocol==="bip322"?"bip322-simple":e.protocol;return this.wallet.signMessage(e.message,n)}async sendTransfer(e){const n=this.getActiveNetwork();if(!n)throw new Error("No active network available");if(!(await this.wallet.getAccounts())[0])throw new Error("No account available");return await this.wallet.sendBitcoin(e.recipient,Number(cW.parseSatoshis(e.amount,n)))}async signPSBT(e){const n=Buffer.from(e.psbt,"base64").toString("hex"),r=await this.wallet.signPsbt(n);let s;return e.broadcast&&(s=await this.wallet.pushPsbt(r)),{psbt:Buffer.from(r,"hex").toString("base64"),txid:s}}async switchNetwork(e){const n=this.getNetwork(e);await this.wallet.switchChain(n)}request(e){return Promise.reject(new Hb(this.id,"request"))}onAccountsChanged(e){typeof e=="object"&&e&&"address"in e&&this.emit("accountsChanged",[e.address])}bindEvents(){this.unbindEvents(),this.wallet.on("accountsChanged",this.onAccountsChanged.bind(this))}unbindEvents(){this.wallet.removeListener("accountsChanged",this.onAccountsChanged.bind(this))}static getWallet(e){if(!De.isClient())return;const n=window;let r;switch(e.id){case"unisat":r=n?.unisat;break;case"bitget":r=n?.bitkeep?.unisat;break;case"binancew3w":r=n?.binancew3w?.bitcoin;break;default:throw new Error(`Unsupported wallet id: ${e.id}`)}if(r)return new lW({wallet:r,...e})}async getPublicKey(){return this.wallet.getPublicKey()}getNetwork(e){switch(e){case Jh.caipNetworkId:return"BITCOIN_MAINNET";case lw.caipNetworkId:return"BITCOIN_TESTNET";default:throw new Error("UnisatConnector: unsupported network")}}}var xlt=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},Elt=function(t,e,n,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(t,n):s?s.value=n:e.set(t,n),n},n6;let w2;const Sk=new Set;function Clt(t){RE=void 0,Sk.add(t)}function _lt(t){RE=void 0,Sk.delete(t)}const qb={};function Slt(){if(w2||(w2=Object.freeze({register:Qee,get:Alt,on:Ilt}),typeof window>"u"))return w2;const t=Object.freeze({register:Qee});try{window.addEventListener("wallet-standard:register-wallet",({detail:e})=>e(t))}catch(e){console.error(`wallet-standard:register-wallet event listener could not be added +`,e)}try{window.dispatchEvent(new Tlt(t))}catch(e){console.error(`wallet-standard:app-ready event could not be dispatched +`,e)}return w2}function Qee(...t){return t=t.filter(e=>!Sk.has(e)),t.length?(t.forEach(e=>Clt(e)),qb.register?.forEach(e=>Jee(()=>e(...t))),function(){t.forEach(n=>_lt(n)),qb.unregister?.forEach(n=>Jee(()=>n(...t)))}):()=>{}}let RE;function Alt(){return RE||(RE=[...Sk]),RE}function Ilt(t,e){return qb[t]?.push(e)||(qb[t]=[e]),function(){qb[t]=qb[t]?.filter(r=>e!==r)}}function Jee(t){try{t()}catch(e){console.error(e)}}class Tlt extends Event{get detail(){return xlt(this,n6,"f")}get type(){return"wallet-standard:app-ready"}constructor(e){super("wallet-standard:app-ready",{bubbles:!1,cancelable:!1,composed:!1}),n6.set(this,void 0),Elt(this,n6,e,"f")}preventDefault(){throw new Error("preventDefault cannot be called")}stopImmediatePropagation(){throw new Error("stopImmediatePropagation cannot be called")}stopPropagation(){throw new Error("stopPropagation cannot be called")}}n6=new WeakMap;class uW extends f3{constructor({wallet:e,requestedChains:n}){super(),this.chain="bip122",this.type="ANNOUNCED",this.requestedChains=[],this.provider=this,this.wallet=e,this.requestedChains=n,this.provider=this}get id(){return this.name}get name(){return this.wallet.name}get imageUrl(){return this.wallet.icon}get explorerId(){return vo.ConnectorExplorerIds[this.name]}get chains(){return this.wallet.chains.map(e=>this.requestedChains.find(n=>{switch(e){case"bitcoin:mainnet":return n.caipNetworkId===Jh.caipNetworkId;case"bitcoin:testnet":return n.caipNetworkId===lw.caipNetworkId;default:return n.caipNetworkId===e}})).filter(Boolean)}async connect(){const r=(await this.getWalletFeature("bitcoin:connect").connect({purposes:["payment","ordinals"]})).accounts[0];if(!r)throw new Error("No account found");return r.address}async getAccountAddresses(){const e=new Set,n=this.wallet.accounts.map(r=>({address:r.address,purpose:nf.Payment,publicKey:Buffer.from(r.publicKey).toString("hex")})).filter(r=>e.has(r.address)?!1:(e.add(r.address),!0));return Promise.resolve(n)}async signMessage(e){e.protocol&&console.warn("WalletStandardConnector:signMessage - protocol parameter not supported in WalletStandard:bitcoin - signMessage");const n=this.getWalletFeature("bitcoin:signMessage"),r=this.wallet.accounts.find(o=>o.address===e.address);if(!r)throw new Error("Account not found");const s=new TextEncoder().encode(e.message),i=(await n.signMessage({account:r,message:s}))[0];if(!i)throw new Error("No response from wallet");return Buffer.from(i.signature).toString("base64")}async signPSBT(e){const n=this.getWalletFeature("bitcoin:signTransaction");if(e.broadcast)throw new Hb(this.id,"signPSBT","This wallet does not support broadcasting, please broadcast it manually or contact the development team.");const r=e.signInputs.map(i=>{const o=this.wallet.accounts.find(a=>a.address===i.address);if(!o)throw new Error(`Account with address ${i.address} not found`);return{account:o,signingIndexes:[i.index],sigHash:void 0}}),s=(await n.signTransaction({psbt:new Uint8Array(Buffer.from(e.psbt,"base64")),inputsToSign:r}))[0];if(!s)throw new Error("No response from wallet");return{psbt:Buffer.from(s.signedPsbt).toString("base64"),txid:void 0}}async sendTransfer(e){return Promise.reject(new Hb(this.id,"sendTransfer",'Please use "signPSBT" instead and broadcast the transaction manually.'))}async disconnect(){return Promise.resolve()}async request(e){return Promise.reject(new Hb(this.id,"request"))}getWalletFeature(e){if(!(e in this.wallet.features))throw new Hb(this.id,e);return this.wallet.features[e]}static watchWallets({callback:e,requestedChains:n}){const{get:r,on:s}=Slt();function i(o){return o.filter(a=>"bitcoin:connect"in a.features).map(a=>new uW({wallet:a,requestedChains:n}))}return e(...i(r())),s("register",(...o)=>e(...i(o)))}async switchNetwork(e){const n=this.wallet.features["bitcoin:switchNetwork"];if(n&&typeof n.switchNetwork=="function"){await n.switchNetwork(e),this.emit("change",{accounts:this.wallet.accounts});return}throw new Error(`${this.name} wallet does not support network switching`)}}const Nlt={getUTXOs:async({network:t,address:e})=>{const n=t.caipNetworkId===lw.caipNetworkId,r=await fetch(`https://mempool.space${n?"/testnet":""}/api/address/${e}/utxo`);return r.ok?await r.json():(console.warn(`Failed to fetch UTXOs: ${await r.text()}`),[])}},Plt=[{id:"unisat",name:"Unisat Wallet",imageUrl:"https://imagedelivery.net/_aTEfDRm7z3tKgu9JhfeKA/530e8a71-f014-46e5-1302-26d1eff60200/sm"},{id:"bitget",name:"Bitget Wallet",imageUrl:De.isClient()?window?.bitkeep?.suiWallet?.icon??"":""},{id:"binancew3w",name:"Binance Web3 Wallet",imageUrl:"https://imagedelivery.net/_aTEfDRm7z3tKgu9JhfeKA/7c1961a6-9c4c-4632-8710-d02a43df1300/sm"}];class klt extends nW{constructor({api:e={},...n}={}){super({namespace:ye.CHAIN.BITCOIN,adapterType:ye.ADAPTER_TYPES.BITCOIN,...n}),this.balancePromises={},this.universalProvider=void 0,this.api={...Nlt,...e}}async connect(e){const n=this.connectors.find(a=>a.id===e.id);if(!n)throw new Error("connectionControllerClient:connectExternal - connector is undefined");const r=n.chains.find(a=>a.id===e.chainId)||n.chains[0];if(!r)throw new Error("The connector does not support any of the requested chains");const s=this.connectionManager?.getConnection({address:e.address,connectorId:n.id,connections:this.connections,connectors:this.connectors});if(s?.account)return this.emit("accountChanged",{address:s.account.address,chainId:s.caipNetwork?.id,connector:n}),{id:n.id,type:n.type,address:s.account.address,chainId:r.id,provider:n.provider};const i=await n.connect(),o=await this.getAccounts({id:n.id});return this.emit("accountChanged",{address:i,chainId:r.id,connector:n}),this.addConnection({connectorId:n.id,accounts:o.accounts.map(a=>({address:a.address,type:a.type})),caipNetwork:r}),n.id!==ye.CONNECTOR_ID.WALLET_CONNECT&&this.listenProviderEvents(n.id,n),{id:n.id,type:n.type,address:i,chainId:r.id,provider:n.provider}}async getAccounts(e){let r=(await this.connectors.find(s=>s.id===e.id)?.getAccountAddresses().catch(()=>[]))?.map(s=>De.createAccount(ye.CHAIN.BITCOIN,s.address,s.purpose||"payment",s.publicKey,s.path));return r&&r.length>1&&(r=[{namespace:ye.CHAIN.BITCOIN,publicKey:r[Al.ACCOUNT_INDEXES.PAYMENT]?.publicKey??"",path:r[Al.ACCOUNT_INDEXES.PAYMENT]?.path??"",address:r[Al.ACCOUNT_INDEXES.PAYMENT]?.address??"",type:"payment"},{namespace:ye.CHAIN.BITCOIN,publicKey:r[Al.ACCOUNT_INDEXES.ORDINAL]?.publicKey??"",path:r[Al.ACCOUNT_INDEXES.ORDINAL]?.path??"",address:r[Al.ACCOUNT_INDEXES.ORDINAL]?.address??"",type:"ordinal"}]),{accounts:r||[]}}async syncConnectors(e,n){function r(){return n?.getCaipNetwork(ye.CHAIN.BITCOIN)}uW.watchWallets({callback:this.addConnector.bind(this),requestedChains:this.networks});const s=await h_.getWallets({requestedChains:this.networks,getActiveNetwork:r});this.addConnector(...s.map(o=>{switch(o.wallet.id){case p_.ProviderId:return new p_({connector:o});default:return o}}));const i=ZT.getWallet({requestedChains:this.networks,getActiveNetwork:r,requestedCaipNetworkId:r()?.caipNetworkId});i&&this.addConnector(i),Plt.forEach(o=>{const a=lW.getWallet({...o,requestedChains:this.networks,getActiveNetwork:r});a&&this.addConnector(a)})}syncConnection(e){return this.connect({id:e.id,chainId:e.chainId,type:""})}async syncConnections({connectToFirstConnector:e,caipNetwork:n,getConnectorStorageInfo:r}){await this.connectionManager?.syncConnections({connectors:this.connectors,caipNetwork:n,caipNetworks:this.getCaipNetworks(),universalProvider:this.universalProvider,onConnection:this.addConnection.bind(this),onListenProvider:this.listenProviderEvents.bind(this),getConnectionStatusInfo:r}),e&&this.emitFirstAvailableConnection()}async disconnectAll(){return{connections:await Promise.all(this.connections.map(async n=>{const r=this.connectors.find(s=>Jn.isLowerCaseMatch(s.id,n.connectorId));if(!r)throw new Error("Connector not found");return await this.disconnect({id:r.id}),n}))}}async signMessage(e){const n=e.provider;if(!n)throw new Error("BitcoinAdapter:signMessage - connector is undefined");return{signature:await n.signMessage({message:e.message,address:e.address})}}getWalletConnectProvider(e){return new Yee({provider:e.provider,chains:e.caipNetworks,getActiveChain:()=>G.getCaipNetworkByNamespace(this.namespace)})}async disconnect(e){if(e.id){const n=this.connectors.find(s=>Jn.isLowerCaseMatch(s.id,e.id));if(!n?.provider)throw new Error("BitcoinAdapter:disconnect - connector.provider is undefined");const r=this.connectionManager?.getConnection({connectorId:e.id,connections:this.connections,connectors:this.connectors});return await n.provider.disconnect(),this.removeProviderListeners(n.id),this.deleteConnection(n.id),this.connections.length===0?this.emit("disconnect"):this.emitFirstAvailableConnection(),{connections:r?[r]:[]}}return this.disconnectAll()}async getBalance(e){const n=e.caipNetwork,r=e.address;if(!r)return Promise.resolve({balance:"0.00",symbol:"BTC"});if(n&&n.chainNamespace===this.namespace){const s=`${n?.caipNetworkId}:${r}`,i=this.balancePromises[s];if(i)return i;const o=Ge.getNativeBalanceCacheForCaipAddress(s);return o?{balance:o.balance,symbol:o.symbol}:(this.balancePromises[s]=new Promise(async a=>{const l=(await this.api.getUTXOs({network:n,address:r})).reduce((d,f)=>d+f.value,0),u=cW.parseSatoshis(l.toString(),n);Ge.updateNativeBalanceCache({caipAddress:s,balance:u,symbol:n.nativeCurrency.symbol,timestamp:Date.now()}),a({balance:u,symbol:n.nativeCurrency.symbol})}).finally(()=>{delete this.balancePromises[s]}),this.balancePromises[s]||Promise.resolve({balance:"0.00",symbol:"BTC"}))}return Promise.resolve({balance:"0",symbol:Jh.nativeCurrency.symbol})}async switchNetwork(e){if(e.providerType==="WALLET_CONNECT"||e.providerType==="AUTH")return await super.switchNetwork(e);const n=e.provider;if(!n)throw new Error("BitcoinAdapter:switchNetwork - provider is undefined");return await n.switchNetwork(e.caipNetwork.caipNetworkId)}estimateGas(e){return Promise.resolve({})}sendTransaction(e){return Promise.resolve({})}writeContract(e){return Promise.resolve({})}parseUnits(e){return BigInt(0)}formatUnits(e){return""}grantPermissions(e){return Promise.resolve({})}getCapabilities(e){return Promise.resolve({})}revokePermissions(e){return Promise.resolve("0x")}async walletGetAssets(e){return Promise.resolve({})}async onChainChanged(e,n){const r=this.connectors.find(a=>a.id===n);if(!r)throw new Error("BitcoinAdapter:onChainChanged - connector is undefined");const{address:s}=await this.connect({id:r.id,chainId:e,type:""}),i=await this.getAccounts({id:r.id}),o=r.chains.find(a=>a.id===e)||r.chains[0];Jn.isLowerCaseMatch(this.getConnectorId(ye.CHAIN.BITCOIN),r.id)&&this.emit("switchNetwork",{chainId:e,address:s}),this.addConnection({connectorId:r.id,accounts:i.accounts.map(a=>({address:a.address,type:a.type})),caipNetwork:o})}setAuthProvider(){}async setUniversalProvider(e){this.universalProvider=e;const n=ye.CONNECTOR_ID.WALLET_CONNECT;return Ml.listenWcProvider({universalProvider:e,namespace:ye.CHAIN.BITCOIN,onConnect:r=>this.onConnect(r,n),onDisconnect:()=>this.onDisconnect(n),onAccountsChanged:r=>this.onAccountsChanged(r,n,!1)}),this.addConnector(new Yee({provider:e,chains:this.getCaipNetworks(),getActiveChain:()=>G.getCaipNetworkByNamespace(this.namespace)})),Promise.resolve()}}function Rlt(t){let e=[],n,r;function s(a){return jC.parseEvmChainId(a)||1}function i(){return n||(n=qm.getInstance({projectId:t.options.projectId,chainId:vm()?.caipNetworkId,enableLogger:t.options.enableAuthLogger,onTimeout:a=>{a==="iframe_load_failed"?Xr.open(fs.ALERT_ERRORS.IFRAME_LOAD_FAILED,"error"):a==="iframe_request_timeout"?Xr.open(fs.ALERT_ERRORS.IFRAME_REQUEST_TIMEOUT,"error"):a==="unverified_domain"&&Xr.open(fs.ALERT_ERRORS.UNVERIFIED_DOMAIN,"error")},abortController:fs.EmbeddedWalletAbortController,getActiveCaipNetwork:a=>vm(a),getCaipNetworks:a=>G.getCaipNetworks(a)})),n}async function o(a={}){const c=i();let l=a.chainId;if(a.isReconnecting){const y=jC.parseEvmChainId(c.getLastUsedChainId()||""),b=t.chains?.[0].id;if(l=y||b,!l)throw new Error("ChainId not found in provider")}const u=Ss("eip155"),{address:d,chainId:f,accounts:p}=await Da.authConnectorAuthenticate({authConnector:c,chainId:l,preferredAccountType:u,socialUri:a.socialUri,chainNamespace:ye.CHAIN.EVM});e=p?.map(y=>y.address)||[d];const m=s(f);return{accounts:e,account:d,chainId:m,chain:{id:m,unsuported:!1}}}return a=>({id:ye.CONNECTOR_ID.AUTH,name:ye.CONNECTOR_NAMES.AUTH,type:"AUTH",chain:ye.CHAIN.EVM,async connect(c={}){if(r)return r;r||(r=new Promise(u=>{u(o(c))}));const l=await r;return r=void 0,l},async disconnect(){await(await this.getProvider()).disconnect()},getAccounts(){return e?.length?(a.emitter.emit("change",{accounts:e}),Promise.resolve(e)):Promise.resolve([])},async getProvider(){return this.provider||(this.provider=qm.getInstance({projectId:t.options.projectId,chainId:vm()?.caipNetworkId,enableLogger:t.options.enableAuthLogger,abortController:fs.EmbeddedWalletAbortController,onTimeout:c=>{c==="iframe_load_failed"?Xr.open(fs.ALERT_ERRORS.IFRAME_LOAD_FAILED,"error"):c==="iframe_request_timeout"?Xr.open(fs.ALERT_ERRORS.IFRAME_REQUEST_TIMEOUT,"error"):c==="unverified_domain"&&Xr.open(fs.ALERT_ERRORS.UNVERIFIED_DOMAIN,"error")},getActiveCaipNetwork:c=>vm(c),getCaipNetworks:c=>G.getCaipNetworks(c)})),Promise.resolve(this.provider)},async getChainId(){const c=await this.getProvider(),{chainId:l}=await c.getChainId();return s(l)},async isAuthorized(){const l=G.state.activeChain===ye.CHAIN.EVM;if(ye.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(f=>ke.getConnectorId(f)===ye.CONNECTOR_ID.AUTH)&&!l)return!1;const d=await this.getProvider();return Promise.resolve(d.getLoginEmailUsed())},async switchChain({chainId:c}){try{const l=a.chains.find(p=>p.id===c);if(!l)throw new df(new Error("chain not found on connector."));const u=await this.getProvider(),d=Ss("eip155"),f=await u.connect({chainId:c,preferredAccountType:d});return e=f?.accounts?.map(p=>p.address)||[f.address],a.emitter.emit("change",{chainId:Number(c),accounts:e}),l}catch(l){throw l instanceof Error?new df(l):l}},onAccountsChanged(c){c.length===0?this.onDisconnect():a.emitter.emit("change",{accounts:c.map(wh)})},onChainChanged(c){const l=Number(c);a.emitter.emit("change",{chainId:l})},async onDisconnect(c){await(await this.getProvider()).disconnect()}})}dW.type="walletConnect";function dW(t,e){const n=t.isNewChainsStale??!0;let r,s,i,o,a,c,l;return u=>({id:"walletConnect",name:"WalletConnect",type:dW.type,async setup(){const d=await this.getProvider().catch(()=>null);d&&(o||(o=this.onConnect.bind(this),d.on("connect",o)),c||(c=this.onSessionDelete.bind(this),d.on("session_delete",c)))},async connect({...d}={}){try{const f=G.getCaipNetworks(),p=await this.getProvider();if(!p)throw new fh;a||(a=this.onDisplayUri,p.on("display_uri",a));const m=await this.isChainsStale();p.session&&m&&await p.disconnect();const y=_e.state.universalProviderConfigOverride;if(!p.session||m){const k=Ml.createNamespaces(f,y);await p.connect({optionalNamespaces:k,..."pairingTopic"in d?{pairingTopic:d.pairingTopic}:{}}),this.setRequestedChainsIds(f.map(B=>Number(B.id)))}const b=await this.getAccounts(),v=await this.getChainId(),x=p.session?.namespaces?.eip155?.chains,E=x?.some(k=>Number(k.split(":")[1])===v);let A=1;E?A=v:x?.[0]&&(A=Number(x[0].split(":")[1])),a&&(p.removeListener("display_uri",a),a=void 0),o&&(p.removeListener("connect",o),o=void 0),s||(s=this.onAccountsChanged.bind(this),p.on("accountsChanged",s)),i||(i=this.onChainChanged.bind(this),p.on("chainChanged",i)),l||(l=this.onDisconnect.bind(this),p.on("disconnect",l)),c||(c=this.onSessionDelete.bind(this),p.on("session_delete",c));const _=y?.defaultChain;return p.setDefaultChain(_??`eip155:${A}`),{accounts:b,chainId:A}}catch(f){throw/(user rejected|connection request reset)/i.test(f?.message)?new ti(f):f}},async disconnect(){const d=await this.getProvider();try{await d?.disconnect()}catch(f){if(!/No matching key/i.test(f.message))throw f}finally{i&&(d?.removeListener("chainChanged",i),i=void 0),l&&(d?.removeListener("disconnect",l),l=void 0),o||(o=this.onConnect.bind(this),d?.on("connect",o)),s&&(d?.removeListener("accountsChanged",s),s=void 0),c&&(d?.removeListener("session_delete",c),c=void 0),this.setRequestedChainsIds([])}},async getAccounts(){const d=await this.getProvider();if(!d?.session?.namespaces)return[];const p=d?.session?.namespaces[ye.CHAIN.EVM]?.accounts?.map(b=>b.split(":")[2])??[],m=new Set;return p.filter(b=>{const v=b?.toLowerCase();return m.has(v)?!1:(m.add(v),!0)})},async getProvider({chainId:d}={}){r||(r=await e.getUniversalProvider(),r?.events.setMaxListeners(Number.POSITIVE_INFINITY));const f=Ge.getActiveNamespace(),p=e.getCaipNetwork()?.id;if(d&&p!==d&&f){const m=Ge.getStoredActiveCaipNetworkId(),b=(f?e.getCaipNetworks(f):[])?.find(v=>v.id===m);b&&b.chainNamespace===ye.CHAIN.EVM&&await this.switchChain?.({chainId:Number(b.id)})}return r},async getChainId(){const d=e.getCaipNetwork(ye.CHAIN.EVM)?.id;if(d)return d;const p=(await this.getProvider()).session?.namespaces[ye.CHAIN.EVM]?.chains?.[0];return G.getCaipNetworks().find(y=>y.id===p)?.id},async isAuthorized(){try{const[d,f]=await Promise.all([this.getAccounts(),this.getProvider()]);return d.length?await this.isChainsStale()&&f.session?(await f.disconnect().catch(()=>{}),!1):!0:!1}catch{return!1}},async switchChain({addEthereumChainParameter:d,chainId:f}){const p=await this.getProvider();if(!p)throw new fh;const m=G.getCaipNetworks().find(y=>y.id===f);if(!m)throw new df(new Uv);try{await p.request({method:"wallet_switchEthereumChain",params:[{chainId:$n(f)}]}),m?.caipNetworkId&&p.setDefaultChain(m?.caipNetworkId),u.emitter.emit("change",{chainId:Number(f)});const y=await this.getRequestedChainsIds();return this.setRequestedChainsIds([...y,f]),{...m,id:m.id}}catch(y){const b=y;if(/(?:user rejected)/iu.test(b.message))throw new ti(b);try{let v;d?.blockExplorerUrls?v=d.blockExplorerUrls:v=m.blockExplorers?.default.url?[m.blockExplorers?.default.url]:[];const x=m.rpcUrls?.chainDefault?.http||[],E={blockExplorerUrls:v,chainId:$n(f),chainName:m.name,iconUrls:d?.iconUrls,nativeCurrency:m.nativeCurrency,rpcUrls:x};await p.request({method:"wallet_addEthereumChain",params:[E]});const A=await this.getRequestedChainsIds();return this.setRequestedChainsIds([...A,f]),{...m,id:m.id}}catch(v){throw new ti(v)}}},onAccountsChanged(d){d.length===0?this.onDisconnect():u.emitter.emit("change",{accounts:d.map(f=>wh(f))})},onChainChanged(d){const f=Number(d);u.emitter.emit("change",{chainId:f})},onConnect(d){this.setRequestedChainsIds(G.getCaipNetworks().map(f=>Number(f.id)))},async onDisconnect(d){this.setRequestedChainsIds([]),u.emitter.emit("disconnect");const f=await this.getProvider();s&&(f.removeListener("accountsChanged",s),s=void 0),i&&(f.removeListener("chainChanged",i),i=void 0),l&&(f.removeListener("disconnect",l),l=void 0),c&&(f.removeListener("session_delete",c),c=void 0),o||(o=this.onConnect.bind(this),f.on("connect",o))},onDisplayUri(d){u.emitter.emit("message",{type:"display_uri",data:d})},onSessionDelete(){this.onDisconnect()},getNamespaceChainsIds(){return r?.session?.namespaces?r?.session?.namespaces[ye.CHAIN.EVM]?.accounts?.map(p=>Number.parseInt(p.split(":")[1]??""))??[]:[]},async getRequestedChainsIds(){const d=await u.storage?.getItem(this.requestedChainsStorageKey)??[];return[...new Set(d)]},async isChainsStale(){if(!n)return!1;const d=u.chains.map(m=>m.id),f=this.getNamespaceChainsIds();if(f.length&&!f.some(m=>d.includes(m)))return!1;const p=await this.getRequestedChainsIds();return!d.every(m=>p.includes(Number(m)))},async setRequestedChainsIds(d){await u.storage?.setItem(this.requestedChainsStorageKey,d)},get requestedChainsStorageKey(){return`${this.id}.requestedChains`}})}const b2=Br({pendingTransactions:0}),ete={state:b2,subscribeKey(t,e){return ai(b2,t,e)},increase(t){b2[t]+=1},decrease(t){b2[t]-=1},reset(t){b2[t]=0}};function Olt(t){try{return JSON.parse(t)}catch{throw new Error("Error parsing wallet capabilities")}}async function $lt(t){if(De.isSafeApp()){const{safe:e}=await et(async()=>{const{safe:n}=await import("./index-4N_q9Ijm.js");return{safe:n}},[]);if(e&&!t.some(n=>n.type==="safe"))return e()}return null}async function Dlt(t){try{const{coinbaseWallet:e}=await et(async()=>{const{coinbaseWallet:n}=await import("./index-4N_q9Ijm.js");return{coinbaseWallet:n}},[]);if(e&&!t.some(n=>n.id==="coinbaseWalletSDK"))return e()}catch(e){console.error("Failed to import Coinbase Wallet SDK:",e)}return null}const Mlt={enable:!1,pollingInterval:3e4};class Llt extends nW{constructor(e){const n=Du.extendCaipNetworks(e.networks,{projectId:e.projectId,customNetworkImageUrls:{},customRpcUrls:e.customRpcUrls});super(),this.balancePromises={},this.namespace=ye.CHAIN.EVM,this.adapterType=ye.ADAPTER_TYPES.WAGMI,this.projectId=e.projectId,this.pendingTransactionsFilter={...Mlt,...e.pendingTransactionsFilter??{}},this.createConfig({...e,networks:n}),this.checkChainId()}construct(e){this.checkChainId(),this.setupWatchers()}async getAccounts(e){const n=this.getWagmiConnector(e.id);if(!n)return{accounts:[]};if(n.id===ye.CONNECTOR_ID.AUTH){const i=await n.getProvider();if(!i?.user)return{accounts:[]};const{address:o,accounts:a}=i.user;return Promise.resolve({accounts:(a||[{address:o,type:"eoa"}]).map(c=>De.createAccount("eip155",c.address,c.type))})}const{addresses:r,address:s}=cv(this.wagmiConfig);return Promise.resolve({accounts:[...new Set(r||[s])].map(i=>De.createAccount("eip155",i||"","eoa"))})}checkChainId(){const{chainId:e}=cv(this.wagmiConfig);e&&this.emit("switchNetwork",{chainId:e})}getWagmiConnector(e){return this.wagmiConfig.connectors.find(n=>n.id===e)}createConfig(e){this.wagmiChains=e.networks.filter(s=>s.chainNamespace===ye.CHAIN.EVM);const n={},r=[...e.connectors??[]];this.wagmiChains.forEach(s=>{const i=e.transports?.[s.id],o=Du.getCaipNetworkId(s);i?n[s.id]=Du.extendWagmiTransports(s,e.projectId,i):n[s.id]=Du.getViemTransport(s,e.projectId,e.customRpcUrls?.[o])}),this.wagmiConfig=Tde({...e,chains:this.wagmiChains,connectors:r,transports:n})}setupWatchPendingTransactions(){if(!this.pendingTransactionsFilter.enable||this.unwatchPendingTransactions)return;this.unwatchPendingTransactions=Cde(this.wagmiConfig,{pollingInterval:this.pendingTransactionsFilter.pollingInterval,onError:()=>{},onTransactions:()=>{this.emit("pendingTransactions"),ete.increase("pendingTransactions")}});const e=ete.subscribeKey("pendingTransactions",n=>{n>=ye.LIMITS.PENDING_TRANSACTIONS&&(this.unwatchPendingTransactions?.(),e())})}setupWatchers(){xde(this.wagmiConfig,{onChange:e=>{this.clearConnections(),this.addConnection(...e.map(n=>{const r=this.getCaipNetworks().find(i=>i.id===n.chainId),s=n.connector.id===ye.CONNECTOR_ID.AUTH;return{accounts:n.accounts.map(i=>({address:i})),caipNetwork:r,connectorId:n.connector.id,auth:s?{name:Ge.getConnectedSocialProvider(),username:Ge.getConnectedSocialUsername()}:void 0}}))}}),vde(this.wagmiConfig,{onChange:(e,n)=>{if(e.status==="disconnected"&&n.address&&this.emit("disconnect"),e?.chainId&&e?.chainId!==n?.chainId&&this.emit("switchNetwork",{chainId:e.chainId}),e.status==="connected"){const r=e.address!==n?.address,s=e.connector.id!==n.connector?.id,i=n.status!=="connected";(r||s||i)&&(this.setupWatchPendingTransactions(),this.handleAccountChanged({address:e.address,chainId:e.chainId,connector:e.connector}))}}})}async addThirdPartyConnectors(e){const n=[];if(e.enableCoinbase!==!1){const s=await Dlt(this.wagmiConfig.connectors);s&&n.push(s)}const r=await $lt(this.wagmiConfig.connectors);r&&n.push(r),await Promise.all(n.map(s=>{const i=this.wagmiConfig._internal.connectors.setup(s);return this.wagmiConfig._internal.connectors.setState(o=>[...o,i]),this.addWagmiConnector(i,e)}))}addWagmiConnectors(e,n){const r=[];e.enableWalletConnect!==!1&&r.push(dW(e,n)),e.enableEIP6963!==!1&&r.push(ZS({shimDisconnect:!0}));const s=n?.remoteFeatures?.email??!0,i=Array.isArray(n?.remoteFeatures?.socials)&&n?.remoteFeatures?.socials?.length>0;(s||i)&&r.push(Rlt({chains:this.wagmiChains,options:{projectId:e.projectId,enableAuthLogger:e.enableAuthLogger}})),r.forEach(o=>{const a=this.wagmiConfig._internal.connectors.setup(o);this.wagmiConfig._internal.connectors.setState(c=>[...c,a])})}async handleAccountChanged({address:e,chainId:n,connector:r}){if(!this.namespace)throw new Error("WagmiAdapter:handleAccountChanged - namespace is required");const s=await r.getProvider().catch(()=>{});this.emit("accountChanged",{address:e,chainId:n,connector:{id:r.id,name:vo.ConnectorNamesMap[r.id]??r.name,imageId:vo.ConnectorImageIds[r.id],type:vo.ConnectorTypesMap[r.type]??"EXTERNAL",info:r.id===ye.CONNECTOR_ID.INJECTED?void 0:{rdns:r.id},provider:s,chain:this.namespace,chains:[]}})}async signMessage(e){try{return{signature:await yde(this.wagmiConfig,{message:e.message,account:e.address})}}catch{throw new Error("WagmiAdapter:signMessage - Sign message failed")}}async sendTransaction(e){const{chainId:n,address:r}=cv(this.wagmiConfig),s={account:r,to:e.to,value:Number.isNaN(Number(e.value))?BigInt(0):BigInt(e.value),gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,data:e.data,chainId:n,type:"legacy",parameters:["nonce"]};await gde(this.wagmiConfig,s);const i=await mde(this.wagmiConfig,s);return await GL(this.wagmiConfig,{hash:i,timeout:25e3}),{hash:i}}async writeContract(e){const{caipNetwork:n,...r}=e,s=Number(jC.caipNetworkIdToNumber(n.caipNetworkId));return{hash:await _de(this.wagmiConfig,{chain:this.wagmiChains?.[s],chainId:s,address:r.tokenAddress,account:r.fromAddress,abi:r.abi,functionName:r.method,args:r.args,__mode:"prepared"})}}async estimateGas(e){try{return{gas:await dde(this.wagmiConfig,{account:e.address,to:e.to,data:e.data,type:"legacy"})}}catch{throw new Error("WagmiAdapter:estimateGas - error estimating gas")}}parseUnits(e){return GLe(e.value,e.decimals)}formatUnits(e){return tx(e.value,e.decimals)}async addWagmiConnector(e,n){if(!this.namespace)throw new Error("WagmiAdapter:addWagmiConnector - namespace is required");if(e.type===ye.CONNECTOR_ID.INJECTED&&n.enableEIP6963===!1||e.id===ye.CONNECTOR_ID.AUTH||e.id===ye.CONNECTOR_ID.WALLET_CONNECT)return;const r=await e.getProvider().catch(()=>{});this.addConnector({id:e.id,explorerId:vo.ConnectorExplorerIds[e.id],imageUrl:n?.connectorImages?.[e.id]??e.icon,name:vo.ConnectorNamesMap[e.id]??e.name,imageId:vo.ConnectorImageIds[e.id],type:vo.ConnectorTypesMap[e.type]??"EXTERNAL",info:e.id===ye.CONNECTOR_ID.INJECTED?void 0:{rdns:e.id},provider:r,chain:this.namespace,chains:[]})}async syncConnectors(e,n){Ede(this.wagmiConfig,{onChange:r=>{r.forEach(s=>this.addWagmiConnector(s,e))}}),this.addWagmiConnectors(e,n),await Promise.all(this.wagmiConfig.connectors.map(r=>this.addWagmiConnector(r,e))),this.addThirdPartyConnectors(e)}async syncConnections(){return Promise.resolve()}async syncConnection(e){const{id:n,chainId:r}=e,i=Md(this.wagmiConfig).find(l=>l.connector.id===n),a=await this.getWagmiConnector(n)?.getProvider();if(De.isSafeApp()&&n===ye.CONNECTOR_ID.SAFE&&!i?.accounts.length){const l=this.getWagmiConnector("safe");if(l){const u=await UI(this.wagmiConfig,{connector:l,chainId:Number(r)}),d=await l.getProvider();return{chainId:Number(r),address:u.accounts[0],provider:d,type:i?.connector.type?.toUpperCase(),id:i?.connector.id}}}return{chainId:Number(i?.chainId),address:i?.accounts[0],provider:a,type:i?.connector.type?.toUpperCase(),id:i?.connector.id}}async connectWalletConnect(e){const n=this.getWalletConnectConnector();await n.authenticate();const r=this.getWagmiConnector("walletConnect");if(!r)throw new Error("UniversalAdapter:connectWalletConnect - connector not found");const s=await UI(this.wagmiConfig,{connector:r,chainId:e?Number(e):void 0});return s.chainId!==Number(e)&&await pT(this.wagmiConfig,{chainId:s.chainId}),{clientId:await n.provider.client.core.crypto.getClientId()}}async connect(e){const{id:n,address:r,provider:s,type:i,info:o,chainId:a,socialUri:c}=e,l=this.getWagmiConnector(n);if(!l)throw new Error("connectionControllerClient:connectExternal - connector is undefined");s&&o&&l.id===ye.CONNECTOR_ID.EIP6963&&l.setEip6963Wallet?.({provider:s,info:o});const u=this.wagmiConfig.state?.connections?.get(l.uid);if(u){await this.wagmiConfig.storage?.setItem("recentConnectorId",l.id);const f=[...u.accounts].sort((p,m)=>Jn.isLowerCaseMatch(p,r)?-1:Jn.isLowerCaseMatch(m,r)?1:0);return this.wagmiConfig?.setState(p=>({...p,connections:new Map(p.connections).set(l.uid,{accounts:f,chainId:u.chainId,connector:u.connector}),current:l.uid,status:"connected"})),{address:f[0],chainId:u.chainId,provider:s,type:i,id:n}}const d=await UI(this.wagmiConfig,{connector:l,chainId:a?Number(a):void 0,socialUri:c});return{address:d.accounts[0],chainId:d.chainId,provider:s,type:i,id:n}}get connections(){return Array.from(this.wagmiConfig.state.connections.values()).map(e=>({accounts:e.accounts.map(n=>({address:n})),connectorId:e.connector.id}))}async reconnect(e){const{id:n}=e,r=this.getWagmiConnector(n);if(!r)throw new Error("connectionControllerClient:connectExternal - connector is undefined");await hT(this.wagmiConfig,{connectors:[r]})}async getBalance(e){const n=e.address,r=this.getCaipNetworks().find(s=>s.id===e.chainId);if(!n)return Promise.resolve({balance:"0.00",symbol:"ETH"});if(r&&this.wagmiConfig){const s=`${r.caipNetworkId}:${e.address}`,i=this.balancePromises[s];if(i)return i;const o=Ge.getNativeBalanceCacheForCaipAddress(s);return o?{balance:o.balance,symbol:o.symbol}:(this.balancePromises[s]=new Promise(async a=>{try{const c=Number(e.chainId),l=await KL(this.wagmiConfig,{address:e.address,chainId:c,token:e.tokens?.[r.caipNetworkId]?.address});Ge.updateNativeBalanceCache({caipAddress:s,balance:l.formatted,symbol:l.symbol,timestamp:Date.now()}),a({balance:l.formatted,symbol:l.symbol})}catch(c){console.warn("Appkit:WagmiAdapter:getBalance - Error getting balance",c),a({balance:"0.00",symbol:"ETH"})}}).finally(()=>{delete this.balancePromises[s]}),this.balancePromises[s]||{balance:"0.00",symbol:"ETH"})}return{balance:"",symbol:""}}getWalletConnectProvider(){return this.getWagmiConnector("walletConnect")?.provider}async disconnect(e){if(e.id){const n=this.getWagmiConnector(e.id),s=Md(this.wagmiConfig).find(i=>Jn.isLowerCaseMatch(i.connector.id,e.id));return await qL(this.wagmiConfig,{connector:n}),_e.state.enableReconnect===!1&&this.deleteConnection(e.id),s?{connections:[{accounts:s.accounts.map(i=>({address:i})),connectorId:s.connector.id}]}:{connections:[]}}return this.disconnectAll()}async disconnectAll(){const e=Md(this.wagmiConfig),n=await Promise.allSettled(e.map(async r=>{const s=this.getWagmiConnector(r.connector.id);return s&&await qL(this.wagmiConfig,{connector:s}),r}));return this.wagmiConfig.state.connections.clear(),{connections:n.filter(r=>r.status==="fulfilled").map(({value:r})=>({accounts:r.accounts.map(s=>({address:s})),connectorId:r.connector.id}))}}async switchNetwork(e){const{caipNetwork:n}=e,r=this.wagmiConfig.chains.find(s=>s.id.toString()===n.id.toString());await pT(this.wagmiConfig,{chainId:n.id,addEthereumChainParameter:{chainName:r?.name??n.name,nativeCurrency:r?.nativeCurrency??n.nativeCurrency,rpcUrls:[n.rpcUrls?.chainDefault?.http?.[0]??r?.rpcUrls?.default?.http?.[0]??""],blockExplorerUrls:[r?.blockExplorers?.default?.url??n.blockExplorers?.default?.url??""]}}),await super.switchNetwork(e)}async getCapabilities(e){if(!this.wagmiConfig)throw new Error("connectionControllerClient:getCapabilities - wagmiConfig is undefined");const r=Md(this.wagmiConfig)[0],s=r?this.getWagmiConnector(r.connector.id):null;if(!s)throw new Error("connectionControllerClient:getCapabilities - connector is undefined");const i=await s.getProvider();if(!i)throw new Error("connectionControllerClient:getCapabilities - provider is undefined");const o=i.session?.sessionProperties?.capabilities;if(o){const c=Olt(o)[e];if(c)return c}return await i.request({method:"wallet_getCapabilities",params:[e]})}async grantPermissions(e){if(!this.wagmiConfig)throw new Error("connectionControllerClient:grantPermissions - wagmiConfig is undefined");const r=Md(this.wagmiConfig)[0],s=r?this.getWagmiConnector(r.connector.id):null;if(!s)throw new Error("connectionControllerClient:grantPermissions - connector is undefined");const i=await s.getProvider();if(!i)throw new Error("connectionControllerClient:grantPermissions - provider is undefined");return i.request({method:"wallet_grantPermissions",params:e})}async revokePermissions(e){if(!this.wagmiConfig)throw new Error("connectionControllerClient:revokePermissions - wagmiConfig is undefined");const r=Md(this.wagmiConfig)[0],s=r?this.getWagmiConnector(r.connector.id):null;if(!s)throw new Error("connectionControllerClient:revokePermissions - connector is undefined");const i=await s.getProvider();if(!i)throw new Error("connectionControllerClient:revokePermissions - provider is undefined");return i.request({method:"wallet_revokePermissions",params:e})}async walletGetAssets(e){if(!this.wagmiConfig)throw new Error("connectionControllerClient:walletGetAssets - wagmiConfig is undefined");const r=Md(this.wagmiConfig)[0],s=r?this.getWagmiConnector(r.connector.id):null;if(!s)throw new Error("connectionControllerClient:walletGetAssets - connector is undefined");const i=await s.getProvider();if(!i)throw new Error("connectionControllerClient:walletGetAssets - provider is undefined");return i.request({method:"wallet_getAssets",params:[e]})}setAuthProvider(e){if(!this.namespace)throw new Error("WagmiAdapter:setAuthProvider - namespace is required");this.addConnector({id:ye.CONNECTOR_ID.AUTH,type:"AUTH",name:ye.CONNECTOR_NAMES.AUTH,provider:e,imageId:vo.ConnectorImageIds[ye.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}async setUniversalProvider(e){return e.on("connect",()=>{const n=Md(this.wagmiConfig),r=this.getWagmiConnector("walletConnect");if(r&&!n.find(s=>s.connector.id===r.id)){if(G.state.activeChain==="eip155")return;hT(this.wagmiConfig,{connectors:[r]})}}),this.addConnector(new yk({provider:e,caipNetworks:this.getCaipNetworks(),namespace:"eip155"})),Promise.resolve()}}function Blt(t){const{children:e,config:n,initialState:r,reconnectOnMount:s=!0}=t,{onMount:i}=Nde(n,{initialState:r,reconnectOnMount:s});n._internal.ssr||i();const o=I.useRef(!0);return I.useEffect(()=>{if(o.current&&n._internal.ssr)return i(),()=>{o.current=!1}},[]),e}const Ult=I.createContext(void 0);function Flt(t){const{children:e,config:n}=t,r={value:n};return I.createElement(Blt,t,I.createElement(Ult.Provider,r,e))}var jlt={};const e0e=[cat,Jh],Ak=jlt.VITE_REOWN_SECRET||"2ead96ea166a03e5ab50e5c190532e72";if(!Ak)throw new Error("VITE_REOWN_SECRET is not defined. Please set it in your .env file");const fW=new Llt({storage:nz({storage:localStorage}),ssr:!1,projectId:Ak,networks:e0e}),OE=fW.wagmiConfig,zlt=new klt({projectId:Ak}),Wlt={name:"OpChan",description:"Decentralized forum powered by Bitcoin Ordinals",url:"https://opchan.app",icons:["https://opchan.com/logo.png"]},t0e={adapters:[fW,zlt],networks:e0e,metadata:Wlt,projectId:Ak,features:{analytics:!1,socials:!1,allWallets:!1},enableWalletConnect:!1},Vlt=Object.freeze(Object.defineProperty({__proto__:null,appkitConfig:t0e,config:OE,wagmiAdapter:fW},Symbol.toStringTag,{value:"Module"}));let Hlt=null;const qlt=()=>Hlt??=et(()=>import("./index-CqL7mnh0.js").then(t=>t.i),__vite__mapDeps([5,6]));class Ui{static instance=null;appKit;activeAccount;activeWalletType;namespace;constructor(e,n,r){if(this.appKit=e,n.isConnected&&n.address)this.activeAccount=n,this.activeWalletType="bitcoin",this.namespace="bip122";else if(r.isConnected&&r.address)this.activeAccount=r,this.activeWalletType="ethereum",this.namespace="eip155";else throw new Error("No wallet is connected")}static create(e,n,r){return Ui.instance=new Ui(e,n,r),Ui.instance}static getInstance(){if(!Ui.instance)throw new Error("WalletManager not initialized. Call WalletManager.create() first.");return Ui.instance}static hasInstance(){return Ui.instance!==null}static clear(){Ui.instance=null}static async resolveENS(e){try{return await fT(OE,{address:e})||null}catch(n){return console.warn("Failed to resolve ENS name:",n),null}}getActiveWallet(){return{type:this.activeWalletType,address:this.activeAccount.address,isConnected:!0}}isConnected(){return this.activeAccount.isConnected}getWalletType(){return this.activeWalletType}getAddress(){return this.activeAccount.address}async signMessage(e){try{const n=this.appKit.chainAdapters?.[this.namespace];if(!n)throw new Error(`No adapter found for namespace: ${this.namespace}`);const r=this.appKit.getProvider(this.namespace);if(!r)throw new Error(`No provider found for namespace: ${this.namespace}`);if(!this.activeAccount.address)throw new Error("No address found for active account");return(await n.signMessage({message:e,address:this.activeAccount.address,provider:r})).signature}catch(n){throw console.error(`Error signing message with ${this.activeWalletType} wallet:`,n),new Error(`Failed to sign message with ${this.activeWalletType} wallet: ${n instanceof Error?n.message:"Unknown error"}`)}}static async verifySignature(e,n,r,s){try{return s==="ethereum"?await bde(OE,{address:r,message:e,signature:n}):s==="bitcoin"?(await qlt()).verify(e,r,n):(console.error("WalletManager.verifySignature - unknown wallet type:",s),!1)}catch(i){return console.error("WalletManager.verifySignature - error verifying signature:",i),!1}}async getWalletInfo(){const e=this.activeAccount.address;if(this.activeWalletType==="bitcoin")return{address:e,walletType:"bitcoin",isConnected:!0};let n;try{n=await fT(OE,{address:e})||void 0}catch(r){console.warn("Failed to resolve ENS name:",r)}return{address:e,walletType:"ethereum",ensName:n,isConnected:!0}}}var os=(t=>(t.CELL="cell",t.POST="post",t.COMMENT="comment",t.VOTE="vote",t.MODERATE="moderate",t.USER_PROFILE_UPDATE="user_profile_update",t))(os||{}),Ou=(t=>(t.MODERATE="moderate",t.UNMODERATE="unmoderate",t))(Ou||{});class Klt{delegationManager;constructor(e){this.delegationManager=e}getDelegationManager(){return this.delegationManager||(this.delegationManager=new vh),this.delegationManager}async isValidMessage(e){if(!this.hasRequiredFields(e))return!1;try{return await this.getDelegationManager().verify(e)}catch{return!1}}hasRequiredFields(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.signature=="string"&&typeof n.browserPubKey=="string"&&typeof n.id=="string"&&typeof n.type=="string"&&typeof n.timestamp=="number"&&typeof n.author=="string"}async validateMessages(e){const n=[],r=[],s=[];for(const i of e)try{if(!this.hasRequiredFields(i)){r.push(i),s.push("Missing required fields");continue}try{if(!await this.getDelegationManager().verify(i)){r.push(i),s.push("Invalid signature");continue}n.push(i)}catch{r.push(i),s.push("Signature verification failed")}}catch(o){r.push(i),s.push(o instanceof Error?o.message:"Unknown validation error")}return{validMessages:n,invalidMessages:r,totalProcessed:e.length,validationErrors:s}}async validateSingleMessage(e){if(!this.hasRequiredFields(e))throw new Error("Message missing required fields");try{if(!await this.getDelegationManager().verify(e))throw new Error("Invalid message signature");return e}catch(n){throw new Error(`Message validation failed: ${n}`)}}async batchValidate(e,n={}){const{maxConcurrent:r=10,skipInvalid:s=!0}=n,i=[],o=[],a=[];for(let c=0;c{try{const m=await this.isValidMessage(f);return{message:f,isValid:m,index:c+p,error:null}}catch(m){return{message:f,isValid:!1,index:c+p,error:m instanceof Error?m.message:"Unknown error"}}}),d=await Promise.allSettled(u);for(const f of d)if(f.status==="fulfilled"){const{message:p,isValid:m,error:y}=f.value;m?i.push(p):s||(o.push(p),y&&a.push(y))}else s||a.push(f.reason?.message||"Batch validation failed")}return{validMessages:i,invalidMessages:o,totalProcessed:e.length,validationErrors:a}}quickValidate(e){return this.hasRequiredFields(e)}getValidationStats(e){const n=e.validMessages.length,r=e.invalidMessages.length,s=e.totalProcessed>0?n/e.totalProcessed:0;return{validCount:n,invalidCount:r,totalProcessed:e.totalProcessed,successRate:s,errorCount:e.validationErrors.length,hasErrors:e.validationErrors.length>0}}filterByType(e,n){return e.filter(r=>r.type===n)}sortByTimestamp(e,n=!0){return[...e].sort((r,s)=>n?r.timestamp-s.timestamp:s.timestamp-r.timestamp)}groupByAuthor(e){const n={};for(const r of e){n[r.author]||(n[r.author]=[]);const s=n[r.author];s&&s.push(r)}return n}async getValidationReport(e){const n=this.validateStructure(e),r=n.isValid?await this.isValidMessage(e):!1;return{...n,hasValidSignature:r,errors:[...n.missingFields,...n.invalidFields]}}validateStructure(e){const n=[],r=[],s=[];if(!e||typeof e!="object")return{isValid:!1,missingFields:["message"],invalidFields:[],warnings:["Message is not an object"]};const i=e,o=["signature","browserPubKey","id","type","timestamp","author"];for(const c of o)c in i?typeof i[c]!=(c==="timestamp"?"number":"string")&&r.push(c):n.push(c);return typeof i.timestamp=="number"&&(Date.now()-i.timestamp>24*60*60*1e3&&s.push("Message is older than 24 hours"),i.timestamp>Date.now()+5*60*1e3&&s.push("Message timestamp is in the future")),{isValid:n.length===0&&r.length===0,missingFields:n,invalidFields:r,warnings:s}}}const Glt="opchan-local",Zlt=3,Et={CELLS:"cells",POSTS:"posts",COMMENTS:"comments",VOTES:"votes",MODERATIONS:"moderations",USER_IDENTITIES:"userIdentities",USER_AUTH:"userAuth",DELEGATION:"delegation",UI_STATE:"uiState",META:"meta",BOOKMARKS:"bookmarks"};function Ylt(){return new Promise((t,e)=>{const n=indexedDB.open(Glt,Zlt);n.onerror=()=>e(n.error),n.onsuccess=()=>t(n.result),n.onupgradeneeded=()=>{const r=n.result;if(r.objectStoreNames.contains(Et.CELLS)||r.createObjectStore(Et.CELLS,{keyPath:"id"}),r.objectStoreNames.contains(Et.POSTS)||r.createObjectStore(Et.POSTS,{keyPath:"id"}).createIndex("by_cellId","cellId",{unique:!1}),r.objectStoreNames.contains(Et.COMMENTS)||r.createObjectStore(Et.COMMENTS,{keyPath:"id"}).createIndex("by_postId","postId",{unique:!1}),r.objectStoreNames.contains(Et.VOTES)||r.createObjectStore(Et.VOTES,{keyPath:"key"}),r.objectStoreNames.contains(Et.MODERATIONS)||r.createObjectStore(Et.MODERATIONS,{keyPath:"targetId"}),r.objectStoreNames.contains(Et.USER_IDENTITIES)||r.createObjectStore(Et.USER_IDENTITIES,{keyPath:"address"}),r.objectStoreNames.contains(Et.USER_AUTH)||r.createObjectStore(Et.USER_AUTH,{keyPath:"key"}),r.objectStoreNames.contains(Et.DELEGATION)||r.createObjectStore(Et.DELEGATION,{keyPath:"key"}),r.objectStoreNames.contains(Et.UI_STATE)||r.createObjectStore(Et.UI_STATE,{keyPath:"key"}),r.objectStoreNames.contains(Et.META)||r.createObjectStore(Et.META,{keyPath:"key"}),!r.objectStoreNames.contains(Et.BOOKMARKS)){const s=r.createObjectStore(Et.BOOKMARKS,{keyPath:"id"});s.createIndex("by_userId","userId",{unique:!1}),s.createIndex("by_type","type",{unique:!1}),s.createIndex("by_targetId","targetId",{unique:!1})}}})}class Xlt{processedMessageIds=new Set;validator;db=null;_isSyncing=!1;_lastSync=null;pendingIds=new Set;pendingListeners=new Set;cache={cells:{},posts:{},comments:{},votes:{},moderations:{},userIdentities:{},bookmarks:{}};constructor(){this.validator=new Klt}async open(){this.db=await Ylt(),await this.hydrateFromIndexedDB(),await this.hydratePendingFromMeta()}async applyMessage(e){if(!await this.validator.isValidMessage(e)){const s=e;return console.warn("LocalDatabase: Rejecting invalid message",{messageId:s?.id,messageType:s?.type,hasSignature:!!s?.signature,hasBrowserPubKey:!!s?.browserPubKey}),!1}const n=e,r=`${n.type}:${n.id}:${n.timestamp}`;return this.processedMessageIds.has(r)?!1:(this.processedMessageIds.add(r),this.storeMessage(n),!0)}async updateCache(e){return this.applyMessage(e)}clear(){this.processedMessageIds.clear(),this.cache.cells={},this.cache.posts={},this.cache.comments={},this.cache.votes={},this.cache.moderations={},this.cache.userIdentities={},this.cache.bookmarks={}}async clearAll(){if(this.clear(),!this.db)return;const e=[Et.CELLS,Et.POSTS,Et.COMMENTS,Et.VOTES,Et.MODERATIONS,Et.USER_IDENTITIES,Et.USER_AUTH,Et.DELEGATION,Et.UI_STATE,Et.META,Et.BOOKMARKS],n=this.db.transaction(e,"readwrite");await Promise.all(e.map(r=>new Promise((s,i)=>{const a=n.objectStore(r).clear();a.onerror=()=>i(a.error),a.onsuccess=()=>s()})))}storeMessage(e){switch(e.type){case os.CELL:(!this.cache.cells[e.id]||this.cache.cells[e.id]?.timestamp!==e.timestamp)&&(this.cache.cells[e.id]=e,this.put(Et.CELLS,e));break;case os.POST:(!this.cache.posts[e.id]||this.cache.posts[e.id]?.timestamp!==e.timestamp)&&(this.cache.posts[e.id]=e,this.put(Et.POSTS,e));break;case os.COMMENT:(!this.cache.comments[e.id]||this.cache.comments[e.id]?.timestamp!==e.timestamp)&&(this.cache.comments[e.id]=e,this.put(Et.COMMENTS,e));break;case os.VOTE:{const n=`${e.targetId}:${e.author}`;(!this.cache.votes[n]||this.cache.votes[n]?.timestamp!==e.timestamp)&&(this.cache.votes[n]=e,this.put(Et.VOTES,{key:n,...e}));break}case os.MODERATE:{const n=e;(!this.cache.moderations[n.targetId]||this.cache.moderations[n.targetId]?.timestamp!==n.timestamp)&&(this.cache.moderations[n.targetId]=n,this.put(Et.MODERATIONS,n));break}case os.USER_PROFILE_UPDATE:{const n=e,{author:r,callSign:s,displayPreference:i,timestamp:o}=n,a=this.cache.userIdentities[r];if(!a||o>a.lastUpdated){const c={ensName:a?.ensName,ordinalDetails:a?.ordinalDetails,callSign:s!==void 0?s:a?.callSign,displayPreference:i,lastUpdated:o,verificationStatus:a?.verificationStatus??Ct.WALLET_UNCONNECTED};this.cache.userIdentities[r]=c,this.put(Et.USER_IDENTITIES,{address:r,...c})}break}default:console.warn("LocalDatabase: Received message with unknown type");break}this.updateLastSync(Date.now())}async hydrateFromIndexedDB(){if(!this.db)return;const[e,n,r,s,i,o,a]=await Promise.all([this.getAllFromStore(Et.CELLS),this.getAllFromStore(Et.POSTS),this.getAllFromStore(Et.COMMENTS),this.getAllFromStore(Et.VOTES),this.getAllFromStore(Et.MODERATIONS),this.getAllFromStore(Et.USER_IDENTITIES),this.getAllFromStore(Et.BOOKMARKS)]);this.cache.cells=Object.fromEntries(e.map(c=>[c.id,c])),this.cache.posts=Object.fromEntries(n.map(c=>[c.id,c])),this.cache.comments=Object.fromEntries(r.map(c=>[c.id,c])),this.cache.votes=Object.fromEntries(s.map(c=>{const{key:l,...u}=c;return[l,u]})),this.cache.moderations=Object.fromEntries(i.map(c=>[c.targetId,c])),this.cache.userIdentities=Object.fromEntries(o.map(c=>{const{address:l,...u}=c;return[l,u]})),this.cache.bookmarks=Object.fromEntries(a.map(c=>[c.id,c]))}async hydratePendingFromMeta(){if(!this.db)return;(await this.getAllFromStore(Et.META)).filter(n=>typeof n.key=="string"&&n.key.startsWith("pending:")).forEach(n=>{const r=n.key.substring(8);this.pendingIds.add(r)})}getAllFromStore(e){return new Promise((n,r)=>{if(!this.db)return n([]);const o=this.db.transaction(e,"readonly").objectStore(e).getAll();o.onerror=()=>r(o.error),o.onsuccess=()=>n(o.result)})}put(e,n){if(!this.db)return;this.db.transaction(e,"readwrite").objectStore(e).put(n)}getSyncState(){return{lastSync:this._lastSync,isSyncing:this._isSyncing}}setSyncing(e){this._isSyncing=e}updateLastSync(e){if(this._lastSync=Math.max(this._lastSync??0,e),!this.db)return;this.db.transaction(Et.META,"readwrite").objectStore(Et.META).put({key:"lastSync",value:this._lastSync})}markPending(e){if(this.pendingIds.add(e),!this.db)return;this.db.transaction(Et.META,"readwrite").objectStore(Et.META).put({key:`pending:${e}`,value:!0}),this.pendingListeners.forEach(s=>s())}clearPending(e){if(this.pendingIds.delete(e),!this.db)return;this.db.transaction(Et.META,"readwrite").objectStore(Et.META).delete(`pending:${e}`),this.pendingListeners.forEach(s=>s())}isPending(e){return this.pendingIds.has(e)}onPendingChange(e){return this.pendingListeners.add(e),()=>this.pendingListeners.delete(e)}async storeUser(e){const n={key:"current",value:e,timestamp:Date.now()};this.put(Et.USER_AUTH,n)}async loadUser(){return this.db?new Promise((e,n)=>{const i=this.db.transaction(Et.USER_AUTH,"readonly").objectStore(Et.USER_AUTH).get("current");i.onerror=()=>n(i.error),i.onsuccess=()=>{const o=i.result;if(!o){e(null);return}const a=o.value,c=a.lastChecked||0,l=24*60*60*1e3;Date.now()-c{const i=this.db.transaction(Et.DELEGATION,"readonly").objectStore(Et.DELEGATION).get("current");i.onerror=()=>n(i.error),i.onsuccess=()=>{const o=i.result;e(o?.value||null)}}):null}async clearDelegation(){if(!this.db)return;this.db.transaction(Et.DELEGATION,"readwrite").objectStore(Et.DELEGATION).delete("current")}async storeUIState(e,n){const r={key:e,value:n,timestamp:Date.now()};this.put(Et.UI_STATE,r)}async loadUIState(e){return this.db?new Promise((n,r)=>{const o=this.db.transaction(Et.UI_STATE,"readonly").objectStore(Et.UI_STATE).get(e);o.onerror=()=>r(o.error),o.onsuccess=()=>{const a=o.result;n(a?.value||null)}}):null}async clearUIState(e){if(!this.db)return;this.db.transaction(Et.UI_STATE,"readwrite").objectStore(Et.UI_STATE).delete(e)}async addBookmark(e){this.cache.bookmarks[e.id]=e,this.put(Et.BOOKMARKS,e)}async removeBookmark(e){if(delete this.cache.bookmarks[e],!this.db)return;this.db.transaction(Et.BOOKMARKS,"readwrite").objectStore(Et.BOOKMARKS).delete(e)}async getUserBookmarks(e){return this.db?new Promise((n,r)=>{const a=this.db.transaction(Et.BOOKMARKS,"readonly").objectStore(Et.BOOKMARKS).index("by_userId").getAll(e);a.onerror=()=>r(a.error),a.onsuccess=()=>n(a.result)}):[]}async getUserBookmarksByType(e,n){return this.db?new Promise((r,s)=>{const c=this.db.transaction(Et.BOOKMARKS,"readonly").objectStore(Et.BOOKMARKS).index("by_userId").getAll(e);c.onerror=()=>s(c.error),c.onsuccess=()=>{const u=c.result.filter(d=>d.type===n);r(u)}}):[]}isBookmarked(e,n,r){const s=`${n}:${r}`;return this.cache.bookmarks[s]?.userId===e}getBookmark(e){return this.cache.bookmarks[e]}getAllBookmarks(){return Object.values(this.cache.bookmarks)}}const ct=new Xlt;class VA{static async store(e){try{await ct.storeDelegation(e)}catch(n){console.error("Failed to store delegation information",n)}}static async retrieve(){try{return await ct.loadDelegation()}catch(e){return console.error("Failed to retrieve delegation information",e),null}}static async clear(){try{await ct.clearDelegation()}catch(e){console.error("Failed to clear delegation information",e)}}}/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const Mi=2n**255n-19n,hv=2n**252n+27742317777372353535851937790883648493n,fB=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,hB=0x6666666666666666666666666666666666666666666666666666666666666658n,Qlt=37095705934669439343138083508754565189542113879843219016388785533085940283555n,HA={a:-1n,d:Qlt,p:Mi,n:hv,h:8,Gx:fB,Gy:hB},Fi=(t="")=>{throw new Error(t)},n0e=t=>typeof t=="string",Jlt=t=>t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array",Qv=(t,e)=>!Jlt(t)||typeof e=="number"&&e>0&&t.length!==e?Fi("Uint8Array of valid length expected"):t,Jv=t=>new Uint8Array(t),Km=(t,e)=>Qv(n0e(t)?pW(t):Jv(Qv(t)),e),Zt=(t,e=Mi)=>{let n=t%e;return n>=0n?n:e+n},tte=t=>t instanceof La?t:Fi("Point expected");class La{constructor(e,n,r,s){this.ex=e,this.ey=n,this.ez=r,this.et=s}static fromAffine(e){return new La(e.x,e.y,1n,Zt(e.x*e.y))}static fromHex(e,n=!1){const{d:r}=HA;e=Km(e,32);const s=e.slice(),i=e[31];s[31]=i&-129;const o=gW(s);n&&!(0n<=o&&o<2n**256n)&&Fi("bad y coord 1"),!n&&!(0n<=o&&o0n;i=i.double(),e>>=1n)e&1n?r=r.add(i):n&&(s=s.add(i));return r}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(HA.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(hv/2n,!1).double();return hv%2n&&(e=e.add(this)),e.is0()}toAffine(){const{ex:e,ey:n,ez:r}=this;if(this.equals(G2))return{x:0n,y:1n};const s=i0e(r,Mi);return Zt(r*s)!==1n&&Fi("invalid inverse"),{x:Zt(e*s),y:Zt(n*s)}}toRawBytes(){const{x:e,y:n}=this.toAffine(),r=s0e(n);return r[31]|=e&1n?128:0,r}toHex(){return hW(this.toRawBytes())}}La.BASE=new La(fB,hB,1n,Zt(fB*hB));La.ZERO=new La(0n,1n,1n,0n);const{BASE:p0,ZERO:G2}=La,r0e=(t,e)=>t.toString(16).padStart(e,"0"),hW=t=>Array.from(Qv(t)).map(e=>r0e(e,2)).join(""),th={_0:48,_9:57,A:65,F:70,a:97,f:102},nte=t=>{if(t>=th._0&&t<=th._9)return t-th._0;if(t>=th.A&&t<=th.F)return t-(th.A-10);if(t>=th.a&&t<=th.f)return t-(th.a-10)},pW=t=>{const e="hex invalid";if(!n0e(t))return Fi(e);const n=t.length,r=n/2;if(n%2)return Fi(e);const s=Jv(r);for(let i=0,o=0;ipW(r0e(t,32*2)).reverse(),gW=t=>BigInt("0x"+hW(Jv(Qv(t)).reverse())),g_=(...t)=>{const e=Jv(t.reduce((r,s)=>r+Qv(s).length,0));let n=0;return t.forEach(r=>{e.set(r,n),n+=r.length}),e},i0e=(t,e)=>{(t===0n||e<=0n)&&Fi("no inverse n="+t+" mod="+e);let n=Zt(t,e),r=e,s=0n,i=1n;for(;n!==0n;){const o=r/n,a=r%n,c=s-i*o;r=n,n=a,s=i,i=c}return r===1n?Zt(s,e):Fi("no inverse")},Pd=(t,e)=>{let n=t;for(;e-- >0n;)n*=n,n%=Mi;return n},eut=t=>{const n=t*t%Mi*t%Mi,r=Pd(n,2n)*n%Mi,s=Pd(r,1n)*t%Mi,i=Pd(s,5n)*s%Mi,o=Pd(i,10n)*i%Mi,a=Pd(o,20n)*o%Mi,c=Pd(a,40n)*a%Mi,l=Pd(c,80n)*c%Mi,u=Pd(l,80n)*c%Mi,d=Pd(u,10n)*i%Mi;return{pow_p_5_8:Pd(d,2n)*t%Mi,b2:n}},rte=19681161376707505956807079304988542015446066515923890162744021073123829784752n,tut=(t,e)=>{const n=Zt(e*e*e),r=Zt(n*n*e),s=eut(t*r).pow_p_5_8;let i=Zt(t*n*s);const o=Zt(e*i*i),a=i,c=Zt(i*rte),l=o===t,u=o===Zt(-t),d=o===Zt(-t*rte);return l&&(i=a),(u||d)&&(i=c),(Zt(i)&1n)===1n&&(i=Zt(-i)),{isValid:l||u,value:i}},YT=t=>Zt(gW(t),hv);let $E;const nut=(...t)=>m_.sha512Async(...t),mW=(...t)=>typeof $E=="function"?$E(...t):Fi("etc.sha512Sync not set"),o0e=t=>{const e=t.slice(0,32);e[0]&=248,e[31]&=127,e[31]|=64;const n=t.slice(32,64),r=YT(e),s=p0.mul(r),i=s.toRawBytes();return{head:e,prefix:n,scalar:r,point:s,pointBytes:i}},rut=t=>nut(Km(t,32)).then(o0e),yW=t=>o0e(mW(Km(t,32))),sut=t=>yW(t).pointBytes;function a0e(t,e){return e.finish(mW(e.hashable))}const iut=(t,e,n)=>{const{pointBytes:r,scalar:s}=t,i=YT(e),o=p0.mul(i).toRawBytes();return{hashable:g_(o,r,n),finish:l=>{const u=Zt(i+YT(l)*s,hv);return Qv(g_(o,s0e(u)),64)}}},out=(t,e)=>{const n=Km(t),r=yW(e),s=mW(r.prefix,n);return a0e(!1,iut(r,s,n))},c0e={zip215:!0},aut=(t,e,n,r=c0e)=>{t=Km(t,64),e=Km(e),n=Km(n,32);const{zip215:s}=r;let i,o,a,c,l=new Uint8Array;try{i=La.fromHex(n,s),o=La.fromHex(t.slice(0,32),s),a=gW(t.slice(32,64)),c=p0.mul(a,!1),l=g_(o.toRawBytes(),i.toRawBytes(),e)}catch{}return{hashable:l,finish:d=>{if(c==null||!s&&i.isSmallOrder())return!1;const f=YT(d);return o.add(i.mul(f,!1)).add(c.negate()).clearCofactor().is0()}}},cut=(t,e,n,r=c0e)=>a0e(!1,aut(t,e,n,r)),ste=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,m_={bytesToHex:hW,hexToBytes:pW,concatBytes:g_,mod:Zt,invert:i0e,randomBytes:(t=32)=>{const e=ste();return(!e||!e.getRandomValues)&&Fi("crypto.getRandomValues must be defined"),e.getRandomValues(Jv(t))},sha512Async:async(...t)=>{const e=ste(),n=e&&e.subtle;n||Fi("etc.sha512Async or crypto.subtle must be defined");const r=g_(...t);return Jv(await n.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(m_,{sha512Sync:{configurable:!1,get(){return $E},set(t){$E||($E=t)}}});const lut={getExtendedPublicKeyAsync:rut,getExtendedPublicKey:yW,randomPrivateKey:()=>m_.randomBytes(32),precompute:(t=8,e=p0)=>(e.multiply(3n),e)},dm=8,uut=()=>{const t=[],e=256/dm+1;let n=p0,r=n;for(let s=0;s{const e=ite||(ite=uut()),n=(u,d)=>{let f=d.negate();return u?f:d};let r=G2,s=p0;const i=1+256/dm,o=2**(dm-1),a=BigInt(2**dm-1),c=2**dm,l=BigInt(dm);for(let u=0;u>=l,f>o&&(f-=c,t+=1n);const p=d,m=d+Math.abs(f)-1,y=u%2!==0,b=f<0;f===0?s=s.add(n(y,e[p])):r=r.add(n(b,e[m]))}return{p:r,f:s}},fut=zj;m_.sha512Sync=(...t)=>fut(m_.concatBytes(...t));class v2{static createAuthMessage(e,n,r,s){return`I, ${n}, authorize browser key ${e} until ${r} (nonce: ${s})`}static async verifyWalletSignature(e,n,r,s){try{return await Ui.verifySignature(e,n,r,s)}catch(i){return console.error("Error verifying wallet signature:",i),!1}}static generateKeypair(){const e=lut.randomPrivateKey(),n=FO(e),r=sut(e),s=FO(r);return{privateKey:n,publicKey:s}}static signRaw(e,n){try{const r=jO(n),s=new TextEncoder().encode(e),i=out(s,r);return FO(i)}catch(r){return console.error("Error signing with private key:",r),null}}static verifyRaw(e,n,r){try{const s=new TextEncoder().encode(e),i=jO(n),o=jO(r);return cut(i,s,o)}catch(s){return console.error("Error verifying signature:",s),!1}}}class vh{cachedDelegation=null;cachedAt=0;static CACHE_TTL_MS=5*1e3;static DURATION_HOURS={"7days":24*7,"30days":24*30};static getDurationHours(e){return vh.DURATION_HOURS[e]}async delegate(e,n,r="7days",s){try{const i=v2.generateKeypair(),o=Date.now()+vh.getDurationHours(r)*60*60*1e3,a=crypto.randomUUID(),c=v2.createAuthMessage(i.publicKey,e,o,a),l=await s(c),u={authMessage:c,walletSignature:l,expiryTimestamp:o,walletAddress:e,walletType:n,browserPublicKey:i.publicKey,browserPrivateKey:i.privateKey,nonce:a};return await VA.store(u),!0}catch(i){return console.error("Error creating delegation:",i),!1}}async signMessage(e){const n=Date.now();(!this.cachedDelegation||n-this.cachedAt>vh.CACHE_TTL_MS)&&(this.cachedDelegation=await VA.retrieve(),this.cachedAt=n);const r=this.cachedDelegation;if(!r||Date.now()>=r.expiryTimestamp)return null;const s=JSON.stringify({...e,signature:void 0,browserPubKey:void 0,delegationProof:void 0}),i=v2.signRaw(s,r.browserPrivateKey);return i?{...e,signature:i,browserPubKey:r.browserPublicKey,delegationProof:this.createProof(r)}:null}async verify(e){if(!e.signature||!e.browserPubKey||!e.delegationProof||!e.author)return!1;const n=JSON.stringify({...e,signature:void 0,browserPubKey:void 0,delegationProof:void 0});return v2.verifyRaw(n,e.signature,e.browserPubKey)?await this.verifyProof(e.delegationProof,e.browserPubKey,e.author):!1}async getStatus(e,n){const r=Date.now();(!this.cachedDelegation||r-this.cachedAt>vh.CACHE_TTL_MS)&&(this.cachedDelegation=await VA.retrieve(),this.cachedAt=r);const s=this.cachedDelegation;if(!s)return{hasDelegation:!1,isValid:!1};const i=r>=s.expiryTimestamp,o=!e||s.walletAddress===e,a=!n||s.walletType===n,c=!i&&o&&a;return{hasDelegation:!0,isValid:c,timeRemaining:c?Math.max(0,s.expiryTimestamp-r):void 0,publicKey:s.browserPublicKey,address:s.walletAddress,walletType:s.walletType,proof:c?this.createProof(s):void 0}}async clear(){await VA.clear()}createProof(e){return{authMessage:e.authMessage,walletSignature:e.walletSignature,expiryTimestamp:e.expiryTimestamp,walletAddress:e.walletAddress,walletType:e.walletType}}async verifyProof(e,n,r){return!e?.walletAddress||!e?.authMessage||e?.expiryTimestamp===void 0||e.walletAddress!==r||Date.now()>=e.expiryTimestamp||!e.authMessage.includes(r)||!e.authMessage.includes(n)||!e.authMessage.includes(e.expiryTimestamp.toString())?!1:await v2.verifyWalletSignature(e.authMessage,e.walletSignature,e.walletAddress,e.walletType)}}const hut={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},put=(t,e)=>{const n=I.useRef(void 0);I.useEffect(()=>{n.current=X7e(t,e)}),I.useDebugValue(n.current)},gut=put,mut=new WeakMap;function ote(t,e){const r=I.useMemo(()=>t&&new WeakMap,[t]),s=I.useRef(void 0);let i=!0;const o=I.useSyncExternalStore(I.useCallback(c=>{const l=Gs(t,c);return c(),l},[t,void 0]),()=>{const c=py(t);try{if(!i&&s.current&&!Mde(s.current,c,r,new WeakMap))return s.current}catch{}return c},()=>py(t));i=!1,I.useLayoutEffect(()=>{s.current=o}),(hut?"production":void 0)!=="production"&&gut(o,r);const a=I.useMemo(()=>new WeakMap,[]);return Dde(o,r,a,mut)}function yut(){try{return De.returnOpenHref(`${ye.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes")}catch{throw new Error("Could not open social popup")}}async function wut(){ze.push("ConnectingFarcaster");const t=ke.getAuthConnector();if(t&&!nt.state.farcasterUrl)try{const{url:e}=await t.provider.getFarcasterUri();nt.setFarcasterUrl(e,G.state.activeChain)}catch(e){ze.goBack(),Wn.showError(e)}}async function but(t){ze.push("ConnectingSocial");const e=ke.getAuthConnector();let n=null;try{const r=setTimeout(()=>{throw new Error("Social login timed out. Please try again.")},45e3);if(e&&t){if(De.isTelegram()||(n=yut()),n)nt.setSocialWindow(n,G.state.activeChain);else if(!De.isTelegram())throw new Error("Could not create social popup");const{uri:s}=await e.provider.getSocialRedirectUri({provider:t});if(!s)throw n?.close(),new Error("Could not fetch the social redirect uri");if(n&&(n.location.href=s),De.isTelegram()){Ge.setTelegramSocialProvider(t);const i=De.formatTelegramSocialLoginUrl(s);De.openHref(i,"_top")}clearTimeout(r)}}catch(r){n?.close(),Wn.showError(r?.message)}}async function vut(t){nt.setSocialProvider(t,G.state.activeChain),Lt.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:t}}),t==="farcaster"?await wut():await but(t)}function g0(t){const e=ote(G.state),{activeConnectorIds:n}=ote(ke.state),r=t?.namespace||e.activeChain;if(!r)return{allAccounts:[],address:void 0,caipAddress:void 0,status:void 0,isConnected:!1,embeddedWalletInfo:void 0};const s=e.chains.get(r)?.accountState,i=ke.getAuthConnector(r),o=n[r];return{allAccounts:Ue.getConnections(r).flatMap(l=>l.accounts.map(({address:u})=>De.createAccount(r,u,"eoa"))),caipAddress:s?.caipAddress,address:De.getPlainAddress(s?.caipAddress),isConnected:!!s?.caipAddress,status:s?.status,embeddedWalletInfo:i&&o===ye.CONNECTOR_ID.AUTH?{user:s?.user?{...s.user,username:Ge.getConnectedSocialUsername()}:void 0,authProvider:s?.socialProvider||"email",accountType:s?.preferredAccountType,isSmartAccountDeployed:!!s?.smartAccountDeployed}:void 0}}function l0e(){async function t(e){await Ue.disconnect(e)}return{disconnect:t}}let wl;function xut(t){t&&(wl=t)}function Eut(){if(!wl)throw new Error('Please call "createAppKit" before using "useAppKit" hook');async function t(n){await wl?.open(n)}async function e(){await wl?.close()}return{open:t,close:e}}function Cut(){if(!wl)throw new Error('Please call "createAppKit" before using "useAppKitState" hook');const[t,e]=I.useState({...wl.getState(),initialized:!1}),[n,r]=I.useState(wl.getRemoteFeatures());return I.useEffect(()=>{if(wl){e({...wl.getState()}),r(wl.getRemoteFeatures());const s=wl?.subscribeState(o=>{e({...o})}),i=wl?.subscribeRemoteFeatures(o=>{r(o)});return()=>{s?.(),i?.()}}return()=>null},[]),{...t,...n??{}}}/** + * @license + * Copyright 2018 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const _ut=new Set(["children","localName","ref","style","className"]),ate=new WeakMap,cte=(t,e,n,r,s)=>{const i=s?.[e];i===void 0?(t[e]=n,n==null&&e in HTMLElement.prototype&&t.removeAttribute(e)):n!==r&&((o,a,c)=>{let l=ate.get(o);l===void 0&&ate.set(o,l=new Map);let u=l.get(a);c!==void 0?u===void 0?(l.set(a,u={handleEvent:c}),o.addEventListener(a,u)):u.handleEvent=c:u!==void 0&&(l.delete(a),o.removeEventListener(a,u))})(t,i,n)},Ik=({react:t,tagName:e,elementClass:n,events:r,displayName:s})=>{const i=new Set(Object.keys(r??{})),o=t.forwardRef((a,c)=>{const l=t.useRef(new Map),u=t.useRef(null),d={},f={};for(const[p,m]of Object.entries(a))_ut.has(p)?d[p==="className"?"class":p]=m:i.has(p)||p in n.prototype?f[p]=m:d[p]=m;return t.useLayoutEffect(()=>{if(u.current===null)return;const p=new Map;for(const m in f)cte(u.current,m,a[m],l.current.get(m),r),l.current.delete(m),p.set(m,a[m]);for(const[m,y]of l.current)cte(u.current,m,void 0,y,r);l.current=p}),t.useLayoutEffect(()=>{u.current?.removeAttribute("defer-hydration")},[]),d.suppressHydrationWarning=!0,t.createElement(e,{...d,ref:t.useCallback(p=>{u.current=p,typeof c=="function"?c(p):c!==null&&(c.current=p)},[c])})});return o.displayName=s??n.name,o};/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const Sut={attribute:!0,type:String,converter:HT,reflect:!1,hasChanged:Qz},Aut=(t=Sut,e,n)=>{const{kind:r,metadata:s}=n;let i=globalThis.litPropertyMetadata.get(s);if(i===void 0&&globalThis.litPropertyMetadata.set(s,i=new Map),r==="setter"&&((t=Object.create(t)).wrapped=!0),i.set(n.name,t),r==="accessor"){const{name:o}=n;return{set(a){const c=e.get.call(this);e.set.call(this,a),this.requestUpdate(o,c,t)},init(a){return a!==void 0&&this.C(o,void 0,t,a),a}}}if(r==="setter"){const{name:o}=n;return function(a){const c=this[o];e.call(this,a),this.requestUpdate(o,c,t)}}throw Error("Unsupported decorator location: "+r)};function ee(t){return(e,n)=>typeof n=="object"?Aut(t,e,n):((r,s,i)=>{const o=s.hasOwnProperty(i);return s.constructor.createProperty(i,r),o?Object.getOwnPropertyDescriptor(s,i):void 0})(t,e,n)}/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */function Ne(t){return ee({...t,state:!0,attribute:!1})}/** + * @license + * Copyright 2018 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const rt=t=>t??Ds,Iut=it` + :host { + display: block; + width: var(--local-width); + height: var(--local-height); + } + + :host([data-object-fit='cover']) img { + object-fit: cover; + object-position: center center; + } + + :host([data-object-fit='contain']) img { + object-fit: contain; + object-position: center center; + } + + img { + display: block; + width: 100%; + height: 100%; + border-radius: inherit; + } +`;var h3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Ay=class extends He{constructor(){super(...arguments),this.src="./path/to/image.jpg",this.alt="Image",this.size=void 0,this.objectFit="cover"}render(){return this.objectFit&&(this.dataset.objectFit=this.objectFit),this.style.cssText=` + --local-width: ${this.size?`var(--wui-icon-size-${this.size});`:"100%"}; + --local-height: ${this.size?`var(--wui-icon-size-${this.size});`:"100%"}; + `,K`${this.alt}`}handleImageError(){this.dispatchEvent(new CustomEvent("onLoadError",{bubbles:!0,composed:!0}))}};Ay.styles=[Ht,mk,Iut];h3([ee()],Ay.prototype,"src",void 0);h3([ee()],Ay.prototype,"alt",void 0);h3([ee()],Ay.prototype,"size",void 0);h3([ee()],Ay.prototype,"objectFit",void 0);Ay=h3([We("wui-image")],Ay);const Tut=it` + :host { + display: flex; + } + + :host([data-size='sm']) > svg { + width: 12px; + height: 12px; + } + + :host([data-size='md']) > svg { + width: 16px; + height: 16px; + } + + :host([data-size='lg']) > svg { + width: 24px; + height: 24px; + } + + :host([data-size='xl']) > svg { + width: 32px; + height: 32px; + } + + svg { + animation: rotate 2s linear infinite; + } + + circle { + fill: none; + stroke: var(--local-color); + stroke-width: 4px; + stroke-dasharray: 1, 124; + stroke-dashoffset: 0; + stroke-linecap: round; + animation: dash 1.5s ease-in-out infinite; + } + + :host([data-size='md']) > svg > circle { + stroke-width: 6px; + } + + :host([data-size='sm']) > svg > circle { + stroke-width: 8px; + } + + @keyframes rotate { + 100% { + transform: rotate(360deg); + } + } + + @keyframes dash { + 0% { + stroke-dasharray: 1, 124; + stroke-dashoffset: 0; + } + + 50% { + stroke-dasharray: 90, 124; + stroke-dashoffset: -35; + } + + 100% { + stroke-dashoffset: -125; + } + } +`;var wW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let y_=class extends He{constructor(){super(...arguments),this.color="accent-100",this.size="lg"}render(){return this.style.cssText=`--local-color: ${this.color==="inherit"?"inherit":`var(--wui-color-${this.color})`}`,this.dataset.size=this.size,K` + + `}};y_.styles=[Ht,Tut];wW([ee()],y_.prototype,"color",void 0);wW([ee()],y_.prototype,"size",void 0);y_=wW([We("wui-loading-spinner")],y_);/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const u0e={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},bW=t=>(...e)=>({_$litDirective$:t,values:e});let d0e=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,n,r){this._$Ct=e,this._$AM=n,this._$Ci=r}_$AS(e,n){return this.update(e,n)}update(e,n){return this.render(...n)}};/** + * @license + * Copyright 2018 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const w_=bW(class extends d0e{constructor(t){if(super(t),t.type!==u0e.ATTRIBUTE||t.name!=="class"||t.strings?.length>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(t){return" "+Object.keys(t).filter(e=>t[e]).join(" ")+" "}update(t,[e]){if(this.st===void 0){this.st=new Set,t.strings!==void 0&&(this.nt=new Set(t.strings.join(" ").split(/\s/).filter(r=>r!=="")));for(const r in e)e[r]&&!this.nt?.has(r)&&this.st.add(r);return this.render(e)}const n=t.element.classList;for(const r of this.st)r in e||(n.remove(r),this.st.delete(r));for(const r in e){const s=!!e[r];s===this.st.has(r)||this.nt?.has(r)||(s?(n.add(r),this.st.add(r)):(n.remove(r),this.st.delete(r)))}return Qh}}),Nut=it` + :host { + display: inline-flex !important; + } + + slot { + width: 100%; + display: inline-block; + font-style: normal; + font-family: var(--wui-font-family); + font-feature-settings: + 'tnum' on, + 'lnum' on, + 'case' on; + line-height: 130%; + font-weight: var(--wui-font-weight-regular); + overflow: inherit; + text-overflow: inherit; + text-align: var(--local-align); + color: var(--local-color); + } + + .wui-line-clamp-1 { + overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 1; + } + + .wui-line-clamp-2 { + overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + } + + .wui-font-medium-400 { + font-size: var(--wui-font-size-medium); + font-weight: var(--wui-font-weight-light); + letter-spacing: var(--wui-letter-spacing-medium); + } + + .wui-font-medium-600 { + font-size: var(--wui-font-size-medium); + letter-spacing: var(--wui-letter-spacing-medium); + } + + .wui-font-title-600 { + font-size: var(--wui-font-size-title); + letter-spacing: var(--wui-letter-spacing-title); + } + + .wui-font-title-6-600 { + font-size: var(--wui-font-size-title-6); + letter-spacing: var(--wui-letter-spacing-title-6); + } + + .wui-font-mini-700 { + font-size: var(--wui-font-size-mini); + letter-spacing: var(--wui-letter-spacing-mini); + text-transform: uppercase; + } + + .wui-font-large-500, + .wui-font-large-600, + .wui-font-large-700 { + font-size: var(--wui-font-size-large); + letter-spacing: var(--wui-letter-spacing-large); + } + + .wui-font-2xl-500, + .wui-font-2xl-600, + .wui-font-2xl-700 { + font-size: var(--wui-font-size-2xl); + letter-spacing: var(--wui-letter-spacing-2xl); + } + + .wui-font-paragraph-400, + .wui-font-paragraph-500, + .wui-font-paragraph-600, + .wui-font-paragraph-700 { + font-size: var(--wui-font-size-paragraph); + letter-spacing: var(--wui-letter-spacing-paragraph); + } + + .wui-font-small-400, + .wui-font-small-500, + .wui-font-small-600 { + font-size: var(--wui-font-size-small); + letter-spacing: var(--wui-letter-spacing-small); + } + + .wui-font-tiny-400, + .wui-font-tiny-500, + .wui-font-tiny-600 { + font-size: var(--wui-font-size-tiny); + letter-spacing: var(--wui-letter-spacing-tiny); + } + + .wui-font-micro-700, + .wui-font-micro-600, + .wui-font-micro-500 { + font-size: var(--wui-font-size-micro); + letter-spacing: var(--wui-letter-spacing-micro); + text-transform: uppercase; + } + + .wui-font-tiny-400, + .wui-font-small-400, + .wui-font-medium-400, + .wui-font-paragraph-400 { + font-weight: var(--wui-font-weight-light); + } + + .wui-font-large-700, + .wui-font-paragraph-700, + .wui-font-micro-700, + .wui-font-mini-700 { + font-weight: var(--wui-font-weight-bold); + } + + .wui-font-medium-600, + .wui-font-medium-title-600, + .wui-font-title-6-600, + .wui-font-large-600, + .wui-font-paragraph-600, + .wui-font-small-600, + .wui-font-tiny-600, + .wui-font-micro-600 { + font-weight: var(--wui-font-weight-medium); + } + + :host([disabled]) { + opacity: 0.4; + } +`;var p3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Iy=class extends He{constructor(){super(...arguments),this.variant="paragraph-500",this.color="fg-300",this.align="left",this.lineClamp=void 0}render(){const e={[`wui-font-${this.variant}`]:!0,[`wui-color-${this.color}`]:!0,[`wui-line-clamp-${this.lineClamp}`]:!!this.lineClamp};return this.style.cssText=` + --local-align: ${this.align}; + --local-color: var(--wui-color-${this.color}); + `,K``}};Iy.styles=[Ht,Nut];p3([ee()],Iy.prototype,"variant",void 0);p3([ee()],Iy.prototype,"color",void 0);p3([ee()],Iy.prototype,"align",void 0);p3([ee()],Iy.prototype,"lineClamp",void 0);Iy=p3([We("wui-text")],Iy);const Put=it` + :host { + display: flex; + width: inherit; + height: inherit; + } +`;var Yc=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let ia=class extends He{render(){return this.style.cssText=` + flex-direction: ${this.flexDirection}; + flex-wrap: ${this.flexWrap}; + flex-basis: ${this.flexBasis}; + flex-grow: ${this.flexGrow}; + flex-shrink: ${this.flexShrink}; + align-items: ${this.alignItems}; + justify-content: ${this.justifyContent}; + column-gap: ${this.columnGap&&`var(--wui-spacing-${this.columnGap})`}; + row-gap: ${this.rowGap&&`var(--wui-spacing-${this.rowGap})`}; + gap: ${this.gap&&`var(--wui-spacing-${this.gap})`}; + padding-top: ${this.padding&&qr.getSpacingStyles(this.padding,0)}; + padding-right: ${this.padding&&qr.getSpacingStyles(this.padding,1)}; + padding-bottom: ${this.padding&&qr.getSpacingStyles(this.padding,2)}; + padding-left: ${this.padding&&qr.getSpacingStyles(this.padding,3)}; + margin-top: ${this.margin&&qr.getSpacingStyles(this.margin,0)}; + margin-right: ${this.margin&&qr.getSpacingStyles(this.margin,1)}; + margin-bottom: ${this.margin&&qr.getSpacingStyles(this.margin,2)}; + margin-left: ${this.margin&&qr.getSpacingStyles(this.margin,3)}; + `,K``}};ia.styles=[Ht,Put];Yc([ee()],ia.prototype,"flexDirection",void 0);Yc([ee()],ia.prototype,"flexWrap",void 0);Yc([ee()],ia.prototype,"flexBasis",void 0);Yc([ee()],ia.prototype,"flexGrow",void 0);Yc([ee()],ia.prototype,"flexShrink",void 0);Yc([ee()],ia.prototype,"alignItems",void 0);Yc([ee()],ia.prototype,"justifyContent",void 0);Yc([ee()],ia.prototype,"columnGap",void 0);Yc([ee()],ia.prototype,"rowGap",void 0);Yc([ee()],ia.prototype,"gap",void 0);Yc([ee()],ia.prototype,"padding",void 0);Yc([ee()],ia.prototype,"margin",void 0);ia=Yc([We("wui-flex")],ia);const kut=it` + :host { + display: block; + width: var(--local-width); + height: var(--local-height); + border-radius: var(--wui-border-radius-3xl); + box-shadow: 0 0 0 8px var(--wui-color-gray-glass-005); + overflow: hidden; + position: relative; + } + + :host([data-variant='generated']) { + --mixed-local-color-1: var(--local-color-1); + --mixed-local-color-2: var(--local-color-2); + --mixed-local-color-3: var(--local-color-3); + --mixed-local-color-4: var(--local-color-4); + --mixed-local-color-5: var(--local-color-5); + } + + @supports (background: color-mix(in srgb, white 50%, black)) { + :host([data-variant='generated']) { + --mixed-local-color-1: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--local-color-1) + ); + --mixed-local-color-2: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--local-color-2) + ); + --mixed-local-color-3: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--local-color-3) + ); + --mixed-local-color-4: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--local-color-4) + ); + --mixed-local-color-5: color-mix( + in srgb, + var(--w3m-color-mix) var(--w3m-color-mix-strength), + var(--local-color-5) + ); + } + } + + :host([data-variant='generated']) { + box-shadow: 0 0 0 8px var(--wui-color-gray-glass-005); + background: radial-gradient( + var(--local-radial-circle), + #fff 0.52%, + var(--mixed-local-color-5) 31.25%, + var(--mixed-local-color-3) 51.56%, + var(--mixed-local-color-2) 65.63%, + var(--mixed-local-color-1) 82.29%, + var(--mixed-local-color-4) 100% + ); + } + + :host([data-variant='default']) { + box-shadow: 0 0 0 8px var(--wui-color-gray-glass-005); + background: radial-gradient( + 75.29% 75.29% at 64.96% 24.36%, + #fff 0.52%, + #f5ccfc 31.25%, + #dba4f5 51.56%, + #9a8ee8 65.63%, + #6493da 82.29%, + #6ebdea 100% + ); + } +`;var g3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Ty=class extends He{constructor(){super(...arguments),this.imageSrc=void 0,this.alt=void 0,this.address=void 0,this.size="xl"}render(){return this.style.cssText=` + --local-width: var(--wui-icon-box-size-${this.size}); + --local-height: var(--wui-icon-box-size-${this.size}); + `,K`${this.visualTemplate()}`}visualTemplate(){if(this.imageSrc)return this.dataset.variant="image",K``;if(this.address){this.dataset.variant="generated";const e=qr.generateAvatarColors(this.address);return this.style.cssText+=` + ${e}`,null}return this.dataset.variant="default",null}};Ty.styles=[Ht,kut];g3([ee()],Ty.prototype,"imageSrc",void 0);g3([ee()],Ty.prototype,"alt",void 0);g3([ee()],Ty.prototype,"address",void 0);g3([ee()],Ty.prototype,"size",void 0);Ty=g3([We("wui-avatar")],Ty);/** + * @license + * Copyright 2020 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const Rut=t=>t===null||typeof t!="object"&&typeof t!="function",Out=t=>t.strings===void 0;/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const DE=(t,e)=>{const n=t._$AN;if(n===void 0)return!1;for(const r of n)r._$AO?.(e,!1),DE(r,e);return!0},XT=t=>{let e,n;do{if((e=t._$AM)===void 0)break;n=e._$AN,n.delete(t),t=e}while(n?.size===0)},f0e=t=>{for(let e;e=t._$AM;t=e){let n=e._$AN;if(n===void 0)e._$AN=n=new Set;else if(n.has(t))break;n.add(t),Mut(e)}};function $ut(t){this._$AN!==void 0?(XT(this),this._$AM=t,f0e(this)):this._$AM=t}function Dut(t,e=!1,n=0){const r=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(e)if(Array.isArray(r))for(let i=n;i{t.type==u0e.CHILD&&(t._$AP??=Dut,t._$AQ??=$ut)};let h0e=class extends d0e{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,n,r){super._$AT(e,n,r),f0e(this),this.isConnected=e._$AU}_$AO(e,n=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),n&&(DE(this,e),XT(this))}setValue(e){if(Out(this._$Ct))this._$Ct._$AI(e,this);else{const n=[...this._$Ct._$AH];n[this._$Ci]=e,this._$Ct._$AI(n,this,0)}}disconnected(){}reconnected(){}};/** + * @license + * Copyright 2021 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */let Lut=class{constructor(e){this.G=e}disconnect(){this.G=void 0}reconnect(e){this.G=e}deref(){return this.G}},But=class{constructor(){this.Y=void 0,this.Z=void 0}get(){return this.Y}pause(){this.Y??=new Promise(e=>this.Z=e)}resume(){this.Z?.(),this.Y=this.Z=void 0}};/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const lte=t=>!Rut(t)&&typeof t.then=="function",ute=1073741823;let Uut=class extends h0e{constructor(){super(...arguments),this._$Cwt=ute,this._$Cbt=[],this._$CK=new Lut(this),this._$CX=new But}render(...e){return e.find(n=>!lte(n))??Qh}update(e,n){const r=this._$Cbt;let s=r.length;this._$Cbt=n;const i=this._$CK,o=this._$CX;this.isConnected||this.disconnected();for(let a=0;athis._$Cwt);a++){const c=n[a];if(!lte(c))return this._$Cwt=a,c;a{for(;o.get();)await o.get();const u=i.deref();if(u!==void 0){const d=u._$Cbt.indexOf(c);d>-1&&d=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const dte={add:async()=>(await et(async()=>{const{addSvg:t}=await import("./add-B1b4Ty-5.js");return{addSvg:t}},[])).addSvg,allWallets:async()=>(await et(async()=>{const{allWalletsSvg:t}=await import("./all-wallets-DKy0zRrU.js");return{allWalletsSvg:t}},[])).allWalletsSvg,arrowBottomCircle:async()=>(await et(async()=>{const{arrowBottomCircleSvg:t}=await import("./arrow-bottom-circle-Bo8O7JgA.js");return{arrowBottomCircleSvg:t}},[])).arrowBottomCircleSvg,appStore:async()=>(await et(async()=>{const{appStoreSvg:t}=await import("./app-store-qA41k1iG.js");return{appStoreSvg:t}},[])).appStoreSvg,apple:async()=>(await et(async()=>{const{appleSvg:t}=await import("./apple-B3teXytZ.js");return{appleSvg:t}},[])).appleSvg,arrowBottom:async()=>(await et(async()=>{const{arrowBottomSvg:t}=await import("./arrow-bottom-C7NMSF0g.js");return{arrowBottomSvg:t}},[])).arrowBottomSvg,arrowLeft:async()=>(await et(async()=>{const{arrowLeftSvg:t}=await import("./arrow-left-DFwUccrs.js");return{arrowLeftSvg:t}},[])).arrowLeftSvg,arrowRight:async()=>(await et(async()=>{const{arrowRightSvg:t}=await import("./arrow-right-2iACcb0n.js");return{arrowRightSvg:t}},[])).arrowRightSvg,arrowTop:async()=>(await et(async()=>{const{arrowTopSvg:t}=await import("./arrow-top-BtzNMuue.js");return{arrowTopSvg:t}},[])).arrowTopSvg,bank:async()=>(await et(async()=>{const{bankSvg:t}=await import("./bank-DPwf5DsI.js");return{bankSvg:t}},[])).bankSvg,browser:async()=>(await et(async()=>{const{browserSvg:t}=await import("./browser-CC3et0uk.js");return{browserSvg:t}},[])).browserSvg,bin:async()=>(await et(async()=>{const{binSvg:t}=await import("./bin-BshwV3dZ.js");return{binSvg:t}},[])).binSvg,bitcoin:async()=>(await et(async()=>{const{bitcoinSvg:t}=await import("./bitcoin-M-S4Gfjc.js");return{bitcoinSvg:t}},[])).bitcoinSvg,card:async()=>(await et(async()=>{const{cardSvg:t}=await import("./card-9KwzYBwi.js");return{cardSvg:t}},[])).cardSvg,checkmark:async()=>(await et(async()=>{const{checkmarkSvg:t}=await import("./checkmark-CDGh-jbz.js");return{checkmarkSvg:t}},[])).checkmarkSvg,checkmarkBold:async()=>(await et(async()=>{const{checkmarkBoldSvg:t}=await import("./checkmark-bold-DBpjkRrv.js");return{checkmarkBoldSvg:t}},[])).checkmarkBoldSvg,chevronBottom:async()=>(await et(async()=>{const{chevronBottomSvg:t}=await import("./chevron-bottom-B9wx_mOd.js");return{chevronBottomSvg:t}},[])).chevronBottomSvg,chevronLeft:async()=>(await et(async()=>{const{chevronLeftSvg:t}=await import("./chevron-left-nYdEcmRU.js");return{chevronLeftSvg:t}},[])).chevronLeftSvg,chevronRight:async()=>(await et(async()=>{const{chevronRightSvg:t}=await import("./chevron-right-BIvCTfn4.js");return{chevronRightSvg:t}},[])).chevronRightSvg,chevronTop:async()=>(await et(async()=>{const{chevronTopSvg:t}=await import("./chevron-top-D_T8NmSU.js");return{chevronTopSvg:t}},[])).chevronTopSvg,chromeStore:async()=>(await et(async()=>{const{chromeStoreSvg:t}=await import("./chrome-store-DjKACh-G.js");return{chromeStoreSvg:t}},[])).chromeStoreSvg,clock:async()=>(await et(async()=>{const{clockSvg:t}=await import("./clock-Bu8fqLqw.js");return{clockSvg:t}},[])).clockSvg,close:async()=>(await et(async()=>{const{closeSvg:t}=await import("./close-DkOqA3XA.js");return{closeSvg:t}},[])).closeSvg,compass:async()=>(await et(async()=>{const{compassSvg:t}=await import("./compass-k9qpYhtB.js");return{compassSvg:t}},[])).compassSvg,coinPlaceholder:async()=>(await et(async()=>{const{coinPlaceholderSvg:t}=await import("./coinPlaceholder-Bog9viJQ.js");return{coinPlaceholderSvg:t}},[])).coinPlaceholderSvg,copy:async()=>(await et(async()=>{const{copySvg:t}=await import("./copy-CrR_vPRD.js");return{copySvg:t}},[])).copySvg,cursor:async()=>(await et(async()=>{const{cursorSvg:t}=await import("./cursor-B5zA10jJ.js");return{cursorSvg:t}},[])).cursorSvg,cursorTransparent:async()=>(await et(async()=>{const{cursorTransparentSvg:t}=await import("./cursor-transparent-8xgUPsqN.js");return{cursorTransparentSvg:t}},[])).cursorTransparentSvg,circle:async()=>(await et(async()=>{const{circleSvg:t}=await import("./circle-CMRf11j6.js");return{circleSvg:t}},[])).circleSvg,desktop:async()=>(await et(async()=>{const{desktopSvg:t}=await import("./desktop-CW7qCBPc.js");return{desktopSvg:t}},[])).desktopSvg,disconnect:async()=>(await et(async()=>{const{disconnectSvg:t}=await import("./disconnect-DzbPXgkg.js");return{disconnectSvg:t}},[])).disconnectSvg,discord:async()=>(await et(async()=>{const{discordSvg:t}=await import("./discord-CPs1H_Zj.js");return{discordSvg:t}},[])).discordSvg,ethereum:async()=>(await et(async()=>{const{ethereumSvg:t}=await import("./ethereum-pDlrEry5.js");return{ethereumSvg:t}},[])).ethereumSvg,etherscan:async()=>(await et(async()=>{const{etherscanSvg:t}=await import("./etherscan-yowPVDyy.js");return{etherscanSvg:t}},[])).etherscanSvg,extension:async()=>(await et(async()=>{const{extensionSvg:t}=await import("./extension-V_MQztIO.js");return{extensionSvg:t}},[])).extensionSvg,externalLink:async()=>(await et(async()=>{const{externalLinkSvg:t}=await import("./external-link-D5nUBuK8.js");return{externalLinkSvg:t}},[])).externalLinkSvg,facebook:async()=>(await et(async()=>{const{facebookSvg:t}=await import("./facebook-IzGdkHXn.js");return{facebookSvg:t}},[])).facebookSvg,farcaster:async()=>(await et(async()=>{const{farcasterSvg:t}=await import("./farcaster-CQ1ZnK9M.js");return{farcasterSvg:t}},[])).farcasterSvg,filters:async()=>(await et(async()=>{const{filtersSvg:t}=await import("./filters-CENUgXu3.js");return{filtersSvg:t}},[])).filtersSvg,github:async()=>(await et(async()=>{const{githubSvg:t}=await import("./github-DB7o3FYw.js");return{githubSvg:t}},[])).githubSvg,google:async()=>(await et(async()=>{const{googleSvg:t}=await import("./google-BQasw2Dk.js");return{googleSvg:t}},[])).googleSvg,helpCircle:async()=>(await et(async()=>{const{helpCircleSvg:t}=await import("./help-circle-VyIXOAlM.js");return{helpCircleSvg:t}},[])).helpCircleSvg,image:async()=>(await et(async()=>{const{imageSvg:t}=await import("./image-Dd9GhBqt.js");return{imageSvg:t}},[])).imageSvg,id:async()=>(await et(async()=>{const{idSvg:t}=await import("./id-Dqw-Wgu3.js");return{idSvg:t}},[])).idSvg,infoCircle:async()=>(await et(async()=>{const{infoCircleSvg:t}=await import("./info-circle-CXT71X33.js");return{infoCircleSvg:t}},[])).infoCircleSvg,lightbulb:async()=>(await et(async()=>{const{lightbulbSvg:t}=await import("./lightbulb-DXUATdFd.js");return{lightbulbSvg:t}},[])).lightbulbSvg,mail:async()=>(await et(async()=>{const{mailSvg:t}=await import("./mail-D5Kz7lp0.js");return{mailSvg:t}},[])).mailSvg,mobile:async()=>(await et(async()=>{const{mobileSvg:t}=await import("./mobile-iSKvjbUf.js");return{mobileSvg:t}},[])).mobileSvg,more:async()=>(await et(async()=>{const{moreSvg:t}=await import("./more-C8OTKC0g.js");return{moreSvg:t}},[])).moreSvg,networkPlaceholder:async()=>(await et(async()=>{const{networkPlaceholderSvg:t}=await import("./network-placeholder-C3ZqCyor.js");return{networkPlaceholderSvg:t}},[])).networkPlaceholderSvg,nftPlaceholder:async()=>(await et(async()=>{const{nftPlaceholderSvg:t}=await import("./nftPlaceholder-1Liwzove.js");return{nftPlaceholderSvg:t}},[])).nftPlaceholderSvg,off:async()=>(await et(async()=>{const{offSvg:t}=await import("./off-DkfF0_gL.js");return{offSvg:t}},[])).offSvg,playStore:async()=>(await et(async()=>{const{playStoreSvg:t}=await import("./play-store-D-_ekw15.js");return{playStoreSvg:t}},[])).playStoreSvg,plus:async()=>(await et(async()=>{const{plusSvg:t}=await import("./plus-DaZ9pOJ-.js");return{plusSvg:t}},[])).plusSvg,qrCode:async()=>(await et(async()=>{const{qrCodeIcon:t}=await import("./qr-code-zSuzYj6q.js");return{qrCodeIcon:t}},[])).qrCodeIcon,recycleHorizontal:async()=>(await et(async()=>{const{recycleHorizontalSvg:t}=await import("./recycle-horizontal-B85mmaoN.js");return{recycleHorizontalSvg:t}},[])).recycleHorizontalSvg,refresh:async()=>(await et(async()=>{const{refreshSvg:t}=await import("./refresh-CsELgs90.js");return{refreshSvg:t}},[])).refreshSvg,search:async()=>(await et(async()=>{const{searchSvg:t}=await import("./search-DCC0JOe_.js");return{searchSvg:t}},[])).searchSvg,send:async()=>(await et(async()=>{const{sendSvg:t}=await import("./send-DbOL9rGQ.js");return{sendSvg:t}},[])).sendSvg,swapHorizontal:async()=>(await et(async()=>{const{swapHorizontalSvg:t}=await import("./swapHorizontal-iQa05UE_.js");return{swapHorizontalSvg:t}},[])).swapHorizontalSvg,swapHorizontalMedium:async()=>(await et(async()=>{const{swapHorizontalMediumSvg:t}=await import("./swapHorizontalMedium-KeWOduSV.js");return{swapHorizontalMediumSvg:t}},[])).swapHorizontalMediumSvg,swapHorizontalBold:async()=>(await et(async()=>{const{swapHorizontalBoldSvg:t}=await import("./swapHorizontalBold-CxDNxTSc.js");return{swapHorizontalBoldSvg:t}},[])).swapHorizontalBoldSvg,swapHorizontalRoundedBold:async()=>(await et(async()=>{const{swapHorizontalRoundedBoldSvg:t}=await import("./swapHorizontalRoundedBold-BKa1b4V9.js");return{swapHorizontalRoundedBoldSvg:t}},[])).swapHorizontalRoundedBoldSvg,swapVertical:async()=>(await et(async()=>{const{swapVerticalSvg:t}=await import("./swapVertical-BkcJfrl6.js");return{swapVerticalSvg:t}},[])).swapVerticalSvg,solana:async()=>(await et(async()=>{const{solanaSvg:t}=await import("./solana-wnPogKuz.js");return{solanaSvg:t}},[])).solanaSvg,telegram:async()=>(await et(async()=>{const{telegramSvg:t}=await import("./telegram-APKTNwpu.js");return{telegramSvg:t}},[])).telegramSvg,threeDots:async()=>(await et(async()=>{const{threeDotsSvg:t}=await import("./three-dots-8jGyRbgm.js");return{threeDotsSvg:t}},[])).threeDotsSvg,twitch:async()=>(await et(async()=>{const{twitchSvg:t}=await import("./twitch-BUKiRB8R.js");return{twitchSvg:t}},[])).twitchSvg,twitter:async()=>(await et(async()=>{const{xSvg:t}=await import("./x-C3LRqiud.js");return{xSvg:t}},[])).xSvg,twitterIcon:async()=>(await et(async()=>{const{twitterIconSvg:t}=await import("./twitterIcon-CzR_RgAK.js");return{twitterIconSvg:t}},[])).twitterIconSvg,user:async()=>(await et(async()=>{const{userSvg:t}=await import("./user-BSr3AuAa.js");return{userSvg:t}},[])).userSvg,verify:async()=>(await et(async()=>{const{verifySvg:t}=await import("./verify-BjYfOgD5.js");return{verifySvg:t}},[])).verifySvg,verifyFilled:async()=>(await et(async()=>{const{verifyFilledSvg:t}=await import("./verify-filled-C34Ypr-X.js");return{verifyFilledSvg:t}},[])).verifyFilledSvg,wallet:async()=>(await et(async()=>{const{walletSvg:t}=await import("./wallet-B7rYWpGd.js");return{walletSvg:t}},[])).walletSvg,walletConnect:async()=>(await et(async()=>{const{walletConnectSvg:t}=await import("./walletconnect-DhIwJMgu.js");return{walletConnectSvg:t}},[])).walletConnectSvg,walletConnectLightBrown:async()=>(await et(async()=>{const{walletConnectLightBrownSvg:t}=await import("./walletconnect-DhIwJMgu.js");return{walletConnectLightBrownSvg:t}},[])).walletConnectLightBrownSvg,walletConnectBrown:async()=>(await et(async()=>{const{walletConnectBrownSvg:t}=await import("./walletconnect-DhIwJMgu.js");return{walletConnectBrownSvg:t}},[])).walletConnectBrownSvg,walletPlaceholder:async()=>(await et(async()=>{const{walletPlaceholderSvg:t}=await import("./wallet-placeholder-BUQhm8ne.js");return{walletPlaceholderSvg:t}},[])).walletPlaceholderSvg,warningCircle:async()=>(await et(async()=>{const{warningCircleSvg:t}=await import("./warning-circle-Dwz2WWdH.js");return{warningCircleSvg:t}},[])).warningCircleSvg,x:async()=>(await et(async()=>{const{xSvg:t}=await import("./x-C3LRqiud.js");return{xSvg:t}},[])).xSvg,info:async()=>(await et(async()=>{const{infoSvg:t}=await import("./info-BzF0mPAp.js");return{infoSvg:t}},[])).infoSvg,exclamationTriangle:async()=>(await et(async()=>{const{exclamationTriangleSvg:t}=await import("./exclamation-triangle-ByL4C-X2.js");return{exclamationTriangleSvg:t}},[])).exclamationTriangleSvg,reown:async()=>(await et(async()=>{const{reownSvg:t}=await import("./reown-logo-CHoXyyWe.js");return{reownSvg:t}},[])).reownSvg,"x-mark":async()=>(await et(async()=>{const{xMarkSvg:t}=await import("./x-mark-DqeqBMH2.js");return{xMarkSvg:t}},[])).xMarkSvg};async function Wut(t){if(wD.has(t))return wD.get(t);const n=(dte[t]??dte.copy)();return wD.set(t,n),n}let Ny=class extends He{constructor(){super(...arguments),this.size="md",this.name="copy",this.color="fg-300",this.aspectRatio="1 / 1"}render(){return this.style.cssText=` + --local-color: ${`var(--wui-color-${this.color});`} + --local-width: ${`var(--wui-icon-size-${this.size});`} + --local-aspect-ratio: ${this.aspectRatio} + `,K`${Fut(Wut(this.name),K`
`)}`}};Ny.styles=[Ht,mk,zut];m3([ee()],Ny.prototype,"size",void 0);m3([ee()],Ny.prototype,"name",void 0);m3([ee()],Ny.prototype,"color",void 0);m3([ee()],Ny.prototype,"aspectRatio",void 0);Ny=m3([We("wui-icon")],Ny);const Vut=it` + :host { + display: inline-flex; + justify-content: center; + align-items: center; + position: relative; + overflow: hidden; + background-color: var(--wui-color-gray-glass-020); + border-radius: var(--local-border-radius); + border: var(--local-border); + box-sizing: content-box; + width: var(--local-size); + height: var(--local-size); + min-height: var(--local-size); + min-width: var(--local-size); + } + + @supports (background: color-mix(in srgb, white 50%, black)) { + :host { + background-color: color-mix(in srgb, var(--local-bg-value) var(--local-bg-mix), transparent); + } + } +`;var bp=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let od=class extends He{constructor(){super(...arguments),this.size="md",this.backgroundColor="accent-100",this.iconColor="accent-100",this.background="transparent",this.border=!1,this.borderColor="wui-color-bg-125",this.icon="copy"}render(){const e=this.iconSize||this.size,n=this.size==="lg",r=this.size==="xl",s=n?"12%":"16%",i=n?"xxs":r?"s":"3xl",o=this.background==="gray",a=this.background==="opaque",c=this.backgroundColor==="accent-100"&&a||this.backgroundColor==="success-100"&&a||this.backgroundColor==="error-100"&&a||this.backgroundColor==="inverse-100"&&a;let l=`var(--wui-color-${this.backgroundColor})`;return c?l=`var(--wui-icon-box-bg-${this.backgroundColor})`:o&&(l=`var(--wui-color-gray-${this.backgroundColor})`),this.style.cssText=` + --local-bg-value: ${l}; + --local-bg-mix: ${c||o?"100%":s}; + --local-border-radius: var(--wui-border-radius-${i}); + --local-size: var(--wui-icon-box-size-${this.size}); + --local-border: ${this.borderColor==="wui-color-bg-125"?"2px":"1px"} solid ${this.border?`var(--${this.borderColor})`:"transparent"} + `,K` `}};od.styles=[Ht,lr,Vut];bp([ee()],od.prototype,"size",void 0);bp([ee()],od.prototype,"backgroundColor",void 0);bp([ee()],od.prototype,"iconColor",void 0);bp([ee()],od.prototype,"iconSize",void 0);bp([ee()],od.prototype,"background",void 0);bp([ee({type:Boolean})],od.prototype,"border",void 0);bp([ee()],od.prototype,"borderColor",void 0);bp([ee()],od.prototype,"icon",void 0);od=bp([We("wui-icon-box")],od);const Hut=it` + :host { + display: block; + } + + button { + border-radius: var(--wui-border-radius-3xl); + background: var(--wui-color-gray-glass-002); + display: flex; + gap: var(--wui-spacing-xs); + padding: var(--wui-spacing-3xs) var(--wui-spacing-xs) var(--wui-spacing-3xs) + var(--wui-spacing-xs); + border: 1px solid var(--wui-color-gray-glass-005); + } + + button:disabled { + background: var(--wui-color-gray-glass-015); + } + + button:disabled > wui-text { + color: var(--wui-color-gray-glass-015); + } + + button:disabled > wui-flex > wui-text { + color: var(--wui-color-gray-glass-015); + } + + button:disabled > wui-image, + button:disabled > wui-flex > wui-avatar { + filter: grayscale(1); + } + + button:has(wui-image) { + padding: var(--wui-spacing-3xs) var(--wui-spacing-3xs) var(--wui-spacing-3xs) + var(--wui-spacing-xs); + } + + wui-text { + color: var(--wui-color-fg-100); + } + + wui-flex > wui-text { + color: var(--wui-color-fg-200); + } + + wui-image, + wui-icon-box { + border-radius: var(--wui-border-radius-3xl); + width: 24px; + height: 24px; + box-shadow: 0 0 0 2px var(--wui-color-gray-glass-005); + } + + wui-flex { + border-radius: var(--wui-border-radius-3xl); + border: 1px solid var(--wui-color-gray-glass-005); + background: var(--wui-color-gray-glass-005); + padding: 4px var(--wui-spacing-m) 4px var(--wui-spacing-xxs); + } + + button.local-no-balance { + border-radius: 0px; + border: none; + background: transparent; + } + + wui-avatar { + width: 20px; + height: 20px; + box-shadow: 0 0 0 2px var(--wui-color-accent-glass-010); + } + + @media (max-width: 500px) { + button { + gap: 0px; + padding: var(--wui-spacing-3xs) var(--wui-spacing-xs) !important; + height: 32px; + } + wui-image, + wui-icon-box, + button > wui-text { + visibility: hidden; + width: 0px; + height: 0px; + } + button { + border-radius: 0px; + border: none; + background: transparent; + padding: 0px; + } + } + + @media (hover: hover) and (pointer: fine) { + button:hover:enabled > wui-flex > wui-text { + color: var(--wui-color-fg-175); + } + + button:active:enabled > wui-flex > wui-text { + color: var(--wui-color-fg-175); + } + } +`;var fd=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let zc=class extends He{constructor(){super(...arguments),this.networkSrc=void 0,this.avatarSrc=void 0,this.balance=void 0,this.isUnsupportedChain=void 0,this.disabled=!1,this.loading=!1,this.address="",this.profileName="",this.charsStart=4,this.charsEnd=6}render(){return K` + + `}balanceTemplate(){if(this.isUnsupportedChain)return K` + Switch Network`;if(this.balance){const e=this.networkSrc?K``:K` + + `,n=this.loading?K``:K` ${this.balance}`;return K`${e} ${n}`}return null}};zc.styles=[Ht,lr,Hut];fd([ee()],zc.prototype,"networkSrc",void 0);fd([ee()],zc.prototype,"avatarSrc",void 0);fd([ee()],zc.prototype,"balance",void 0);fd([ee({type:Boolean})],zc.prototype,"isUnsupportedChain",void 0);fd([ee({type:Boolean})],zc.prototype,"disabled",void 0);fd([ee({type:Boolean})],zc.prototype,"loading",void 0);fd([ee()],zc.prototype,"address",void 0);fd([ee()],zc.prototype,"profileName",void 0);fd([ee()],zc.prototype,"charsStart",void 0);fd([ee()],zc.prototype,"charsEnd",void 0);zc=fd([We("wui-account-button")],zc);var ua=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};class da extends He{constructor(){super(...arguments),this.unsubscribe=[],this.disabled=!1,this.balance="show",this.charsStart=4,this.charsEnd=6,this.namespace=void 0,this.isSupported=_e.state.allowUnsupportedChain?!0:G.state.activeChain?G.checkIfSupportedNetwork(G.state.activeChain):!0}connectedCallback(){super.connectedCallback(),this.setAccountData(G.getAccountData(this.namespace)),this.setNetworkData(G.getNetworkData(this.namespace))}firstUpdated(){const e=this.namespace;e?this.unsubscribe.push(G.subscribeChainProp("accountState",n=>{this.setAccountData(n)},e),G.subscribeChainProp("networkState",n=>{this.setNetworkData(n),this.isSupported=G.checkIfSupportedNetwork(e,n?.caipNetwork?.caipNetworkId)},e)):this.unsubscribe.push(mi.subscribeNetworkImages(()=>{this.networkImage=nr.getNetworkImage(this.network)}),G.subscribeKey("activeCaipAddress",n=>{this.caipAddress=n}),nt.subscribeKey("balance",n=>this.balanceVal=n),nt.subscribeKey("balanceSymbol",n=>this.balanceSymbol=n),nt.subscribeKey("profileName",n=>this.profileName=n),nt.subscribeKey("profileImage",n=>this.profileImage=n),G.subscribeKey("activeCaipNetwork",n=>{this.network=n,this.networkImage=nr.getNetworkImage(n),this.isSupported=n?.chainNamespace?G.checkIfSupportedNetwork(n?.chainNamespace):!0,this.fetchNetworkImage(n)}))}updated(){this.fetchNetworkImage(this.network)}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){if(!G.state.activeChain)return null;const e=this.balance==="show",n=typeof this.balanceVal!="string";return K` + + + `}onClick(){this.isSupported||_e.state.allowUnsupportedChain?tn.open({namespace:this.namespace}):tn.open({view:"UnsupportedChain"})}async fetchNetworkImage(e){e?.assets?.imageId&&(this.networkImage=await nr.fetchNetworkImage(e?.assets?.imageId))}setAccountData(e){e&&(this.caipAddress=e.caipAddress,this.balanceVal=e.balance,this.balanceSymbol=e.balanceSymbol,this.profileName=e.profileName,this.profileImage=e.profileImage)}setNetworkData(e){e&&(this.network=e.caipNetwork,this.networkImage=nr.getNetworkImage(e.caipNetwork))}}ua([ee({type:Boolean})],da.prototype,"disabled",void 0);ua([ee()],da.prototype,"balance",void 0);ua([ee()],da.prototype,"charsStart",void 0);ua([ee()],da.prototype,"charsEnd",void 0);ua([ee()],da.prototype,"namespace",void 0);ua([Ne()],da.prototype,"caipAddress",void 0);ua([Ne()],da.prototype,"balanceVal",void 0);ua([Ne()],da.prototype,"balanceSymbol",void 0);ua([Ne()],da.prototype,"profileName",void 0);ua([Ne()],da.prototype,"profileImage",void 0);ua([Ne()],da.prototype,"network",void 0);ua([Ne()],da.prototype,"networkImage",void 0);ua([Ne()],da.prototype,"isSupported",void 0);let pB=class extends da{};pB=ua([We("w3m-account-button")],pB);let QT=class extends da{};QT=ua([We("appkit-account-button")],QT);const qut=it` + :host { + display: block; + width: max-content; + } +`;var hd=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};class tu extends He{constructor(){super(...arguments),this.unsubscribe=[],this.disabled=!1,this.balance=void 0,this.size=void 0,this.label=void 0,this.loadingLabel=void 0,this.charsStart=4,this.charsEnd=6,this.namespace=void 0}connectedCallback(){super.connectedCallback(),this.caipAddress=this.namespace?G.state.chains.get(this.namespace)?.accountState?.caipAddress:G.state.activeCaipAddress}firstUpdated(){this.namespace?this.unsubscribe.push(G.subscribeChainProp("accountState",e=>{this.caipAddress=e?.caipAddress},this.namespace)):this.unsubscribe.push(G.subscribeKey("activeCaipAddress",e=>this.caipAddress=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return this.caipAddress?K` + + + `:K` + + `}}tu.styles=qut;hd([ee({type:Boolean})],tu.prototype,"disabled",void 0);hd([ee()],tu.prototype,"balance",void 0);hd([ee()],tu.prototype,"size",void 0);hd([ee()],tu.prototype,"label",void 0);hd([ee()],tu.prototype,"loadingLabel",void 0);hd([ee()],tu.prototype,"charsStart",void 0);hd([ee()],tu.prototype,"charsEnd",void 0);hd([ee()],tu.prototype,"namespace",void 0);hd([Ne()],tu.prototype,"caipAddress",void 0);let gB=class extends tu{};gB=hd([We("w3m-button")],gB);let JT=class extends tu{};JT=hd([We("appkit-button")],JT);const Kut=it` + :host { + position: relative; + display: block; + } + + button { + background: var(--wui-color-accent-100); + border: 1px solid var(--wui-color-gray-glass-010); + border-radius: var(--wui-border-radius-m); + gap: var(--wui-spacing-xs); + } + + button.loading { + background: var(--wui-color-gray-glass-010); + border: 1px solid var(--wui-color-gray-glass-010); + pointer-events: none; + } + + button:disabled { + background-color: var(--wui-color-gray-glass-015); + border: 1px solid var(--wui-color-gray-glass-010); + } + + button:disabled > wui-text { + color: var(--wui-color-gray-glass-015); + } + + @media (hover: hover) and (pointer: fine) { + button:hover:enabled { + background-color: var(--wui-color-accent-090); + } + + button:active:enabled { + background-color: var(--wui-color-accent-080); + } + } + + button:focus-visible { + border: 1px solid var(--wui-color-gray-glass-010); + background-color: var(--wui-color-accent-090); + -webkit-box-shadow: 0px 0px 0px 4px var(--wui-box-shadow-blue); + -moz-box-shadow: 0px 0px 0px 4px var(--wui-box-shadow-blue); + box-shadow: 0px 0px 0px 4px var(--wui-box-shadow-blue); + } + + button[data-size='sm'] { + padding: 6.75px 10px 7.25px; + } + + ::slotted(*) { + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + opacity: var(--local-opacity-100); + } + + button > wui-text { + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + opacity: var(--local-opacity-100); + color: var(--wui-color-inverse-100); + } + + button[data-size='md'] { + padding: 9px var(--wui-spacing-l) 9px var(--wui-spacing-l); + } + + button[data-size='md'] + wui-text { + padding-left: var(--wui-spacing-3xs); + } + + @media (max-width: 500px) { + button[data-size='md'] { + height: 32px; + padding: 5px 12px; + } + + button[data-size='md'] > wui-text > slot { + font-size: 14px !important; + } + } + + wui-loading-spinner { + width: 14px; + height: 14px; + } + + wui-loading-spinner::slotted(svg) { + width: 10px !important; + height: 10px !important; + } + + button[data-size='sm'] > wui-loading-spinner { + width: 12px; + height: 12px; + } +`;var vW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let b_=class extends He{constructor(){super(...arguments),this.size="md",this.loading=!1}render(){const e=this.size==="md"?"paragraph-600":"small-600";return K` + + `}loadingTemplate(){return this.loading?K``:null}};b_.styles=[Ht,lr,Kut];vW([ee()],b_.prototype,"size",void 0);vW([ee({type:Boolean})],b_.prototype,"loading",void 0);b_=vW([We("wui-connect-button")],b_);var R0=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};class O0 extends He{constructor(){super(),this.unsubscribe=[],this.size="md",this.label="Connect Wallet",this.loadingLabel="Connecting...",this.open=tn.state.open,this.loading=this.namespace?tn.state.loadingNamespaceMap.get(this.namespace):tn.state.loading,this.unsubscribe.push(tn.subscribe(e=>{this.open=e.open,this.loading=this.namespace?e.loadingNamespaceMap.get(this.namespace):e.loading}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return K` + + ${this.loading?this.loadingLabel:this.label} + + `}onClick(){this.open?tn.close():this.loading||tn.open({view:"Connect",namespace:this.namespace})}}R0([ee()],O0.prototype,"size",void 0);R0([ee()],O0.prototype,"label",void 0);R0([ee()],O0.prototype,"loadingLabel",void 0);R0([ee()],O0.prototype,"namespace",void 0);R0([Ne()],O0.prototype,"open",void 0);R0([Ne()],O0.prototype,"loading",void 0);let mB=class extends O0{};mB=R0([We("w3m-connect-button")],mB);let eN=class extends O0{};eN=R0([We("appkit-connect-button")],eN);const Gut=it` + :host { + display: block; + } + + button { + border-radius: var(--wui-border-radius-3xl); + display: flex; + gap: var(--wui-spacing-xs); + padding: var(--wui-spacing-2xs) var(--wui-spacing-s) var(--wui-spacing-2xs) + var(--wui-spacing-xs); + border: 1px solid var(--wui-color-gray-glass-010); + background-color: var(--wui-color-gray-glass-005); + color: var(--wui-color-fg-100); + } + + button:disabled { + border: 1px solid var(--wui-color-gray-glass-005); + background-color: var(--wui-color-gray-glass-015); + color: var(--wui-color-gray-glass-015); + } + + @media (hover: hover) and (pointer: fine) { + button:hover:enabled { + background-color: var(--wui-color-gray-glass-010); + } + + button:active:enabled { + background-color: var(--wui-color-gray-glass-015); + } + } + + wui-image, + wui-icon-box { + border-radius: var(--wui-border-radius-3xl); + width: 24px; + height: 24px; + box-shadow: 0 0 0 2px var(--wui-color-gray-glass-005); + } +`;var Tk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let e1=class extends He{constructor(){super(...arguments),this.imageSrc=void 0,this.isUnsupportedChain=void 0,this.disabled=!1}render(){return K` + + `}visualTemplate(){return this.isUnsupportedChain?K` + + `:this.imageSrc?K``:K` + + `}};e1.styles=[Ht,lr,Gut];Tk([ee()],e1.prototype,"imageSrc",void 0);Tk([ee({type:Boolean})],e1.prototype,"isUnsupportedChain",void 0);Tk([ee({type:Boolean})],e1.prototype,"disabled",void 0);e1=Tk([We("wui-network-button")],e1);const Zut=it` + :host { + display: block; + width: max-content; + } +`;var vp=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};class _f extends He{constructor(){super(),this.unsubscribe=[],this.disabled=!1,this.network=G.state.activeCaipNetwork,this.networkImage=nr.getNetworkImage(this.network),this.caipAddress=G.state.activeCaipAddress,this.loading=tn.state.loading,this.isSupported=_e.state.allowUnsupportedChain?!0:G.state.activeChain?G.checkIfSupportedNetwork(G.state.activeChain):!0,this.unsubscribe.push(mi.subscribeNetworkImages(()=>{this.networkImage=nr.getNetworkImage(this.network)}),G.subscribeKey("activeCaipAddress",e=>{this.caipAddress=e}),G.subscribeKey("activeCaipNetwork",e=>{this.network=e,this.networkImage=nr.getNetworkImage(e),this.isSupported=e?.chainNamespace?G.checkIfSupportedNetwork(e.chainNamespace):!0,nr.fetchNetworkImage(e?.assets?.imageId)}),tn.subscribeKey("loading",e=>this.loading=e))}firstUpdated(){nr.fetchNetworkImage(this.network?.assets?.imageId)}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const e=this.network?G.checkIfSupportedNetwork(this.network.chainNamespace):!0;return K` + + ${this.getLabel()} + + + `}getLabel(){return this.network?!this.isSupported&&!_e.state.allowUnsupportedChain?"Switch Network":this.network.name:this.label?this.label:this.caipAddress?"Unknown Network":"Select Network"}onClick(){this.loading||(Lt.sendEvent({type:"track",event:"CLICK_NETWORKS"}),tn.open({view:"Networks"}))}}_f.styles=Zut;vp([ee({type:Boolean})],_f.prototype,"disabled",void 0);vp([ee({type:String})],_f.prototype,"label",void 0);vp([Ne()],_f.prototype,"network",void 0);vp([Ne()],_f.prototype,"networkImage",void 0);vp([Ne()],_f.prototype,"caipAddress",void 0);vp([Ne()],_f.prototype,"loading",void 0);vp([Ne()],_f.prototype,"isSupported",void 0);let yB=class extends _f{};yB=vp([We("w3m-network-button")],yB);let tN=class extends _f{};tN=vp([We("appkit-network-button")],tN);const Yut=it` + :host { + --prev-height: 0px; + --new-height: 0px; + display: block; + } + + div.w3m-router-container { + transform: translateY(0); + opacity: 1; + } + + div.w3m-router-container[view-direction='prev'] { + animation: + slide-left-out 150ms forwards ease, + slide-left-in 150ms forwards ease; + animation-delay: 0ms, 200ms; + } + + div.w3m-router-container[view-direction='next'] { + animation: + slide-right-out 150ms forwards ease, + slide-right-in 150ms forwards ease; + animation-delay: 0ms, 200ms; + } + + @keyframes slide-left-out { + from { + transform: translateX(0px); + opacity: 1; + } + to { + transform: translateX(10px); + opacity: 0; + } + } + + @keyframes slide-left-in { + from { + transform: translateX(-10px); + opacity: 0; + } + to { + transform: translateX(0); + opacity: 1; + } + } + + @keyframes slide-right-out { + from { + transform: translateX(0px); + opacity: 1; + } + to { + transform: translateX(-10px); + opacity: 0; + } + } + + @keyframes slide-right-in { + from { + transform: translateX(10px); + opacity: 0; + } + to { + transform: translateX(0); + opacity: 1; + } + } +`;var xW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let t1=class extends He{constructor(){super(),this.resizeObserver=void 0,this.prevHeight="0px",this.prevHistoryLength=1,this.unsubscribe=[],this.view=ze.state.view,this.viewDirection="",this.unsubscribe.push(ze.subscribeKey("view",e=>this.onViewChange(e)))}firstUpdated(){this.resizeObserver=new ResizeObserver(([e])=>{const n=`${e?.contentRect.height}px`;this.prevHeight!=="0px"&&(this.style.setProperty("--prev-height",this.prevHeight),this.style.setProperty("--new-height",n),this.style.animation="w3m-view-height 150ms forwards ease",this.style.height="auto"),setTimeout(()=>{this.prevHeight=n,this.style.animation="unset"},Am.ANIMATION_DURATIONS.ModalHeight)}),this.resizeObserver?.observe(this.getWrapper())}disconnectedCallback(){this.resizeObserver?.unobserve(this.getWrapper()),this.unsubscribe.forEach(e=>e())}render(){return K`
+ ${this.viewTemplate()} +
`}viewTemplate(){switch(this.view){case"AccountSettings":return K``;case"Account":return K``;case"AllWallets":return K``;case"ApproveTransaction":return K``;case"BuyInProgress":return K``;case"ChooseAccountName":return K``;case"Connect":return K``;case"Create":return K``;case"ConnectingWalletConnect":return K``;case"ConnectingWalletConnectBasic":return K``;case"ConnectingExternal":return K``;case"ConnectingSiwe":return K``;case"ConnectWallets":return K``;case"ConnectSocials":return K``;case"ConnectingSocial":return K``;case"DataCapture":return K``;case"DataCaptureOtpConfirm":return K``;case"Downloads":return K``;case"EmailLogin":return K``;case"EmailVerifyOtp":return K``;case"EmailVerifyDevice":return K``;case"GetWallet":return K``;case"Networks":return K``;case"SwitchNetwork":return K``;case"ProfileWallets":return K``;case"Transactions":return K``;case"OnRampProviders":return K``;case"OnRampTokenSelect":return K``;case"OnRampFiatSelect":return K``;case"UpgradeEmailWallet":return K``;case"UpdateEmailWallet":return K``;case"UpdateEmailPrimaryOtp":return K``;case"UpdateEmailSecondaryOtp":return K``;case"UnsupportedChain":return K``;case"Swap":return K``;case"SwapSelectToken":return K``;case"SwapPreview":return K``;case"WalletSend":return K``;case"WalletSendSelectToken":return K``;case"WalletSendPreview":return K``;case"WhatIsABuy":return K``;case"WalletReceive":return K``;case"WalletCompatibleNetworks":return K``;case"WhatIsAWallet":return K``;case"ConnectingMultiChain":return K``;case"WhatIsANetwork":return K``;case"ConnectingFarcaster":return K``;case"SwitchActiveChain":return K``;case"RegisterAccountName":return K``;case"RegisterAccountNameSuccess":return K``;case"SmartSessionCreated":return K``;case"SmartSessionList":return K``;case"SIWXSignMessage":return K``;case"Pay":return K``;case"PayLoading":return K``;default:return K``}}onViewChange(e){Tc.hide();let n=Am.VIEW_DIRECTION.Next;const{history:r}=ze.state;r.length{this.view=e},Am.ANIMATION_DURATIONS.ViewTransition)}getWrapper(){return this.shadowRoot?.querySelector("div")}};t1.styles=Yut;xW([Ne()],t1.prototype,"view",void 0);xW([Ne()],t1.prototype,"viewDirection",void 0);t1=xW([We("w3m-router")],t1);const Xut=it` + button { + border-radius: var(--local-border-radius); + color: var(--wui-color-fg-100); + padding: var(--local-padding); + } + + @media (max-width: 700px) { + :host(:not([size='sm'])) button { + padding: var(--wui-spacing-s); + } + } + + button > wui-icon { + pointer-events: none; + } + + button:disabled > wui-icon { + color: var(--wui-color-bg-300) !important; + } + + button:disabled { + background-color: transparent; + } +`;var y3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Py=class extends He{constructor(){super(...arguments),this.size="md",this.disabled=!1,this.icon="copy",this.iconColor="inherit"}render(){this.dataset.size=this.size;let e="",n="";switch(this.size){case"lg":e="--wui-border-radius-xs",n="--wui-spacing-1xs";break;case"sm":e="--wui-border-radius-3xs",n="--wui-spacing-xxs";break;default:e="--wui-border-radius-xxs",n="--wui-spacing-2xs";break}return this.style.cssText=` + --local-border-radius: var(${e}); + --local-padding: var(${n}); + `,K` + + `}};Py.styles=[Ht,lr,mk,Xut];y3([ee()],Py.prototype,"size",void 0);y3([ee({type:Boolean})],Py.prototype,"disabled",void 0);y3([ee()],Py.prototype,"icon",void 0);y3([ee()],Py.prototype,"iconColor",void 0);Py=y3([We("wui-icon-link")],Py);const Qut=it` + button { + column-gap: var(--wui-spacing-s); + padding: 11px 18px 11px var(--wui-spacing-s); + width: 100%; + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + color: var(--wui-color-fg-250); + transition: + color var(--wui-ease-out-power-1) var(--wui-duration-md), + background-color var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: color, background-color; + } + + button[data-iconvariant='square'], + button[data-iconvariant='square-blue'] { + padding: 6px 18px 6px 9px; + } + + button > wui-flex { + flex: 1; + } + + button > wui-image { + width: 32px; + height: 32px; + box-shadow: 0 0 0 2px var(--wui-color-gray-glass-005); + border-radius: var(--wui-border-radius-3xl); + } + + button > wui-icon { + width: 36px; + height: 36px; + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + } + + button > wui-icon-box[data-variant='blue'] { + box-shadow: 0 0 0 2px var(--wui-color-accent-glass-005); + } + + button > wui-icon-box[data-variant='overlay'] { + box-shadow: 0 0 0 2px var(--wui-color-gray-glass-005); + } + + button > wui-icon-box[data-variant='square-blue'] { + border-radius: var(--wui-border-radius-3xs); + position: relative; + border: none; + width: 36px; + height: 36px; + } + + button > wui-icon-box[data-variant='square-blue']::after { + content: ''; + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + border-radius: inherit; + border: 1px solid var(--wui-color-accent-glass-010); + pointer-events: none; + } + + button > wui-icon:last-child { + width: 14px; + height: 14px; + } + + button:disabled { + color: var(--wui-color-gray-glass-020); + } + + button[data-loading='true'] > wui-icon { + opacity: 0; + } + + wui-loading-spinner { + position: absolute; + right: 18px; + top: 50%; + transform: translateY(-50%); + } +`;var pd=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Wc=class extends He{constructor(){super(...arguments),this.tabIdx=void 0,this.variant="icon",this.disabled=!1,this.imageSrc=void 0,this.alt=void 0,this.chevron=!1,this.loading=!1}render(){return K` + + `}visualTemplate(){if(this.variant==="image"&&this.imageSrc)return K``;if(this.iconVariant==="square"&&this.icon&&this.variant==="icon")return K``;if(this.variant==="icon"&&this.icon&&this.iconVariant){const e=["blue","square-blue"].includes(this.iconVariant)?"accent-100":"fg-200",n=this.iconVariant==="square-blue"?"mdl":"md",r=this.iconSize?this.iconSize:n;return K` + + `}return null}loadingTemplate(){return this.loading?K``:K``}chevronTemplate(){return this.chevron?K``:null}};Wc.styles=[Ht,lr,Qut];pd([ee()],Wc.prototype,"icon",void 0);pd([ee()],Wc.prototype,"iconSize",void 0);pd([ee()],Wc.prototype,"tabIdx",void 0);pd([ee()],Wc.prototype,"variant",void 0);pd([ee()],Wc.prototype,"iconVariant",void 0);pd([ee({type:Boolean})],Wc.prototype,"disabled",void 0);pd([ee()],Wc.prototype,"imageSrc",void 0);pd([ee()],Wc.prototype,"alt",void 0);pd([ee({type:Boolean})],Wc.prototype,"chevron",void 0);pd([ee({type:Boolean})],Wc.prototype,"loading",void 0);Wc=pd([We("wui-list-item")],Wc);const Jut=it` + :host { + width: var(--local-width); + position: relative; + } + + button { + border: none; + border-radius: var(--local-border-radius); + width: var(--local-width); + white-space: nowrap; + } + + /* -- Sizes --------------------------------------------------- */ + button[data-size='xs'] { + padding: var(--wui-spacing-3xs) var(--wui-spacing-s) var(--wui-spacing-3xs) var(--wui-spacing-s); + height: 24px; + } + + button[data-size='xs'][data-icon-left='true'][data-icon-right='false'] { + padding: var(--wui-spacing-3xs) var(--wui-spacing-s) var(--wui-spacing-3xs) var(--wui-spacing-s); + } + + button[data-size='xs'][data-icon-right='true'][data-icon-left='false'] { + padding: var(--wui-spacing-3xs) var(--wui-spacing-s) var(--wui-spacing-3xs) var(--wui-spacing-s); + } + + button[data-size='sm'] { + padding: 7.2px var(--wui-spacing-s) 7.2px var(--wui-spacing-s); + height: 32px; + } + + button[data-size='sm'][data-icon-left='true'][data-icon-right='false'] { + padding: 7.2px var(--wui-spacing-s) 7.2px var(--wui-spacing-s); + } + + button[data-size='sm'][data-icon-right='true'][data-icon-left='false'] { + padding: 7.2px var(--wui-spacing-s) 7.2px var(--wui-spacing-s); + } + + button[data-size='md'] { + padding: 8.2px var(--wui-spacing-l) 9px var(--wui-spacing-l); + height: 36px; + } + + button[data-size='md'][data-icon-left='true'][data-icon-right='false'] { + padding: 8.2px var(--wui-spacing-l) 9px var(--wui-spacing-s); + } + + button[data-size='md'][data-icon-right='true'][data-icon-left='false'] { + padding: 8.2px var(--wui-spacing-s) 9px var(--wui-spacing-l); + } + + button[data-size='lg'] { + padding: var(--wui-spacing-m) var(--wui-spacing-2l); + height: 48px; + } + + /* -- Variants --------------------------------------------------------- */ + button[data-variant='main'] { + background-color: var(--wui-color-accent-100); + color: var(--wui-color-inverse-100); + border: none; + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + } + + button[data-variant='inverse'] { + background-color: var(--wui-color-inverse-100); + color: var(--wui-color-inverse-000); + border: none; + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + } + + button[data-variant='accent'] { + background-color: var(--wui-color-accent-glass-010); + color: var(--wui-color-accent-100); + border: none; + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-005); + } + + button[data-variant='accent-error'] { + background: var(--wui-color-error-glass-015); + color: var(--wui-color-error-100); + border: none; + box-shadow: inset 0 0 0 1px var(--wui-color-error-glass-010); + } + + button[data-variant='accent-success'] { + background: var(--wui-color-success-glass-015); + color: var(--wui-color-success-100); + border: none; + box-shadow: inset 0 0 0 1px var(--wui-color-success-glass-010); + } + + button[data-variant='neutral'] { + background: transparent; + color: var(--wui-color-fg-100); + border: none; + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-005); + } + + /* -- Focus states --------------------------------------------------- */ + button[data-variant='main']:focus-visible:enabled { + background-color: var(--wui-color-accent-090); + box-shadow: + inset 0 0 0 1px var(--wui-color-accent-100), + 0 0 0 4px var(--wui-color-accent-glass-020); + } + button[data-variant='inverse']:focus-visible:enabled { + background-color: var(--wui-color-inverse-100); + box-shadow: + inset 0 0 0 1px var(--wui-color-gray-glass-010), + 0 0 0 4px var(--wui-color-accent-glass-020); + } + button[data-variant='accent']:focus-visible:enabled { + background-color: var(--wui-color-accent-glass-010); + box-shadow: + inset 0 0 0 1px var(--wui-color-accent-100), + 0 0 0 4px var(--wui-color-accent-glass-020); + } + button[data-variant='accent-error']:focus-visible:enabled { + background: var(--wui-color-error-glass-015); + box-shadow: + inset 0 0 0 1px var(--wui-color-error-100), + 0 0 0 4px var(--wui-color-error-glass-020); + } + button[data-variant='accent-success']:focus-visible:enabled { + background: var(--wui-color-success-glass-015); + box-shadow: + inset 0 0 0 1px var(--wui-color-success-100), + 0 0 0 4px var(--wui-color-success-glass-020); + } + button[data-variant='neutral']:focus-visible:enabled { + background: var(--wui-color-gray-glass-005); + box-shadow: + inset 0 0 0 1px var(--wui-color-gray-glass-010), + 0 0 0 4px var(--wui-color-gray-glass-002); + } + + /* -- Hover & Active states ----------------------------------------------------------- */ + @media (hover: hover) and (pointer: fine) { + button[data-variant='main']:hover:enabled { + background-color: var(--wui-color-accent-090); + } + + button[data-variant='main']:active:enabled { + background-color: var(--wui-color-accent-080); + } + + button[data-variant='accent']:hover:enabled { + background-color: var(--wui-color-accent-glass-015); + } + + button[data-variant='accent']:active:enabled { + background-color: var(--wui-color-accent-glass-020); + } + + button[data-variant='accent-error']:hover:enabled { + background: var(--wui-color-error-glass-020); + color: var(--wui-color-error-100); + } + + button[data-variant='accent-error']:active:enabled { + background: var(--wui-color-error-glass-030); + color: var(--wui-color-error-100); + } + + button[data-variant='accent-success']:hover:enabled { + background: var(--wui-color-success-glass-020); + color: var(--wui-color-success-100); + } + + button[data-variant='accent-success']:active:enabled { + background: var(--wui-color-success-glass-030); + color: var(--wui-color-success-100); + } + + button[data-variant='neutral']:hover:enabled { + background: var(--wui-color-gray-glass-002); + } + + button[data-variant='neutral']:active:enabled { + background: var(--wui-color-gray-glass-005); + } + + button[data-size='lg'][data-icon-left='true'][data-icon-right='false'] { + padding-left: var(--wui-spacing-m); + } + + button[data-size='lg'][data-icon-right='true'][data-icon-left='false'] { + padding-right: var(--wui-spacing-m); + } + } + + /* -- Disabled state --------------------------------------------------- */ + button:disabled { + background-color: var(--wui-color-gray-glass-002); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-002); + color: var(--wui-color-gray-glass-020); + cursor: not-allowed; + } + + button > wui-text { + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + opacity: var(--local-opacity-100); + } + + ::slotted(*) { + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + opacity: var(--local-opacity-100); + } + + wui-loading-spinner { + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + opacity: var(--local-opacity-000); + } +`;var Sf=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const fte={main:"inverse-100",inverse:"inverse-000",accent:"accent-100","accent-error":"error-100","accent-success":"success-100",neutral:"fg-100",disabled:"gray-glass-020"},edt={lg:"paragraph-600",md:"small-600",sm:"small-600",xs:"tiny-600"},tdt={lg:"md",md:"md",sm:"sm",xs:"sm"};let Hl=class extends He{constructor(){super(...arguments),this.size="lg",this.disabled=!1,this.fullWidth=!1,this.loading=!1,this.variant="main",this.hasIconLeft=!1,this.hasIconRight=!1,this.borderRadius="m"}render(){this.style.cssText=` + --local-width: ${this.fullWidth?"100%":"auto"}; + --local-opacity-100: ${this.loading?0:1}; + --local-opacity-000: ${this.loading?1:0}; + --local-border-radius: var(--wui-border-radius-${this.borderRadius}); + `;const e=this.textVariant??edt[this.size];return K` + + `}handleSlotLeftChange(){this.hasIconLeft=!0}handleSlotRightChange(){this.hasIconRight=!0}loadingTemplate(){if(this.loading){const e=tdt[this.size],n=this.disabled?fte.disabled:fte[this.variant];return K``}return K``}};Hl.styles=[Ht,lr,Jut];Sf([ee()],Hl.prototype,"size",void 0);Sf([ee({type:Boolean})],Hl.prototype,"disabled",void 0);Sf([ee({type:Boolean})],Hl.prototype,"fullWidth",void 0);Sf([ee({type:Boolean})],Hl.prototype,"loading",void 0);Sf([ee()],Hl.prototype,"variant",void 0);Sf([ee({type:Boolean})],Hl.prototype,"hasIconLeft",void 0);Sf([ee({type:Boolean})],Hl.prototype,"hasIconRight",void 0);Sf([ee()],Hl.prototype,"borderRadius",void 0);Sf([ee()],Hl.prototype,"textVariant",void 0);Hl=Sf([We("wui-button")],Hl);const ndt=it` + :host { + display: block; + } + + button { + width: 100%; + display: block; + padding-top: var(--wui-spacing-l); + padding-bottom: var(--wui-spacing-l); + padding-left: var(--wui-spacing-s); + padding-right: var(--wui-spacing-2l); + border-radius: var(--wui-border-radius-s); + background-color: var(--wui-color-accent-glass-010); + } + + button:hover { + background-color: var(--wui-color-accent-glass-015) !important; + } + + button:active { + background-color: var(--wui-color-accent-glass-020) !important; + } +`;var Nk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let n1=class extends He{constructor(){super(...arguments),this.label="",this.description="",this.icon="wallet"}render(){return K` + + `}};n1.styles=[Ht,lr,ndt];Nk([ee()],n1.prototype,"label",void 0);Nk([ee()],n1.prototype,"description",void 0);Nk([ee()],n1.prototype,"icon",void 0);n1=Nk([We("wui-notice-card")],n1);var p0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let wB=class extends He{constructor(){super(),this.unsubscribe=[],this.socialProvider=Ge.getConnectedSocialProvider(),this.socialUsername=Ge.getConnectedSocialUsername(),this.namespace=G.state.activeChain,this.unsubscribe.push(G.subscribeKey("activeChain",e=>{this.namespace=e}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const e=ke.getConnectorId(this.namespace),n=ke.getAuthConnector();if(!n||e!==ye.CONNECTOR_ID.AUTH)return this.style.cssText="display: none",null;const r=n.provider.getEmail()??"";return!r&&!this.socialUsername?(this.style.cssText="display: none",null):K` + {this.onGoToUpdateEmail(r,this.socialProvider)}} + > + ${this.getAuthName(r)} + + `}onGoToUpdateEmail(e,n){n||ze.push("UpdateEmailWallet",{email:e,redirectView:"Account"})}getAuthName(e){return this.socialUsername?this.socialProvider==="discord"&&this.socialUsername.endsWith("0")?this.socialUsername.slice(0,-1):this.socialUsername:e.length>30?`${e.slice(0,-3)}...`:e}};p0e([Ne()],wB.prototype,"namespace",void 0);wB=p0e([We("w3m-account-auth-button")],wB);var Af=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let ql=class extends He{constructor(){super(),this.usubscribe=[],this.networkImages=mi.state.networkImages,this.address=nt.state.address,this.profileImage=nt.state.profileImage,this.profileName=nt.state.profileName,this.network=G.state.activeCaipNetwork,this.disconnecting=!1,this.loading=!1,this.switched=!1,this.text="",this.remoteFeatures=_e.state.remoteFeatures,this.usubscribe.push(nt.subscribe(e=>{e.address&&(this.address=e.address,this.profileImage=e.profileImage,this.profileName=e.profileName)}),G.subscribeKey("activeCaipNetwork",e=>{e?.id&&(this.network=e)}),_e.subscribeKey("remoteFeatures",e=>{this.remoteFeatures=e}))}disconnectedCallback(){this.usubscribe.forEach(e=>e())}render(){if(!this.address)throw new Error("w3m-account-settings-view: No account provided");const e=this.networkImages[this.network?.assets?.imageId??""];return K` + + + + + + ${qr.getTruncateString({string:this.address,charsStart:4,charsEnd:6,truncate:"middle"})} + + + + + + + + ${this.authCardTemplate()} + + + + ${this.network?.name??"Unknown"} + + + ${this.togglePreferredAccountBtnTemplate()} ${this.chooseNameButtonTemplate()} + + Disconnect + + + + `}chooseNameButtonTemplate(){const e=this.network?.chainNamespace,n=ke.getConnectorId(e),r=ke.getAuthConnector();return!G.checkIfNamesSupported()||!r||n!==ye.CONNECTOR_ID.AUTH||this.profileName?null:K` + + Choose account name + + `}authCardTemplate(){const e=ke.getConnectorId(this.network?.chainNamespace),n=ke.getAuthConnector(),{origin:r}=location;return!n||e!==ye.CONNECTOR_ID.AUTH||r.includes(wn.SECURE_SITE)?null:K` + + `}isAllowedNetworkSwitch(){const e=G.getAllRequestedCaipNetworks(),n=e?e.length>1:!1,r=e?.find(({id:s})=>s===this.network?.id);return n||!r}onCopyAddress(){try{this.address&&(De.copyToClopboard(this.address),Wn.showSuccess("Address copied"))}catch{Wn.showError("Failed to copy")}}togglePreferredAccountBtnTemplate(){const e=this.network?.chainNamespace,n=G.checkIfSmartAccountEnabled(),r=ke.getConnectorId(e);return!ke.getAuthConnector()||r!==ye.CONNECTOR_ID.AUTH||!n?null:(this.switched||(this.text=Ss(e)===_r.ACCOUNT_TYPES.SMART_ACCOUNT?"Switch to your EOA":"Switch to your Smart Account"),K` + + ${this.text} + + `)}onChooseName(){ze.push("ChooseAccountName")}async changePreferredAccountType(){const e=this.network?.chainNamespace,n=G.checkIfSmartAccountEnabled(),r=Ss(e)===_r.ACCOUNT_TYPES.SMART_ACCOUNT||!n?_r.ACCOUNT_TYPES.EOA:_r.ACCOUNT_TYPES.SMART_ACCOUNT;ke.getAuthConnector()&&(this.loading=!0,await Ue.setPreferredAccountType(r,e),this.text=r===_r.ACCOUNT_TYPES.SMART_ACCOUNT?"Switch to your EOA":"Switch to your Smart Account",this.switched=!0,gr.resetSend(),this.loading=!1,this.requestUpdate())}onNetworks(){this.isAllowedNetworkSwitch()&&ze.push("Networks")}async onDisconnect(){try{this.disconnecting=!0;const e=this.network?.chainNamespace,r=Ue.getConnections(e).length>0,s=e&&ke.state.activeConnectorIds[e],i=this.remoteFeatures?.multiWallet;await Ue.disconnect(i?{id:s,namespace:e}:{}),r&&i&&(ze.push("ProfileWallets"),Wn.showSuccess("Wallet deleted"))}catch{Lt.sendEvent({type:"track",event:"DISCONNECT_ERROR"}),Wn.showError("Failed to disconnect")}finally{this.disconnecting=!1}}onGoToUpgradeView(){Lt.sendEvent({type:"track",event:"EMAIL_UPGRADE_FROM_MODAL"}),ze.push("UpgradeEmailWallet")}};Af([Ne()],ql.prototype,"address",void 0);Af([Ne()],ql.prototype,"profileImage",void 0);Af([Ne()],ql.prototype,"profileName",void 0);Af([Ne()],ql.prototype,"network",void 0);Af([Ne()],ql.prototype,"disconnecting",void 0);Af([Ne()],ql.prototype,"loading",void 0);Af([Ne()],ql.prototype,"switched",void 0);Af([Ne()],ql.prototype,"text",void 0);Af([Ne()],ql.prototype,"remoteFeatures",void 0);ql=Af([We("w3m-account-settings-view")],ql);const rdt=it` + :host { + display: inline-flex; + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-3xl); + padding: var(--wui-spacing-3xs); + position: relative; + height: 36px; + min-height: 36px; + overflow: hidden; + } + + :host::before { + content: ''; + position: absolute; + pointer-events: none; + top: 4px; + left: 4px; + display: block; + width: var(--local-tab-width); + height: 28px; + border-radius: var(--wui-border-radius-3xl); + background-color: var(--wui-color-gray-glass-002); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-002); + transform: translateX(calc(var(--local-tab) * var(--local-tab-width))); + transition: transform var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: background-color, opacity; + } + + :host([data-type='flex'])::before { + left: 3px; + transform: translateX(calc((var(--local-tab) * 34px) + (var(--local-tab) * 4px))); + } + + :host([data-type='flex']) { + display: flex; + padding: 0px 0px 0px 12px; + gap: 4px; + } + + :host([data-type='flex']) > button > wui-text { + position: absolute; + left: 18px; + opacity: 0; + } + + button[data-active='true'] > wui-icon, + button[data-active='true'] > wui-text { + color: var(--wui-color-fg-100); + } + + button[data-active='false'] > wui-icon, + button[data-active='false'] > wui-text { + color: var(--wui-color-fg-200); + } + + button[data-active='true']:disabled, + button[data-active='false']:disabled { + background-color: transparent; + opacity: 0.5; + cursor: not-allowed; + } + + button[data-active='true']:disabled > wui-text { + color: var(--wui-color-fg-200); + } + + button[data-active='false']:disabled > wui-text { + color: var(--wui-color-fg-300); + } + + button > wui-icon, + button > wui-text { + pointer-events: none; + transition: color var(--wui-e ase-out-power-1) var(--wui-duration-md); + will-change: color; + } + + button { + width: var(--local-tab-width); + transition: background-color var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: background-color; + } + + :host([data-type='flex']) > button { + width: 34px; + position: relative; + display: flex; + justify-content: flex-start; + } + + button:hover:enabled, + button:active:enabled { + background-color: transparent !important; + } + + button:hover:enabled > wui-icon, + button:active:enabled > wui-icon { + transition: all var(--wui-ease-out-power-1) var(--wui-duration-lg); + color: var(--wui-color-fg-125); + } + + button:hover:enabled > wui-text, + button:active:enabled > wui-text { + transition: all var(--wui-ease-out-power-1) var(--wui-duration-lg); + color: var(--wui-color-fg-125); + } + + button { + border-radius: var(--wui-border-radius-3xl); + } +`;var $0=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let gf=class extends He{constructor(){super(...arguments),this.tabs=[],this.onTabChange=()=>null,this.buttons=[],this.disabled=!1,this.localTabWidth="100px",this.activeTab=0,this.isDense=!1}render(){return this.isDense=this.tabs.length>3,this.style.cssText=` + --local-tab: ${this.activeTab}; + --local-tab-width: ${this.localTabWidth}; + `,this.dataset.type=this.isDense?"flex":"block",this.tabs.map((e,n)=>{const r=n===this.activeTab;return K` + + `})}firstUpdated(){this.shadowRoot&&this.isDense&&(this.buttons=[...this.shadowRoot.querySelectorAll("button")],setTimeout(()=>{this.animateTabs(0,!0)},0))}iconTemplate(e){return e.icon?K``:null}onTabClick(e){this.buttons&&this.animateTabs(e,!1),this.activeTab=e,this.onTabChange(e)}animateTabs(e,n){const r=this.buttons[this.activeTab],s=this.buttons[e],i=r?.querySelector("wui-text"),o=s?.querySelector("wui-text"),a=s?.getBoundingClientRect(),c=o?.getBoundingClientRect();r&&i&&!n&&e!==this.activeTab&&(i.animate([{opacity:0}],{duration:50,easing:"ease",fill:"forwards"}),r.animate([{width:"34px"}],{duration:500,easing:"ease",fill:"forwards"})),s&&a&&c&&o&&(e!==this.activeTab||n)&&(this.localTabWidth=`${Math.round(a.width+c.width)+6}px`,s.animate([{width:`${a.width+c.width}px`}],{duration:n?0:500,fill:"forwards",easing:"ease"}),o.animate([{opacity:1}],{duration:n?0:125,delay:n?0:200,fill:"forwards",easing:"ease"}))}};gf.styles=[Ht,lr,rdt];$0([ee({type:Array})],gf.prototype,"tabs",void 0);$0([ee()],gf.prototype,"onTabChange",void 0);$0([ee({type:Array})],gf.prototype,"buttons",void 0);$0([ee({type:Boolean})],gf.prototype,"disabled",void 0);$0([ee()],gf.prototype,"localTabWidth",void 0);$0([Ne()],gf.prototype,"activeTab",void 0);$0([Ne()],gf.prototype,"isDense",void 0);gf=$0([We("wui-tabs")],gf);const sdt=it` + :host { + display: flex; + justify-content: center; + align-items: center; + height: var(--wui-spacing-m); + padding: 0 var(--wui-spacing-3xs) !important; + border-radius: var(--wui-border-radius-5xs); + transition: + border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1), + background-color var(--wui-duration-lg) var(--wui-ease-out-power-1); + will-change: border-radius, background-color; + } + + :host > wui-text { + transform: translateY(5%); + } + + :host([data-variant='main']) { + background-color: var(--wui-color-accent-glass-015); + color: var(--wui-color-accent-100); + } + + :host([data-variant='shade']) { + background-color: var(--wui-color-gray-glass-010); + color: var(--wui-color-fg-200); + } + + :host([data-variant='success']) { + background-color: var(--wui-icon-box-bg-success-100); + color: var(--wui-color-success-100); + } + + :host([data-variant='error']) { + background-color: var(--wui-icon-box-bg-error-100); + color: var(--wui-color-error-100); + } + + :host([data-size='lg']) { + padding: 11px 5px !important; + } + + :host([data-size='lg']) > wui-text { + transform: translateY(2%); + } + + :host([data-size='xs']) { + height: var(--wui-spacing-2l); + padding: 0 var(--wui-spacing-3xs) !important; + } + + :host([data-size='xs']) > wui-text { + transform: translateY(2%); + } +`;var EW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let v_=class extends He{constructor(){super(...arguments),this.variant="main",this.size="lg"}render(){this.dataset.variant=this.variant,this.dataset.size=this.size;const e=this.size==="md"||this.size==="xs"?"mini-700":"micro-700";return K` + + + + `}};v_.styles=[Ht,sdt];EW([ee()],v_.prototype,"variant",void 0);EW([ee()],v_.prototype,"size",void 0);v_=EW([We("wui-tag")],v_);const idt=it` + button { + display: flex; + align-items: center; + padding: var(--wui-spacing-xxs); + border-radius: var(--wui-border-radius-xxs); + column-gap: var(--wui-spacing-xs); + } + + wui-image, + .icon-box { + width: var(--wui-spacing-xxl); + height: var(--wui-spacing-xxl); + border-radius: var(--wui-border-radius-3xs); + } + + wui-text { + flex: 1; + } + + .icon-box { + position: relative; + } + + .icon-box[data-active='true'] { + background-color: var(--wui-color-gray-glass-005); + } + + .circle { + position: absolute; + left: 16px; + top: 15px; + width: var(--wui-spacing-1xs); + height: var(--wui-spacing-1xs); + background-color: var(--wui-color-success-100); + border: 2px solid var(--wui-color-modal-bg); + border-radius: 50%; + } +`;var If=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Kl=class extends He{constructor(){super(...arguments),this.address="",this.profileName="",this.alt="",this.imageSrc="",this.icon=void 0,this.iconSize="md",this.loading=!1,this.charsStart=4,this.charsEnd=6}render(){return K` + + `}leftImageTemplate(){const e=this.icon?K``:K``;return K` + + ${e} + + + `}textTemplate(){return K` + + ${qr.getTruncateString({string:this.profileName||this.address,charsStart:this.profileName?16:this.charsStart,charsEnd:this.profileName?0:this.charsEnd,truncate:this.profileName?"end":"middle"})} + + `}rightImageTemplate(){return K``}};Kl.styles=[Ht,lr,idt];If([ee()],Kl.prototype,"address",void 0);If([ee()],Kl.prototype,"profileName",void 0);If([ee()],Kl.prototype,"alt",void 0);If([ee()],Kl.prototype,"imageSrc",void 0);If([ee()],Kl.prototype,"icon",void 0);If([ee()],Kl.prototype,"iconSize",void 0);If([ee({type:Boolean})],Kl.prototype,"loading",void 0);If([ee({type:Number})],Kl.prototype,"charsStart",void 0);If([ee({type:Number})],Kl.prototype,"charsEnd",void 0);Kl=If([We("wui-wallet-switch")],Kl);const odt=it` + wui-flex { + width: 100%; + } + + :host > wui-flex:first-child { + transform: translateY(calc(var(--wui-spacing-xxs) * -1)); + } + + wui-icon-link { + margin-right: calc(var(--wui-icon-box-size-md) * -1); + } + + wui-notice-card { + margin-bottom: var(--wui-spacing-3xs); + } + + wui-list-item > wui-text { + flex: 1; + } + + w3m-transactions-view { + max-height: 200px; + } + + .tab-content-container { + height: 300px; + overflow-y: auto; + overflow-x: hidden; + scrollbar-width: none; + } + + .tab-content-container::-webkit-scrollbar { + display: none; + } + + .account-button { + width: auto; + border: none; + display: flex; + align-items: center; + justify-content: center; + gap: var(--wui-spacing-s); + height: 48px; + padding: var(--wui-spacing-xs); + padding-right: var(--wui-spacing-s); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-002); + background-color: var(--wui-color-gray-glass-002); + border-radius: 24px; + transition: background-color 0.2s linear; + } + + .account-button:hover { + background-color: var(--wui-color-gray-glass-005); + } + + .avatar-container { + position: relative; + } + + wui-avatar.avatar { + width: 32px; + height: 32px; + box-shadow: 0 0 0 2px var(--wui-color-gray-glass-005); + } + + wui-wallet-switch { + margin-top: var(--wui-spacing-xs); + } + + wui-avatar.network-avatar { + width: 16px; + height: 16px; + position: absolute; + left: 100%; + top: 100%; + transform: translate(-75%, -75%); + box-shadow: 0 0 0 2px var(--wui-color-gray-glass-005); + } + + .account-links { + display: flex; + justify-content: space-between; + align-items: center; + } + + .account-links wui-flex { + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + flex: 1; + background: red; + align-items: center; + justify-content: center; + height: 48px; + padding: 10px; + flex: 1 0 0; + border-radius: var(--XS, 16px); + border: 1px solid var(--dark-accent-glass-010, rgba(71, 161, 255, 0.1)); + background: var(--dark-accent-glass-010, rgba(71, 161, 255, 0.1)); + transition: + background-color var(--wui-ease-out-power-1) var(--wui-duration-md), + opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: background-color, opacity; + } + + .account-links wui-flex:hover { + background: var(--dark-accent-glass-015, rgba(71, 161, 255, 0.15)); + } + + .account-links wui-flex wui-icon { + width: var(--S, 20px); + height: var(--S, 20px); + } + + .account-links wui-flex wui-icon svg path { + stroke: #667dff; + } +`;var nu=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Ja=class extends He{constructor(){super(),this.unsubscribe=[],this.caipAddress=nt.state.caipAddress,this.address=De.getPlainAddress(nt.state.caipAddress),this.profileImage=nt.state.profileImage,this.profileName=nt.state.profileName,this.disconnecting=!1,this.balance=nt.state.balance,this.balanceSymbol=nt.state.balanceSymbol,this.features=_e.state.features,this.remoteFeatures=_e.state.remoteFeatures,this.namespace=G.state.activeChain,this.activeConnectorIds=ke.state.activeConnectorIds,this.unsubscribe.push(nt.subscribeKey("caipAddress",e=>{this.address=De.getPlainAddress(e),this.caipAddress=e}),nt.subscribeKey("balance",e=>this.balance=e),nt.subscribeKey("balanceSymbol",e=>this.balanceSymbol=e),nt.subscribeKey("profileName",e=>this.profileName=e),nt.subscribeKey("profileImage",e=>this.profileImage=e),_e.subscribeKey("features",e=>this.features=e),_e.subscribeKey("remoteFeatures",e=>this.remoteFeatures=e),ke.subscribeKey("activeConnectorIds",e=>{this.activeConnectorIds=e}),G.subscribeKey("activeChain",e=>this.namespace=e),G.subscribeKey("activeCaipNetwork",e=>{e?.chainNamespace&&(this.namespace=e?.chainNamespace)}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){if(!this.caipAddress||!this.namespace)return null;const e=this.activeConnectorIds[this.namespace],n=e?ke.getConnectorById(e):void 0,r=nr.getConnectorImage(n);return K` + + + + + ${De.formatBalance(this.balance,this.balanceSymbol)} + + + ${this.explorerBtnTemplate()} + + + + ${this.authCardTemplate()} + ${this.orderedFeaturesTemplate()} ${this.activityTemplate()} + + Disconnect + + `}onrampTemplate(){if(!this.namespace)return null;const e=this.remoteFeatures?.onramp,n=wn.ONRAMP_SUPPORTED_CHAIN_NAMESPACES.includes(this.namespace);return!e||!n?null:K` + + Buy crypto + + `}orderedFeaturesTemplate(){return(this.features?.walletFeaturesOrder||wn.DEFAULT_FEATURES.walletFeaturesOrder).map(n=>{switch(n){case"onramp":return this.onrampTemplate();case"swaps":return this.swapsTemplate();case"send":return this.sendTemplate();default:return null}})}activityTemplate(){return this.namespace&&this.remoteFeatures?.activity&&wn.ACTIVITY_ENABLED_CHAIN_NAMESPACES.includes(this.namespace)?K` + Activity + `:null}swapsTemplate(){const e=this.remoteFeatures?.swaps,n=G.state.activeChain===ye.CHAIN.EVM;return!e||!n?null:K` + + Swap + + `}sendTemplate(){const e=this.features?.send,n=G.state.activeChain;if(!n)throw new Error("SendController:sendTemplate - namespace is required");const r=wn.SEND_SUPPORTED_NAMESPACES.includes(n);return!e||!r?null:K` + + Send + + `}authCardTemplate(){const e=G.state.activeChain;if(!e)throw new Error("AuthCardTemplate:authCardTemplate - namespace is required");const n=ke.getConnectorId(e),r=ke.getAuthConnector(),{origin:s}=location;return!r||n!==ye.CONNECTOR_ID.AUTH||s.includes(wn.SECURE_SITE)?null:K` + + `}handleClickPay(){ze.push("OnRampProviders")}handleClickSwap(){ze.push("Swap")}handleClickSend(){ze.push("WalletSend")}explorerBtnTemplate(){return nt.state.addressExplorerUrl?K` + + + Block Explorer + + + `:null}onTransactions(){Lt.sendEvent({type:"track",event:"CLICK_TRANSACTIONS",properties:{isSmartAccount:Ss(G.state.activeChain)===_r.ACCOUNT_TYPES.SMART_ACCOUNT}}),ze.push("Transactions")}async onDisconnect(){try{this.disconnecting=!0;const n=Ue.getConnections(this.namespace).length>0,r=this.namespace&&ke.state.activeConnectorIds[this.namespace],s=this.remoteFeatures?.multiWallet;await Ue.disconnect(s?{id:r,namespace:this.namespace}:{}),n&&s&&(ze.push("ProfileWallets"),Wn.showSuccess("Wallet deleted"))}catch{Lt.sendEvent({type:"track",event:"DISCONNECT_ERROR"}),Wn.showError("Failed to disconnect")}finally{this.disconnecting=!1}}onExplorer(){const e=nt.state.addressExplorerUrl;e&&De.openHref(e,"_blank")}onGoToUpgradeView(){Lt.sendEvent({type:"track",event:"EMAIL_UPGRADE_FROM_MODAL"}),ze.push("UpgradeEmailWallet")}onGoToProfileWalletsView(){ze.push("ProfileWallets")}};Ja.styles=odt;nu([Ne()],Ja.prototype,"caipAddress",void 0);nu([Ne()],Ja.prototype,"address",void 0);nu([Ne()],Ja.prototype,"profileImage",void 0);nu([Ne()],Ja.prototype,"profileName",void 0);nu([Ne()],Ja.prototype,"disconnecting",void 0);nu([Ne()],Ja.prototype,"balance",void 0);nu([Ne()],Ja.prototype,"balanceSymbol",void 0);nu([Ne()],Ja.prototype,"features",void 0);nu([Ne()],Ja.prototype,"remoteFeatures",void 0);nu([Ne()],Ja.prototype,"namespace",void 0);nu([Ne()],Ja.prototype,"activeConnectorIds",void 0);Ja=nu([We("w3m-account-default-widget")],Ja);const adt=it` + span { + font-weight: 500; + font-size: 40px; + color: var(--wui-color-fg-100); + line-height: 130%; /* 52px */ + letter-spacing: -1.6px; + text-align: center; + } + + .pennies { + color: var(--wui-color-fg-200); + } +`;var CW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let x_=class extends He{constructor(){super(...arguments),this.dollars="0",this.pennies="00"}render(){return K`$${this.dollars}.${this.pennies}`}};x_.styles=[Ht,adt];CW([ee()],x_.prototype,"dollars",void 0);CW([ee()],x_.prototype,"pennies",void 0);x_=CW([We("wui-balance")],x_);const cdt=it` + :host { + position: relative; + } + + button { + display: flex; + justify-content: center; + align-items: center; + height: 48px; + width: 100%; + background-color: var(--wui-color-accent-glass-010); + border-radius: var(--wui-border-radius-xs); + border: 1px solid var(--wui-color-accent-glass-010); + transition: background-color var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: background-color; + } + + wui-tooltip { + padding: 7px var(--wui-spacing-s) 8px var(--wui-spacing-s); + position: absolute; + top: -8px; + left: 50%; + transform: translate(-50%, -100%); + opacity: 0; + display: none; + } + + @media (hover: hover) and (pointer: fine) { + button:hover:enabled { + background-color: var(--wui-color-accent-glass-015); + } + + button:active:enabled { + background-color: var(--wui-color-accent-glass-020); + } + } +`;var _W=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let E_=class extends He{constructor(){super(...arguments),this.text="",this.icon="card"}render(){return K``}};E_.styles=[Ht,lr,cdt];_W([ee()],E_.prototype,"text",void 0);_W([ee()],E_.prototype,"icon",void 0);E_=_W([We("wui-icon-button")],E_);const ldt=it` + :host { + display: block; + padding: 9px var(--wui-spacing-s) 10px var(--wui-spacing-s); + border-radius: var(--wui-border-radius-xxs); + + color: var(--wui-color-bg-100); + position: relative; + } + + :host([data-variant='shade']) { + background-color: var(--wui-color-bg-150); + border: 1px solid var(--wui-color-gray-glass-005); + } + + :host([data-variant='shade']) > wui-text { + color: var(--wui-color-fg-150); + } + + :host([data-variant='fill']) { + background-color: var(--wui-color-fg-100); + border: none; + } + + wui-icon { + position: absolute; + width: 12px !important; + height: 4px !important; + } + + wui-icon[data-placement='top'] { + bottom: 0px; + left: 50%; + transform: translate(-50%, 95%); + } + + wui-icon[data-placement='bottom'] { + top: 0; + left: 50%; + transform: translate(-50%, -95%) rotate(180deg); + } + + wui-icon[data-placement='right'] { + top: 50%; + left: 0; + transform: translate(-65%, -50%) rotate(90deg); + } + + wui-icon[data-placement='left'] { + top: 50%; + right: 0%; + transform: translate(65%, -50%) rotate(270deg); + } +`;var Pk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let r1=class extends He{constructor(){super(...arguments),this.placement="top",this.variant="fill",this.message=""}render(){return this.dataset.variant=this.variant,K` + ${this.message}`}};r1.styles=[Ht,lr,ldt];Pk([ee()],r1.prototype,"placement",void 0);Pk([ee()],r1.prototype,"variant",void 0);Pk([ee()],r1.prototype,"message",void 0);r1=Pk([We("wui-tooltip")],r1);const udt={getTabsByNamespace(t){return!!t&&t===ye.CHAIN.EVM?_e.state.remoteFeatures?.activity===!1?Am.ACCOUNT_TABS.filter(n=>n.label!=="Activity"):Am.ACCOUNT_TABS:[]}},ddt=it` + button { + padding: var(--wui-spacing-4xs) var(--wui-spacing-xxs); + border-radius: var(--wui-border-radius-3xs); + background-color: transparent; + color: var(--wui-color-accent-100); + } + + button:disabled { + background-color: transparent; + color: var(--wui-color-gray-glass-015); + } + + button:hover { + background-color: var(--wui-color-gray-glass-005); + } +`;var kk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let s1=class extends He{constructor(){super(...arguments),this.tabIdx=void 0,this.disabled=!1,this.color="inherit"}render(){return K` + + `}};s1.styles=[Ht,lr,ddt];kk([ee()],s1.prototype,"tabIdx",void 0);kk([ee({type:Boolean})],s1.prototype,"disabled",void 0);kk([ee()],s1.prototype,"color",void 0);s1=kk([We("wui-link")],s1);var bB;(function(t){t.approve="approved",t.bought="bought",t.borrow="borrowed",t.burn="burnt",t.cancel="canceled",t.claim="claimed",t.deploy="deployed",t.deposit="deposited",t.execute="executed",t.mint="minted",t.receive="received",t.repay="repaid",t.send="sent",t.sell="sold",t.stake="staked",t.trade="swapped",t.unstake="unstaked",t.withdraw="withdrawn"})(bB||(bB={}));const fdt=it` + :host > wui-flex { + display: flex; + justify-content: center; + align-items: center; + position: relative; + width: 40px; + height: 40px; + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-005); + background-color: var(--wui-color-gray-glass-005); + } + + :host > wui-flex wui-image { + display: block; + } + + :host > wui-flex, + :host > wui-flex wui-image, + .swap-images-container, + .swap-images-container.nft, + wui-image.nft { + border-top-left-radius: var(--local-left-border-radius); + border-top-right-radius: var(--local-right-border-radius); + border-bottom-left-radius: var(--local-left-border-radius); + border-bottom-right-radius: var(--local-right-border-radius); + } + + wui-icon { + width: 20px; + height: 20px; + } + + wui-icon-box { + position: absolute; + right: 0; + bottom: 0; + transform: translate(20%, 20%); + } + + .swap-images-container { + position: relative; + width: 40px; + height: 40px; + overflow: hidden; + } + + .swap-images-container wui-image:first-child { + position: absolute; + width: 40px; + height: 40px; + top: 0; + left: 0%; + clip-path: inset(0px calc(50% + 2px) 0px 0%); + } + + .swap-images-container wui-image:last-child { + clip-path: inset(0px 0px 0px calc(50% + 2px)); + } +`;var fw=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let tp=class extends He{constructor(){super(...arguments),this.images=[],this.secondImage={type:void 0,url:""}}render(){const[e,n]=this.images,r=e?.type==="NFT",s=n?.url?n.type==="NFT":r,i=r?"var(--wui-border-radius-xxs)":"var(--wui-border-radius-s)",o=s?"var(--wui-border-radius-xxs)":"var(--wui-border-radius-s)";return this.style.cssText=` + --local-left-border-radius: ${i}; + --local-right-border-radius: ${o}; + `,K` ${this.templateVisual()} ${this.templateIcon()} `}templateVisual(){const[e,n]=this.images,r=e?.type;return this.images.length===2&&(e?.url||n?.url)?K`
+ ${e?.url?K``:null} + ${n?.url?K``:null} +
`:e?.url?K``:r==="NFT"?K``:K``}templateIcon(){let e="accent-100",n;return n=this.getIcon(),this.status&&(e=this.getStatusColor()),n?K` + + `:null}getDirectionIcon(){switch(this.direction){case"in":return"arrowBottom";case"out":return"arrowTop";default:return}}getIcon(){return this.onlyDirectionIcon?this.getDirectionIcon():this.type==="trade"?"swapHorizontalBold":this.type==="approve"?"checkmark":this.type==="cancel"?"close":this.getDirectionIcon()}getStatusColor(){switch(this.status){case"confirmed":return"success-100";case"failed":return"error-100";case"pending":return"inverse-100";default:return"accent-100"}}};tp.styles=[fdt];fw([ee()],tp.prototype,"type",void 0);fw([ee()],tp.prototype,"status",void 0);fw([ee()],tp.prototype,"direction",void 0);fw([ee({type:Boolean})],tp.prototype,"onlyDirectionIcon",void 0);fw([ee({type:Array})],tp.prototype,"images",void 0);fw([ee({type:Object})],tp.prototype,"secondImage",void 0);tp=fw([We("wui-transaction-visual")],tp);const hdt=it` + :host > wui-flex:first-child { + align-items: center; + column-gap: var(--wui-spacing-s); + padding: 6.5px var(--wui-spacing-xs) 6.5px var(--wui-spacing-xs); + width: 100%; + } + + :host > wui-flex:first-child wui-text:nth-child(1) { + text-transform: capitalize; + } + + wui-transaction-visual { + width: 40px; + height: 40px; + } + + wui-flex { + flex: 1; + } + + :host wui-flex wui-flex { + overflow: hidden; + } + + :host .description-container wui-text span { + word-break: break-all; + } + + :host .description-container wui-text { + overflow: hidden; + } + + :host .description-separator-icon { + margin: 0px 6px; + } + + :host wui-text > span { + overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 1; + } +`;var gd=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Vc=class extends He{constructor(){super(...arguments),this.type="approve",this.onlyDirectionIcon=!1,this.images=[],this.price=[],this.amount=[],this.symbol=[]}render(){return K` + + + + + ${bB[this.type]||this.type} + + + ${this.templateDescription()} ${this.templateSecondDescription()} + + + ${this.date} + + `}templateDescription(){const e=this.descriptions?.[0];return e?K` + + ${e} + + `:null}templateSecondDescription(){const e=this.descriptions?.[1];return e?K` + + + ${e} + + `:null}};Vc.styles=[Ht,hdt];gd([ee()],Vc.prototype,"type",void 0);gd([ee({type:Array})],Vc.prototype,"descriptions",void 0);gd([ee()],Vc.prototype,"date",void 0);gd([ee({type:Boolean})],Vc.prototype,"onlyDirectionIcon",void 0);gd([ee()],Vc.prototype,"status",void 0);gd([ee()],Vc.prototype,"direction",void 0);gd([ee({type:Array})],Vc.prototype,"images",void 0);gd([ee({type:Array})],Vc.prototype,"price",void 0);gd([ee({type:Array})],Vc.prototype,"amount",void 0);gd([ee({type:Array})],Vc.prototype,"symbol",void 0);Vc=gd([We("wui-transaction-list-item")],Vc);const pdt=it` + :host { + display: block; + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-005); + background: linear-gradient( + 120deg, + var(--wui-color-bg-200) 5%, + var(--wui-color-bg-200) 48%, + var(--wui-color-bg-300) 55%, + var(--wui-color-bg-300) 60%, + var(--wui-color-bg-300) calc(60% + 10px), + var(--wui-color-bg-200) calc(60% + 12px), + var(--wui-color-bg-200) 100% + ); + background-size: 250%; + animation: shimmer 3s linear infinite reverse; + } + + :host([variant='light']) { + background: linear-gradient( + 120deg, + var(--wui-color-bg-150) 5%, + var(--wui-color-bg-150) 48%, + var(--wui-color-bg-200) 55%, + var(--wui-color-bg-200) 60%, + var(--wui-color-bg-200) calc(60% + 10px), + var(--wui-color-bg-150) calc(60% + 12px), + var(--wui-color-bg-150) 100% + ); + background-size: 250%; + } + + @keyframes shimmer { + from { + background-position: -250% 0; + } + to { + background-position: 250% 0; + } + } +`;var w3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let ky=class extends He{constructor(){super(...arguments),this.width="",this.height="",this.borderRadius="m",this.variant="default"}render(){return this.style.cssText=` + width: ${this.width}; + height: ${this.height}; + border-radius: ${`clamp(0px,var(--wui-border-radius-${this.borderRadius}), 40px)`}; + `,K``}};ky.styles=[pdt];w3([ee()],ky.prototype,"width",void 0);w3([ee()],ky.prototype,"height",void 0);w3([ee()],ky.prototype,"borderRadius",void 0);w3([ee()],ky.prototype,"variant",void 0);ky=w3([We("wui-shimmer")],ky);const gdt=it` + :host > wui-flex:first-child { + column-gap: var(--wui-spacing-s); + padding: 7px var(--wui-spacing-l) 7px var(--wui-spacing-xs); + width: 100%; + } + + wui-flex { + display: flex; + flex: 1; + } +`;var mdt=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let vB=class extends He{render(){return K` + + + + + + + + + `}};vB.styles=[Ht,gdt];vB=mdt([We("wui-transaction-list-item-loader")],vB);const ydt=it` + :host { + min-height: 100%; + } + + .group-container[last-group='true'] { + padding-bottom: var(--wui-spacing-m); + } + + .contentContainer { + height: 280px; + } + + .contentContainer > wui-icon-box { + width: 40px; + height: 40px; + border-radius: var(--wui-border-radius-xxs); + } + + .contentContainer > .textContent { + width: 65%; + } + + .emptyContainer { + height: 100%; + } +`;var hw=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const qA="last-transaction",wdt=7;let np=class extends He{constructor(){super(),this.unsubscribe=[],this.paginationObserver=void 0,this.page="activity",this.caipAddress=G.state.activeCaipAddress,this.transactionsByYear=Vo.state.transactionsByYear,this.loading=Vo.state.loading,this.empty=Vo.state.empty,this.next=Vo.state.next,Vo.clearCursor(),this.unsubscribe.push(G.subscribeKey("activeCaipAddress",e=>{e&&this.caipAddress!==e&&(Vo.resetTransactions(),Vo.fetchTransactions(e)),this.caipAddress=e}),G.subscribeKey("activeCaipNetwork",()=>{this.updateTransactionView()}),Vo.subscribe(e=>{this.transactionsByYear=e.transactionsByYear,this.loading=e.loading,this.empty=e.empty,this.next=e.next}))}firstUpdated(){this.updateTransactionView(),this.createPaginationObserver()}updated(){this.setPaginationObserver()}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return K` ${this.empty?null:this.templateTransactionsByYear()} + ${this.loading?this.templateLoading():null} + ${!this.loading&&this.empty?this.templateEmpty():null}`}updateTransactionView(){Vo.resetTransactions(),this.caipAddress&&Vo.fetchTransactions(De.getPlainAddress(this.caipAddress))}templateTransactionsByYear(){return Object.keys(this.transactionsByYear).sort().reverse().map(n=>{const r=parseInt(n,10),s=new Array(12).fill(null).map((i,o)=>{const a=zb.getTransactionGroupTitle(r,o),c=this.transactionsByYear[r]?.[o];return{groupTitle:a,transactions:c}}).filter(({transactions:i})=>i).reverse();return s.map(({groupTitle:i,transactions:o},a)=>{const c=a===s.length-1;return o?K` + + + ${i} + + + ${this.templateTransactions(o,c)} + + + `:null})})}templateRenderTransaction(e,n){const{date:r,descriptions:s,direction:i,isAllNFT:o,images:a,status:c,transfers:l,type:u}=this.getTransactionListItemProps(e),d=l?.length>1;return l?.length===2&&!o?K` + + `:d?l.map((p,m)=>{const y=zb.getTransferDescription(p),b=n&&m===l.length-1;return K` `}):K` + + `}templateTransactions(e,n){return e.map((r,s)=>{const i=n&&s===e.length-1;return K`${this.templateRenderTransaction(r,i)}`})}emptyStateActivity(){return K` + + + No Transactions yet + Start trading on dApps
+ to grow your wallet!
+
+
`}emptyStateAccount(){return K` + + + No activity yet + Your next transactions will appear here + + Trade + `}templateEmpty(){return this.page==="account"?K`${this.emptyStateAccount()}`:K`${this.emptyStateActivity()}`}templateLoading(){return this.page==="activity"?Array(wdt).fill(K` `).map(e=>e):null}onReceiveClick(){ze.push("WalletReceive")}createPaginationObserver(){const{projectId:e}=_e.state;this.paginationObserver=new IntersectionObserver(([n])=>{n?.isIntersecting&&!this.loading&&(Vo.fetchTransactions(De.getPlainAddress(this.caipAddress)),Lt.sendEvent({type:"track",event:"LOAD_MORE_TRANSACTIONS",properties:{address:De.getPlainAddress(this.caipAddress),projectId:e,cursor:this.next,isSmartAccount:Ss(G.state.activeChain)===_r.ACCOUNT_TYPES.SMART_ACCOUNT}}))},{}),this.setPaginationObserver()}setPaginationObserver(){this.paginationObserver?.disconnect();const e=this.shadowRoot?.querySelector(`#${qA}`);e&&this.paginationObserver?.observe(e)}getTransactionListItemProps(e){const n=e7.formatDate(e?.metadata?.minedAt),r=zb.getTransactionDescriptions(e),s=e?.transfers,i=e?.transfers?.[0],o=!!i&&e?.transfers?.every(c=>!!c.nft_info),a=zb.getTransactionImages(s);return{date:n,direction:i?.direction,descriptions:r,isAllNFT:o,images:a,status:e.metadata?.status,transfers:s,type:e.metadata?.operationType}}};np.styles=ydt;hw([ee()],np.prototype,"page",void 0);hw([Ne()],np.prototype,"caipAddress",void 0);hw([Ne()],np.prototype,"transactionsByYear",void 0);hw([Ne()],np.prototype,"loading",void 0);hw([Ne()],np.prototype,"empty",void 0);hw([Ne()],np.prototype,"next",void 0);np=hw([We("w3m-activity-list")],np);const bdt=it` + :host { + width: 100%; + max-height: 280px; + overflow: scroll; + scrollbar-width: none; + } + + :host::-webkit-scrollbar { + display: none; + } +`;var vdt=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let xB=class extends He{render(){return K``}};xB.styles=bdt;xB=vdt([We("w3m-account-activity-widget")],xB);const xdt=it` + .contentContainer { + height: 280px; + } + + .contentContainer > wui-icon-box { + width: 40px; + height: 40px; + border-radius: var(--wui-border-radius-xxs); + } + + .contentContainer > .textContent { + width: 65%; + } +`;var Edt=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let EB=class extends He{render(){return K`${this.nftTemplate()}`}nftTemplate(){return K` + + + Coming soon + Stay tuned for our upcoming NFT feature + + Receive funds + `}onReceiveClick(){ze.push("WalletReceive")}};EB.styles=xdt;EB=Edt([We("w3m-account-nfts-widget")],EB);const Cdt=it` + button { + width: 100%; + display: flex; + gap: var(--wui-spacing-s); + align-items: center; + justify-content: flex-start; + padding: var(--wui-spacing-s) var(--wui-spacing-m) var(--wui-spacing-s) var(--wui-spacing-s); + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + } + + wui-icon-box { + width: var(--wui-spacing-2xl); + height: var(--wui-spacing-2xl); + } + + wui-flex { + width: auto; + } +`;var D0=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let mf=class extends He{constructor(){super(...arguments),this.icon="card",this.text="",this.description="",this.tag=void 0,this.iconBackgroundColor="accent-100",this.iconColor="accent-100",this.disabled=!1}render(){return K` + + `}titleTemplate(){return this.tag?K` ${this.text}${this.tag} + `:K`${this.text}`}};mf.styles=[Ht,lr,Cdt];D0([ee()],mf.prototype,"icon",void 0);D0([ee()],mf.prototype,"text",void 0);D0([ee()],mf.prototype,"description",void 0);D0([ee()],mf.prototype,"tag",void 0);D0([ee()],mf.prototype,"iconBackgroundColor",void 0);D0([ee()],mf.prototype,"iconColor",void 0);D0([ee({type:Boolean})],mf.prototype,"disabled",void 0);mf=D0([We("wui-list-description")],mf);const _dt=it` + button { + padding: 6.5px var(--wui-spacing-l) 6.5px var(--wui-spacing-xs); + display: flex; + justify-content: space-between; + width: 100%; + border-radius: var(--wui-border-radius-xs); + background-color: var(--wui-color-gray-glass-002); + } + + button[data-clickable='false'] { + pointer-events: none; + background-color: transparent; + } + + wui-image, + wui-icon { + width: var(--wui-spacing-3xl); + height: var(--wui-spacing-3xl); + } + + wui-image { + border-radius: var(--wui-border-radius-3xl); + } +`;var pw=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let rp=class extends He{constructor(){super(...arguments),this.tokenName="",this.tokenImageUrl="",this.tokenValue=0,this.tokenAmount="0.0",this.tokenCurrency="",this.clickable=!1}render(){return K` + + `}visualTemplate(){return this.tokenName&&this.tokenImageUrl?K``:K``}};rp.styles=[Ht,lr,_dt];pw([ee()],rp.prototype,"tokenName",void 0);pw([ee()],rp.prototype,"tokenImageUrl",void 0);pw([ee({type:Number})],rp.prototype,"tokenValue",void 0);pw([ee()],rp.prototype,"tokenAmount",void 0);pw([ee()],rp.prototype,"tokenCurrency",void 0);pw([ee({type:Boolean})],rp.prototype,"clickable",void 0);rp=pw([We("wui-list-token")],rp);const Sdt=it` + :host { + width: 100%; + } + + wui-flex { + width: 100%; + } + + .contentContainer { + max-height: 280px; + overflow: scroll; + scrollbar-width: none; + } + + .contentContainer::-webkit-scrollbar { + display: none; + } +`;var SW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let C_=class extends He{constructor(){super(),this.unsubscribe=[],this.tokenBalance=nt.state.tokenBalance,this.remoteFeatures=_e.state.remoteFeatures,this.unsubscribe.push(nt.subscribe(e=>{this.tokenBalance=e.tokenBalance}),_e.subscribeKey("remoteFeatures",e=>{this.remoteFeatures=e}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return K`${this.tokenTemplate()}`}tokenTemplate(){return this.tokenBalance&&this.tokenBalance?.length>0?K` + ${this.tokenItemTemplate()} + `:K` ${this.onRampTemplate()} + `}onRampTemplate(){return this.remoteFeatures?.onramp?K``:K``}tokenItemTemplate(){return this.tokenBalance?.map(e=>K``)}onReceiveClick(){ze.push("WalletReceive")}onBuyClick(){Lt.sendEvent({type:"track",event:"SELECT_BUY_CRYPTO",properties:{isSmartAccount:Ss(G.state.activeChain)===_r.ACCOUNT_TYPES.SMART_ACCOUNT}}),ze.push("OnRampProviders")}};C_.styles=Sdt;SW([Ne()],C_.prototype,"tokenBalance",void 0);SW([Ne()],C_.prototype,"remoteFeatures",void 0);C_=SW([We("w3m-account-tokens-widget")],C_);const Adt=it` + :host { + width: 100%; + display: block; + } +`;var AW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let __=class extends He{constructor(){super(),this.unsubscribe=[],this.text="",this.open=Tc.state.open,this.unsubscribe.push(ze.subscribeKey("view",()=>{Tc.hide()}),tn.subscribeKey("open",e=>{e||Tc.hide()}),Tc.subscribeKey("open",e=>{this.open=e}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e()),Tc.hide()}render(){return K` +
+ ${this.renderChildren()} +
+ `}renderChildren(){return K` `}onMouseEnter(){const e=this.getBoundingClientRect();this.open||Tc.showTooltip({message:this.text,triggerRect:{width:e.width,height:e.height,left:e.left,top:e.top},variant:"shade"})}onMouseLeave(e){this.contains(e.relatedTarget)||Tc.hide()}};__.styles=[Adt];AW([ee()],__.prototype,"text",void 0);AW([Ne()],__.prototype,"open",void 0);__=AW([We("w3m-tooltip-trigger")],__);const Idt=it` + :host { + pointer-events: none; + } + + :host > wui-flex { + display: var(--w3m-tooltip-display); + opacity: var(--w3m-tooltip-opacity); + padding: 9px var(--wui-spacing-s) 10px var(--wui-spacing-s); + border-radius: var(--wui-border-radius-xxs); + color: var(--wui-color-bg-100); + position: fixed; + top: var(--w3m-tooltip-top); + left: var(--w3m-tooltip-left); + transform: translate(calc(-50% + var(--w3m-tooltip-parent-width)), calc(-100% - 8px)); + max-width: calc(var(--w3m-modal-width) - var(--wui-spacing-xl)); + transition: opacity 0.2s var(--wui-ease-out-power-2); + will-change: opacity; + } + + :host([data-variant='shade']) > wui-flex { + background-color: var(--wui-color-bg-150); + border: 1px solid var(--wui-color-gray-glass-005); + } + + :host([data-variant='shade']) > wui-flex > wui-text { + color: var(--wui-color-fg-150); + } + + :host([data-variant='fill']) > wui-flex { + background-color: var(--wui-color-fg-100); + border: none; + } + + wui-icon { + position: absolute; + width: 12px !important; + height: 4px !important; + color: var(--wui-color-bg-150); + } + + wui-icon[data-placement='top'] { + bottom: 0px; + left: 50%; + transform: translate(-50%, 95%); + } + + wui-icon[data-placement='bottom'] { + top: 0; + left: 50%; + transform: translate(-50%, -95%) rotate(180deg); + } + + wui-icon[data-placement='right'] { + top: 50%; + left: 0; + transform: translate(-65%, -50%) rotate(90deg); + } + + wui-icon[data-placement='left'] { + top: 50%; + right: 0%; + transform: translate(65%, -50%) rotate(270deg); + } +`;var b3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Ry=class extends He{constructor(){super(),this.unsubscribe=[],this.open=Tc.state.open,this.message=Tc.state.message,this.triggerRect=Tc.state.triggerRect,this.variant=Tc.state.variant,this.unsubscribe.push(Tc.subscribe(e=>{this.open=e.open,this.message=e.message,this.triggerRect=e.triggerRect,this.variant=e.variant}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){this.dataset.variant=this.variant;const e=this.triggerRect.top,n=this.triggerRect.left;return this.style.cssText=` + --w3m-tooltip-top: ${e}px; + --w3m-tooltip-left: ${n}px; + --w3m-tooltip-parent-width: ${this.triggerRect.width/2}px; + --w3m-tooltip-display: ${this.open?"flex":"none"}; + --w3m-tooltip-opacity: ${this.open?1:0}; + `,K` + + ${this.message} + `}};Ry.styles=[Idt];b3([Ne()],Ry.prototype,"open",void 0);b3([Ne()],Ry.prototype,"message",void 0);b3([Ne()],Ry.prototype,"triggerRect",void 0);b3([Ne()],Ry.prototype,"variant",void 0);Ry=b3([We("w3m-tooltip"),We("w3m-tooltip")],Ry);const Tdt=it` + wui-flex { + width: 100%; + } + + wui-promo { + position: absolute; + top: -32px; + } + + wui-profile-button { + margin-top: calc(-1 * var(--wui-spacing-2l)); + } + + wui-promo + wui-profile-button { + margin-top: var(--wui-spacing-2l); + } + + wui-tabs { + width: 100%; + } + + .contentContainer { + height: 280px; + } + + .contentContainer > wui-icon-box { + width: 40px; + height: 40px; + border-radius: var(--wui-border-radius-xxs); + } + + .contentContainer > .textContent { + width: 65%; + } +`;var md=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const Ndt=48,Pdt=430;let Hc=class extends He{constructor(){super(),this.unsubscribe=[],this.address=nt.state.address,this.profileName=nt.state.profileName,this.network=G.state.activeCaipNetwork,this.currentTab=nt.state.currentTab,this.tokenBalance=nt.state.tokenBalance,this.features=_e.state.features,this.namespace=G.state.activeChain,this.activeConnectorIds=ke.state.activeConnectorIds,this.remoteFeatures=_e.state.remoteFeatures,this.unsubscribe.push(nt.subscribe(e=>{e.address?(this.address=e.address,this.profileName=e.profileName,this.currentTab=e.currentTab,this.tokenBalance=e.tokenBalance):tn.close()}),ke.subscribeKey("activeConnectorIds",e=>{this.activeConnectorIds=e}),G.subscribeKey("activeChain",e=>this.namespace=e),G.subscribeKey("activeCaipNetwork",e=>this.network=e),_e.subscribeKey("features",e=>this.features=e),_e.subscribeKey("remoteFeatures",e=>this.remoteFeatures=e)),this.watchSwapValues()}disconnectedCallback(){this.unsubscribe.forEach(e=>e()),clearInterval(this.watchTokenBalance)}firstUpdated(){nt.fetchTokenBalance()}render(){if(!this.address)throw new Error("w3m-account-view: No account provided");if(!this.namespace)return null;const e=this.activeConnectorIds[this.namespace],n=e?ke.getConnectorById(e):void 0,{icon:r,iconSize:s}=this.getAuthData();return K` + + + + ${this.tokenBalanceTemplate()} + + ${this.orderedWalletFeatures()} ${this.tabsTemplate()} ${this.listContentTemplate()} + `}orderedWalletFeatures(){const e=this.features?.walletFeaturesOrder||wn.DEFAULT_FEATURES.walletFeaturesOrder;return e.every(r=>r==="send"||r==="receive"?!this.features?.[r]:r==="swaps"||r==="onramp"?!this.remoteFeatures?.[r]:!0)?null:K` + ${e.map(r=>{switch(r){case"onramp":return this.onrampTemplate();case"swaps":return this.swapsTemplate();case"receive":return this.receiveTemplate();case"send":return this.sendTemplate();default:return null}})} + `}onrampTemplate(){return this.remoteFeatures?.onramp?K` + + + + `:null}swapsTemplate(){const e=this.remoteFeatures?.swaps,n=G.state.activeChain===ye.CHAIN.EVM;return!e||!n?null:K` + + + + + `}receiveTemplate(){return this.features?.receive?K` + + + + + `:null}sendTemplate(){const e=this.features?.send,n=G.state.activeChain,r=wn.SEND_SUPPORTED_NAMESPACES.includes(n);return!e||!r?null:K` + + + + `}watchSwapValues(){this.watchTokenBalance=setInterval(()=>nt.fetchTokenBalance(e=>this.onTokenBalanceError(e)),1e4)}onTokenBalanceError(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===ye.HTTP_STATUS_CODES.SERVICE_UNAVAILABLE&&clearInterval(this.watchTokenBalance)}listContentTemplate(){return this.currentTab===0?K``:this.currentTab===1?K``:this.currentTab===2?K``:K``}tokenBalanceTemplate(){if(this.tokenBalance&&this.tokenBalance?.length>=0){const e=De.calculateBalance(this.tokenBalance),{dollars:n="0",pennies:r="00"}=De.formatTokenBalance(e);return K``}return K``}tabsTemplate(){const e=udt.getTabsByNamespace(G.state.activeChain);if(e.length===0)return null;const n=De.isMobile()&&window.innerWidth`}onTabChange(e){nt.setCurrentTab(e)}onBuyClick(){ze.push("OnRampProviders")}onSwapClick(){this.network?.caipNetworkId&&!wn.SWAP_SUPPORTED_NETWORKS.includes(this.network?.caipNetworkId)?ze.push("UnsupportedChain",{swapUnsupportedChain:!0}):(Lt.sendEvent({type:"track",event:"OPEN_SWAP",properties:{network:this.network?.caipNetworkId||"",isSmartAccount:Ss(G.state.activeChain)===_r.ACCOUNT_TYPES.SMART_ACCOUNT}}),ze.push("Swap"))}getAuthData(){const e=Ge.getConnectedSocialProvider(),n=Ge.getConnectedSocialUsername(),s=ke.getAuthConnector()?.provider.getEmail()??"";return{name:qu.getAuthName({email:s,socialUsername:n,socialProvider:e}),icon:e??"mail",iconSize:e?"xl":"md"}}onReceiveClick(){ze.push("WalletReceive")}onGoToProfileWalletsView(){ze.push("ProfileWallets")}onSendClick(){Lt.sendEvent({type:"track",event:"OPEN_SEND",properties:{network:this.network?.caipNetworkId||"",isSmartAccount:Ss(G.state.activeChain)===_r.ACCOUNT_TYPES.SMART_ACCOUNT}}),ze.push("WalletSend")}};Hc.styles=Tdt;md([Ne()],Hc.prototype,"watchTokenBalance",void 0);md([Ne()],Hc.prototype,"address",void 0);md([Ne()],Hc.prototype,"profileName",void 0);md([Ne()],Hc.prototype,"network",void 0);md([Ne()],Hc.prototype,"currentTab",void 0);md([Ne()],Hc.prototype,"tokenBalance",void 0);md([Ne()],Hc.prototype,"features",void 0);md([Ne()],Hc.prototype,"namespace",void 0);md([Ne()],Hc.prototype,"activeConnectorIds",void 0);md([Ne()],Hc.prototype,"remoteFeatures",void 0);Hc=md([We("w3m-account-wallet-features-widget")],Hc);var g0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let nN=class extends He{constructor(){super(),this.unsubscribe=[],this.namespace=G.state.activeChain,this.unsubscribe.push(G.subscribeKey("activeChain",e=>{this.namespace=e}))}render(){if(!this.namespace)return null;const e=ke.getConnectorId(this.namespace),n=ke.getAuthConnector();return K` + ${n&&e===ye.CONNECTOR_ID.AUTH?this.walletFeaturesTemplate():this.defaultTemplate()} + `}walletFeaturesTemplate(){return K``}defaultTemplate(){return K``}};g0e([Ne()],nN.prototype,"namespace",void 0);nN=g0e([We("w3m-account-view")],nN);const kdt=it` + :host { + position: relative; + background-color: var(--wui-color-gray-glass-002); + display: flex; + justify-content: center; + align-items: center; + width: var(--local-size); + height: var(--local-size); + border-radius: inherit; + border-radius: var(--local-border-radius); + } + + :host > wui-flex { + overflow: hidden; + border-radius: inherit; + border-radius: var(--local-border-radius); + } + + :host::after { + content: ''; + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + border-radius: inherit; + border: 1px solid var(--wui-color-gray-glass-010); + pointer-events: none; + } + + :host([name='Extension'])::after { + border: 1px solid var(--wui-color-accent-glass-010); + } + + :host([data-wallet-icon='allWallets']) { + background-color: var(--wui-all-wallets-bg-100); + } + + :host([data-wallet-icon='allWallets'])::after { + border: 1px solid var(--wui-color-accent-glass-010); + } + + wui-icon[data-parent-size='inherit'] { + width: 75%; + height: 75%; + align-items: center; + } + + wui-icon[data-parent-size='sm'] { + width: 18px; + height: 18px; + } + + wui-icon[data-parent-size='md'] { + width: 24px; + height: 24px; + } + + wui-icon[data-parent-size='lg'] { + width: 42px; + height: 42px; + } + + wui-icon[data-parent-size='full'] { + width: 100%; + height: 100%; + } + + :host > wui-icon-box { + position: absolute; + overflow: hidden; + right: -1px; + bottom: -2px; + z-index: 1; + border: 2px solid var(--wui-color-bg-150, #1e1f1f); + padding: 1px; + } +`;var gw=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let sp=class extends He{constructor(){super(...arguments),this.size="md",this.name="",this.installed=!1,this.badgeSize="xs"}render(){let e="xxs";return this.size==="lg"?e="m":this.size==="md"?e="xs":e="xxs",this.style.cssText=` + --local-border-radius: var(--wui-border-radius-${e}); + --local-size: var(--wui-wallet-image-size-${this.size}); + `,this.walletIcon&&(this.dataset.walletIcon=this.walletIcon),K` + ${this.templateVisual()} + `}templateVisual(){return this.imageSrc?K``:this.walletIcon?K``:K``}};sp.styles=[lr,Ht,kdt];gw([ee()],sp.prototype,"size",void 0);gw([ee()],sp.prototype,"name",void 0);gw([ee()],sp.prototype,"imageSrc",void 0);gw([ee()],sp.prototype,"walletIcon",void 0);gw([ee({type:Boolean})],sp.prototype,"installed",void 0);gw([ee()],sp.prototype,"badgeSize",void 0);sp=gw([We("wui-wallet-image")],sp);const Rdt=it` + wui-image { + width: var(--wui-spacing-2xl); + height: var(--wui-spacing-2xl); + border-radius: var(--wui-border-radius-3xs); + } + + wui-image, + .icon-box { + width: var(--wui-spacing-2xl); + height: var(--wui-spacing-2xl); + border-radius: var(--wui-border-radius-3xs); + } + + wui-icon:not(.custom-icon, .icon-badge) { + cursor: pointer; + } + + .icon-box { + position: relative; + background-color: var(--wui-color-gray-glass-002); + } + + .icon-badge { + position: absolute; + top: 18px; + left: 23px; + z-index: 3; + background-color: var(--wui-color-gray-glass-005); + border: 2px solid var(--wui-color-modal-bg); + border-radius: 50%; + padding: var(--wui-spacing-4xs); + } +`;var ic=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let ko=class extends He{constructor(){super(...arguments),this.address="",this.profileName="",this.content=[],this.alt="",this.imageSrc="",this.icon=void 0,this.iconSize="md",this.iconBadge=void 0,this.iconBadgeSize="md",this.buttonVariant="neutral",this.enableMoreButton=!1,this.charsStart=4,this.charsEnd=6}render(){return K` + + ${this.topTemplate()} ${this.bottomTemplate()} + + `}topTemplate(){return K` + + ${this.imageOrIconTemplate()} + + + ${this.enableMoreButton?K``:null} + + `}bottomTemplate(){return K` ${this.contentTemplate()} `}imageOrIconTemplate(){return this.icon?K` + + + + + ${this.iconBadge?K``:null} + + + `:K` + + + + `}contentTemplate(){return this.content.length===0?null:K` + + ${this.content.map(e=>this.labelAndTagTemplate(e))} + + `}labelAndTagTemplate({address:e,profileName:n,label:r,description:s,enableButton:i,buttonType:o,buttonLabel:a,buttonVariant:c,tagVariant:l,tagLabel:u,alignItems:d="flex-end"}){return K` + + + ${r?K`${r}`:null} + + + + ${qr.getTruncateString({string:n||e,charsStart:n?16:this.charsStart,charsEnd:n?0:this.charsEnd,truncate:n?"end":"middle"})} + + + ${l&&u?K`${u}`:null} + + + ${s?K`${s}`:null} + + + ${i?this.buttonTemplate({buttonType:o,buttonLabel:a,buttonVariant:c}):null} + + `}buttonTemplate({buttonType:e,buttonLabel:n,buttonVariant:r}){return K` + + ${n} + + `}dispatchDisconnectEvent(){this.dispatchEvent(new CustomEvent("disconnect",{bubbles:!0,composed:!0}))}dispatchSwitchEvent(){this.dispatchEvent(new CustomEvent("switch",{bubbles:!0,composed:!0}))}dispatchExternalLinkEvent(){this.dispatchEvent(new CustomEvent("externalLink",{bubbles:!0,composed:!0}))}dispatchMoreButtonEvent(){this.dispatchEvent(new CustomEvent("more",{bubbles:!0,composed:!0}))}dispatchCopyEvent(){this.dispatchEvent(new CustomEvent("copy",{bubbles:!0,composed:!0}))}};ko.styles=[Ht,lr,Rdt];ic([ee()],ko.prototype,"address",void 0);ic([ee()],ko.prototype,"profileName",void 0);ic([ee({type:Array})],ko.prototype,"content",void 0);ic([ee()],ko.prototype,"alt",void 0);ic([ee()],ko.prototype,"imageSrc",void 0);ic([ee()],ko.prototype,"icon",void 0);ic([ee()],ko.prototype,"iconSize",void 0);ic([ee()],ko.prototype,"iconBadge",void 0);ic([ee()],ko.prototype,"iconBadgeSize",void 0);ic([ee()],ko.prototype,"buttonVariant",void 0);ic([ee({type:Boolean})],ko.prototype,"enableMoreButton",void 0);ic([ee({type:Number})],ko.prototype,"charsStart",void 0);ic([ee({type:Number})],ko.prototype,"charsEnd",void 0);ko=ic([We("wui-active-profile-wallet-item")],ko);const Odt=it` + wui-image, + .icon-box { + width: var(--wui-spacing-2xl); + height: var(--wui-spacing-2xl); + border-radius: var(--wui-border-radius-3xs); + } + + .right-icon { + cursor: pointer; + } + + .icon-box { + position: relative; + background-color: var(--wui-color-gray-glass-002); + } + + .icon-badge { + position: absolute; + top: 18px; + left: 23px; + z-index: 3; + background-color: var(--wui-color-gray-glass-005); + border: 2px solid var(--wui-color-modal-bg); + border-radius: 50%; + padding: var(--wui-spacing-4xs); + } +`;var Bo=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let vi=class extends He{constructor(){super(...arguments),this.address="",this.profileName="",this.alt="",this.buttonLabel="",this.buttonVariant="accent",this.imageSrc="",this.icon=void 0,this.iconSize="md",this.iconBadgeSize="md",this.rightIcon="off",this.rightIconSize="md",this.loading=!1,this.charsStart=4,this.charsEnd=6}render(){return K` + + ${this.imageOrIconTemplate()} ${this.labelAndDescriptionTemplate()} + ${this.buttonActionTemplate()} + + `}imageOrIconTemplate(){return this.icon?K` + + + + ${this.iconBadge?K``:null} + + + `:K``}labelAndDescriptionTemplate(){return K` + + + ${qr.getTruncateString({string:this.profileName||this.address,charsStart:this.profileName?16:this.charsStart,charsEnd:this.profileName?0:this.charsEnd,truncate:this.profileName?"end":"middle"})} + + + `}buttonActionTemplate(){return K` + + + ${this.buttonLabel} + + + + + `}handleButtonClick(){this.dispatchEvent(new CustomEvent("buttonClick",{bubbles:!0,composed:!0}))}handleIconClick(){this.dispatchEvent(new CustomEvent("iconClick",{bubbles:!0,composed:!0}))}};vi.styles=[Ht,lr,Odt];Bo([ee()],vi.prototype,"address",void 0);Bo([ee()],vi.prototype,"profileName",void 0);Bo([ee()],vi.prototype,"alt",void 0);Bo([ee()],vi.prototype,"buttonLabel",void 0);Bo([ee()],vi.prototype,"buttonVariant",void 0);Bo([ee()],vi.prototype,"imageSrc",void 0);Bo([ee()],vi.prototype,"icon",void 0);Bo([ee()],vi.prototype,"iconSize",void 0);Bo([ee()],vi.prototype,"iconBadge",void 0);Bo([ee()],vi.prototype,"iconBadgeSize",void 0);Bo([ee()],vi.prototype,"rightIcon",void 0);Bo([ee()],vi.prototype,"rightIconSize",void 0);Bo([ee({type:Boolean})],vi.prototype,"loading",void 0);Bo([ee({type:Number})],vi.prototype,"charsStart",void 0);Bo([ee({type:Number})],vi.prototype,"charsEnd",void 0);vi=Bo([We("wui-inactive-profile-wallet-item")],vi);const $dt=it` + :host { + position: relative; + display: flex; + width: 100%; + height: 1px; + background-color: var(--wui-color-gray-glass-005); + justify-content: center; + align-items: center; + } + + :host > wui-text { + position: absolute; + padding: 0px 10px; + background-color: var(--wui-color-modal-bg); + transition: background-color var(--wui-duration-lg) var(--wui-ease-out-power-1); + will-change: background-color; + } +`;var m0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let rN=class extends He{constructor(){super(...arguments),this.text=""}render(){return K`${this.template()}`}template(){return this.text?K`${this.text}`:null}};rN.styles=[Ht,$dt];m0e([ee()],rN.prototype,"text",void 0);rN=m0e([We("wui-separator")],rN);const bD={getAuthData(t){const e=t.connectorId===ye.CONNECTOR_ID.AUTH;if(!e)return{isAuth:!1,icon:void 0,iconSize:void 0,name:void 0};const n=t?.auth?.name??Ge.getConnectedSocialProvider(),r=t?.auth?.username??Ge.getConnectedSocialUsername(),i=ke.getAuthConnector()?.provider.getEmail()??"";return{isAuth:!0,icon:n??"mail",iconSize:n?"xl":"md",name:e?qu.getAuthName({email:i,socialUsername:r,socialProvider:n}):void 0}}},Ddt=it` + :host { + --connect-scroll--top-opacity: 0; + --connect-scroll--bottom-opacity: 0; + } + + .balance-amount { + flex: 1; + } + + .wallet-list { + scrollbar-width: none; + overflow-y: scroll; + overflow-x: hidden; + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + mask-image: linear-gradient( + to bottom, + rgba(0, 0, 0, calc(1 - var(--connect-scroll--top-opacity))) 0px, + rgba(200, 200, 200, calc(1 - var(--connect-scroll--top-opacity))) 1px, + black 40px, + black calc(100% - 40px), + rgba(155, 155, 155, calc(1 - var(--connect-scroll--bottom-opacity))) calc(100% - 1px), + rgba(0, 0, 0, calc(1 - var(--connect-scroll--bottom-opacity))) 100% + ); + } + + .active-wallets { + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + } + + .active-wallets-box { + height: 330px; + } + + .empty-wallet-list-box { + height: 400px; + } + + .empty-box { + width: 100%; + padding: var(--wui-spacing-l); + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + } + + wui-separator { + margin: var(--wui-spacing-xs) 0 var(--wui-spacing-xs) 0; + } + + .active-connection { + padding: var(--wui-spacing-xs); + } + + .recent-connection { + padding: var(--wui-spacing-xs) 0 var(--wui-spacing-xs) 0; + } + + @media (max-width: 430px) { + .active-wallets-box, + .empty-wallet-list-box { + height: auto; + max-height: clamp(360px, 470px, 80vh); + } + } +`;var oc=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const Mdt=16,Ldt=4,fl={ADDRESS_DISPLAY:{START:4,END:6},BADGE:{SIZE:"md",ICON:"lightbulb"},SCROLL_THRESHOLD:50,OPACITY_RANGE:[0,1]},ME={eip155:"ethereum",solana:"solana",bip122:"bitcoin"},hte=[{namespace:"eip155",icon:ME.eip155,label:"EVM"},{namespace:"solana",icon:ME.solana,label:"Solana"},{namespace:"bip122",icon:ME.bip122,label:"Bitcoin"}],Bdt={eip155:{title:"Add EVM Wallet",description:"Add your first EVM wallet"},solana:{title:"Add Solana Wallet",description:"Add your first Solana wallet"},bip122:{title:"Add Bitcoin Wallet",description:"Add your first Bitcoin wallet"}};let Ki=class extends He{constructor(){super(),this.unsubscribers=[],this.currentTab=0,this.namespace=G.state.activeChain,this.namespaces=Array.from(G.state.chains.keys()),this.caipAddress=void 0,this.profileName=void 0,this.activeConnectorIds=ke.state.activeConnectorIds,this.lastSelectedAddress="",this.lastSelectedConnectorId="",this.isSwitching=!1,this.caipNetwork=G.state.activeCaipNetwork,this.user=nt.state.user,this.remoteFeatures=_e.state.remoteFeatures,this.tabWidth="",this.currentTab=this.namespace?this.namespaces.indexOf(this.namespace):0,this.caipAddress=G.getAccountData(this.namespace)?.caipAddress,this.profileName=G.getAccountData(this.namespace)?.profileName,this.unsubscribers.push(Ue.subscribeKey("connections",()=>this.onConnectionsChange()),Ue.subscribeKey("recentConnections",()=>this.requestUpdate()),ke.subscribeKey("activeConnectorIds",e=>{this.activeConnectorIds=e}),G.subscribeKey("activeCaipNetwork",e=>this.caipNetwork=e),nt.subscribeKey("user",e=>this.user=e),_e.subscribeKey("remoteFeatures",e=>this.remoteFeatures=e)),this.chainListener=G.subscribeChainProp("accountState",e=>{this.caipAddress=e?.caipAddress,this.profileName=e?.profileName},this.namespace)}disconnectedCallback(){this.unsubscribers.forEach(e=>e()),this.resizeObserver?.disconnect(),this.tabsResizeObserver?.disconnect(),this.removeScrollListener(),this.chainListener?.()}firstUpdated(){const e=this.shadowRoot?.querySelector(".wallet-list"),n=this.shadowRoot?.querySelector("wui-tabs");if(!e)return;const r=()=>this.updateScrollOpacity(e);if(requestAnimationFrame(r),e.addEventListener("scroll",r),this.resizeObserver=new ResizeObserver(r),this.resizeObserver.observe(e),r(),n){const s=()=>{const o=hte.filter(a=>this.namespaces.includes(a.namespace)).length;if(o>1){const a=this.getBoundingClientRect()?.width,c=Ldt*2,l=Mdt*2,d=(a-l-c)/o;this.tabWidth=`${d}px`,this.requestUpdate()}};this.tabsResizeObserver=new ResizeObserver(s),this.tabsResizeObserver.observe(this),s()}}render(){const e=this.namespace;if(!e)throw new Error("Namespace is not set");return K` + + ${this.renderTabs()} ${this.renderHeader(e)} ${this.renderConnections(e)} + ${this.renderAddConnectionButton(e)} + + `}renderTabs(){const e=hte.filter(r=>this.namespaces.includes(r.namespace));return e.length>1?K` + this.handleTabChange(r)} + .activeTab=${this.currentTab} + localTabWidth=${this.tabWidth} + .tabs=${e} + > + `:null}renderHeader(e){const r=this.getActiveConnections(e).flatMap(({accounts:s})=>s).length+(this.caipAddress?1:0);return K` + + + ${r>1?"Wallets":"Wallet"} + + ${r} + + Ue.disconnect({namespace:e})} + ?disabled=${!this.hasAnyConnections(e)} + data-testid="disconnect-all-button" + > + Disconnect All + + + `}renderConnections(e){const n=this.hasAnyConnections(e);return K` + + ${n?this.renderActiveConnections(e):this.renderEmptyState(e)} + + `}renderActiveConnections(e){const n=this.getActiveConnections(e),r=this.activeConnectorIds[e],s=this.getPlainAddress();return K` + ${s||r||n.length>0?K` + ${this.renderActiveProfile(e)} ${this.renderActiveConnectionsList(e)} + `:null} + ${this.renderRecentConnections(e)} + `}renderActiveProfile(e){const n=this.activeConnectorIds[e];if(!n)return null;const{connections:r}=Sl.getConnectionsData(e),s=ke.getConnectorById(n),i=nr.getConnectorImage(s),o=this.getPlainAddress();if(!o)return null;const a=e===ye.CHAIN.BITCOIN,c=bD.getAuthData({connectorId:n,accounts:[]}),l=this.getActiveConnections(e).flatMap(f=>f.accounts).length>0,u=r.find(f=>f.connectorId===n),d=u?.accounts.filter(f=>!Jn.isLowerCaseMatch(f.address,o));return K` + + this.handleCopyAddress(o)} + @disconnect=${()=>this.handleDisconnect(e,{id:n})} + @switch=${()=>{a&&u&&d?.[0]&&this.handleSwitchWallet(u,d[0].address,e)}} + @externalLink=${()=>this.handleExternalLink(o)} + @more=${()=>this.handleMore()} + data-testid="wui-active-profile-wallet-item" + > + ${l?K``:null} + + `}renderActiveConnectionsList(e){const n=this.getActiveConnections(e);return n.length===0?null:K` + + ${this.renderConnectionList(n,!1,e)} + + `}renderRecentConnections(e){const{recentConnections:n}=Sl.getConnectionsData(e);return n.flatMap(s=>s.accounts).length===0?null:K` + + RECENTLY CONNECTED + + ${this.renderConnectionList(n,!0,e)} + + + `}renderConnectionList(e,n,r){return e.filter(s=>s.accounts.length>0).map((s,i)=>{const o=ke.getConnectorById(s.connectorId),a=nr.getConnectorImage(o)??"",c=bD.getAuthData(s);return s.accounts.map((l,u)=>{const d=i!==0||u!==0,f=this.isAccountLoading(s.connectorId,l.address);return K` + + ${d?K``:null} + this.handleSwitchWallet(s,l.address,r)} + @iconClick=${()=>this.handleWalletAction({connection:s,address:l.address,isRecentConnection:n,namespace:r})} + > + + `})})}renderAddConnectionButton(e){if(!this.isMultiWalletEnabled()&&this.caipAddress||!this.hasAnyConnections(e))return null;const{title:n}=this.getChainLabelInfo(e);return K` + this.handleAddConnection(e)} + data-testid="add-connection-button" + > + ${n} + + `}renderEmptyState(e){const{title:n,description:r}=this.getChainLabelInfo(e);return K` + + + + + + No wallet connected + ${r} + + + this.handleAddConnection(e)} + data-testid="empty-state-button" + > + + ${n} + + + + `}handleTabChange(e){const n=this.namespaces[e];n&&(this.chainListener?.(),this.currentTab=this.namespaces.indexOf(n),this.namespace=n,this.caipAddress=G.getAccountData(n)?.caipAddress,this.profileName=G.getAccountData(n)?.profileName,this.chainListener=G.subscribeChainProp("accountState",r=>{this.caipAddress=r?.caipAddress},n))}async handleSwitchWallet(e,n,r){try{this.isSwitching=!0,this.lastSelectedConnectorId=e.connectorId,this.lastSelectedAddress=n,await Ue.switchConnection({connection:e,address:n,namespace:r,closeModalOnConnect:!1,onChange({hasSwitchedAccount:s,hasSwitchedWallet:i}){i?Wn.showSuccess("Wallet switched"):s&&Wn.showSuccess("Account switched")}})}catch{Wn.showError("Failed to switch wallet")}finally{this.isSwitching=!1}}handleWalletAction(e){const{connection:n,address:r,isRecentConnection:s,namespace:i}=e;s?(Ge.deleteAddressFromConnection({connectorId:n.connectorId,address:r,namespace:i}),Ue.syncStorageConnections(),Wn.showSuccess("Wallet deleted")):this.handleDisconnect(i,{id:n.connectorId})}async handleDisconnect(e,{id:n}){try{await Ue.disconnect({id:n,namespace:e}),Wn.showSuccess("Wallet disconnected")}catch{Wn.showError("Failed to disconnect wallet")}}handleCopyAddress(e){De.copyToClopboard(e),Wn.showSuccess("Address copied")}handleMore(){ze.push("AccountSettings")}handleExternalLink(e){const n=this.caipNetwork?.blockExplorers?.default.url;n&&De.openHref(`${n}/address/${e}`,"_blank")}handleAddConnection(e){ke.setFilterByNamespace(e),ze.push("Connect")}getChainLabelInfo(e){return Bdt[e]??{title:"Add Wallet",description:"Add your first wallet"}}isSmartAccount(e){if(!this.namespace)return!1;const n=this.user?.accounts?.find(r=>r.type==="smartAccount");return n&&e?Jn.isLowerCaseMatch(n.address,e):!1}getPlainAddress(){return this.caipAddress?De.getPlainAddress(this.caipAddress):void 0}getActiveConnections(e){const n=this.activeConnectorIds[e],{connections:r}=Sl.getConnectionsData(e),[s]=r.filter(c=>Jn.isLowerCaseMatch(c.connectorId,n));if(!n)return r;const i=e===ye.CHAIN.BITCOIN,{address:o}=this.caipAddress?Yo.parseCaipAddress(this.caipAddress):{};let a=[...o?[o]:[]];return i&&s&&(a=s.accounts.map(c=>c.address)||[]),Sl.excludeConnectorAddressFromConnections({connectorId:n,addresses:a,connections:r})}hasAnyConnections(e){const n=this.getActiveConnections(e),{recentConnections:r}=Sl.getConnectionsData(e);return!!this.caipAddress||n.length>0||r.length>0}isAccountLoading(e,n){return Jn.isLowerCaseMatch(this.lastSelectedConnectorId,e)&&Jn.isLowerCaseMatch(this.lastSelectedAddress,n)&&this.isSwitching}getProfileContent(e){const{address:n,connections:r,connectorId:s,namespace:i}=e,[o]=r.filter(c=>Jn.isLowerCaseMatch(c.connectorId,s));if(i===ye.CHAIN.BITCOIN&&o?.accounts.every(c=>typeof c.type=="string"))return this.getBitcoinProfileContent(o.accounts,n);const a=bD.getAuthData({connectorId:s,accounts:[]});return[{address:n,tagLabel:"Active",tagVariant:"success",enableButton:!0,profileName:this.profileName,buttonType:"disconnect",buttonLabel:"Disconnect",buttonVariant:"neutral",...a.isAuth?{description:this.isSmartAccount(n)?"Smart Account":"EOA Account"}:{}}]}getBitcoinProfileContent(e,n){const r=e.length>1,s=this.getPlainAddress();return e.map(i=>{const o=Jn.isLowerCaseMatch(i.address,s);let a="PAYMENT";return i.type==="ordinal"&&(a="ORDINALS"),{address:i.address,tagLabel:Jn.isLowerCaseMatch(i.address,n)?"Active":void 0,tagVariant:Jn.isLowerCaseMatch(i.address,n)?"success":void 0,enableButton:!0,...r?{label:a,alignItems:"flex-end",buttonType:o?"disconnect":"switch",buttonLabel:o?"Disconnect":"Switch",buttonVariant:o?"neutral":"accent"}:{alignItems:"center",buttonType:"disconnect",buttonLabel:"Disconnect",buttonVariant:"neutral"}}})}removeScrollListener(){const e=this.shadowRoot?.querySelector(".wallet-list");e&&e.removeEventListener("scroll",()=>this.handleConnectListScroll())}handleConnectListScroll(){const e=this.shadowRoot?.querySelector(".wallet-list");e&&this.updateScrollOpacity(e)}isMultiWalletEnabled(){return!!this.remoteFeatures?.multiWallet}updateScrollOpacity(e){e.style.setProperty("--connect-scroll--top-opacity",VT.interpolate([0,fl.SCROLL_THRESHOLD],fl.OPACITY_RANGE,e.scrollTop).toString()),e.style.setProperty("--connect-scroll--bottom-opacity",VT.interpolate([0,fl.SCROLL_THRESHOLD],fl.OPACITY_RANGE,e.scrollHeight-e.scrollTop-e.offsetHeight).toString())}onConnectionsChange(){if(this.isMultiWalletEnabled()&&this.namespace){const{connections:e}=Sl.getConnectionsData(this.namespace);e.length===0&&ze.reset("ProfileWallets")}this.requestUpdate()}};Ki.styles=Ddt;oc([Ne()],Ki.prototype,"currentTab",void 0);oc([Ne()],Ki.prototype,"namespace",void 0);oc([Ne()],Ki.prototype,"namespaces",void 0);oc([Ne()],Ki.prototype,"caipAddress",void 0);oc([Ne()],Ki.prototype,"profileName",void 0);oc([Ne()],Ki.prototype,"activeConnectorIds",void 0);oc([Ne()],Ki.prototype,"lastSelectedAddress",void 0);oc([Ne()],Ki.prototype,"lastSelectedConnectorId",void 0);oc([Ne()],Ki.prototype,"isSwitching",void 0);oc([Ne()],Ki.prototype,"caipNetwork",void 0);oc([Ne()],Ki.prototype,"user",void 0);oc([Ne()],Ki.prototype,"remoteFeatures",void 0);oc([Ne()],Ki.prototype,"tabWidth",void 0);Ki=oc([We("w3m-profile-wallets-view")],Ki);/** + * @license + * Copyright 2020 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const v3=()=>new Udt;class Udt{}const vD=new WeakMap,x3=bW(class extends h0e{render(t){return Ds}update(t,[e]){const n=e!==this.G;return n&&this.G!==void 0&&this.rt(void 0),(n||this.lt!==this.ct)&&(this.G=e,this.ht=t.options?.host,this.rt(this.ct=t.element)),Ds}rt(t){if(this.isConnected||(t=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let n=vD.get(e);n===void 0&&(n=new WeakMap,vD.set(e,n)),n.get(this.G)!==void 0&&this.G.call(this.ht,void 0),n.set(this.G,t),t!==void 0&&this.G.call(this.ht,t)}else this.G.value=t}get lt(){return typeof this.G=="function"?vD.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}}),Fdt=it` + :host { + display: flex; + align-items: center; + justify-content: center; + } + + label { + position: relative; + display: inline-block; + width: 32px; + height: 22px; + } + + input { + width: 0; + height: 0; + opacity: 0; + } + + span { + position: absolute; + cursor: pointer; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: var(--wui-color-blue-100); + border-width: 1px; + border-style: solid; + border-color: var(--wui-color-gray-glass-002); + border-radius: 999px; + transition: + background-color var(--wui-ease-inout-power-1) var(--wui-duration-md), + border-color var(--wui-ease-inout-power-1) var(--wui-duration-md); + will-change: background-color, border-color; + } + + span:before { + position: absolute; + content: ''; + height: 16px; + width: 16px; + left: 3px; + top: 2px; + background-color: var(--wui-color-inverse-100); + transition: transform var(--wui-ease-inout-power-1) var(--wui-duration-lg); + will-change: transform; + border-radius: 50%; + } + + input:checked + span { + border-color: var(--wui-color-gray-glass-005); + background-color: var(--wui-color-blue-100); + } + + input:not(:checked) + span { + background-color: var(--wui-color-gray-glass-010); + } + + input:checked + span:before { + transform: translateX(calc(100% - 7px)); + } +`;var y0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let sN=class extends He{constructor(){super(...arguments),this.inputElementRef=v3(),this.checked=void 0}render(){return K` + + `}dispatchChangeEvent(){this.dispatchEvent(new CustomEvent("switchChange",{detail:this.inputElementRef.value?.checked,bubbles:!0,composed:!0}))}};sN.styles=[Ht,lr,mk,Fdt];y0e([ee({type:Boolean})],sN.prototype,"checked",void 0);sN=y0e([We("wui-switch")],sN);const jdt=it` + :host { + height: 100%; + } + + button { + display: flex; + align-items: center; + justify-content: center; + column-gap: var(--wui-spacing-1xs); + padding: var(--wui-spacing-xs) var(--wui-spacing-s); + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-002); + transition: background-color var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: background-color; + cursor: pointer; + } + + wui-switch { + pointer-events: none; + } +`;var w0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let iN=class extends He{constructor(){super(...arguments),this.checked=void 0}render(){return K` + + `}};iN.styles=[Ht,lr,jdt];w0e([ee({type:Boolean})],iN.prototype,"checked",void 0);iN=w0e([We("wui-certified-switch")],iN);const zdt=it` + button { + background-color: var(--wui-color-fg-300); + border-radius: var(--wui-border-radius-4xs); + width: 16px; + height: 16px; + } + + button:disabled { + background-color: var(--wui-color-bg-300); + } + + wui-icon { + color: var(--wui-color-bg-200) !important; + } + + button:focus-visible { + background-color: var(--wui-color-fg-250); + border: 1px solid var(--wui-color-accent-100); + } + + @media (hover: hover) and (pointer: fine) { + button:hover:enabled { + background-color: var(--wui-color-fg-250); + } + + button:active:enabled { + background-color: var(--wui-color-fg-225); + } + } +`;var b0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let oN=class extends He{constructor(){super(...arguments),this.icon="copy"}render(){return K` + + `}};oN.styles=[Ht,lr,zdt];b0e([ee()],oN.prototype,"icon",void 0);oN=b0e([We("wui-input-element")],oN);const Wdt=it` + :host { + position: relative; + width: 100%; + display: inline-block; + color: var(--wui-color-fg-275); + } + + input { + width: 100%; + border-radius: var(--wui-border-radius-xs); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-002); + background: var(--wui-color-gray-glass-002); + font-size: var(--wui-font-size-paragraph); + letter-spacing: var(--wui-letter-spacing-paragraph); + color: var(--wui-color-fg-100); + transition: + background-color var(--wui-ease-inout-power-1) var(--wui-duration-md), + border-color var(--wui-ease-inout-power-1) var(--wui-duration-md), + box-shadow var(--wui-ease-inout-power-1) var(--wui-duration-md); + will-change: background-color, border-color, box-shadow; + caret-color: var(--wui-color-accent-100); + } + + input:disabled { + cursor: not-allowed; + border: 1px solid var(--wui-color-gray-glass-010); + } + + input:disabled::placeholder, + input:disabled + wui-icon { + color: var(--wui-color-fg-300); + } + + input::placeholder { + color: var(--wui-color-fg-275); + } + + input:focus:enabled { + background-color: var(--wui-color-gray-glass-005); + -webkit-box-shadow: + inset 0 0 0 1px var(--wui-color-accent-100), + 0px 0px 0px 4px var(--wui-box-shadow-blue); + -moz-box-shadow: + inset 0 0 0 1px var(--wui-color-accent-100), + 0px 0px 0px 4px var(--wui-box-shadow-blue); + box-shadow: + inset 0 0 0 1px var(--wui-color-accent-100), + 0px 0px 0px 4px var(--wui-box-shadow-blue); + } + + input:hover:enabled { + background-color: var(--wui-color-gray-glass-005); + } + + wui-icon { + position: absolute; + top: 50%; + transform: translateY(-50%); + pointer-events: none; + } + + .wui-size-sm { + padding: 9px var(--wui-spacing-m) 10px var(--wui-spacing-s); + } + + wui-icon + .wui-size-sm { + padding: 9px var(--wui-spacing-m) 10px 36px; + } + + wui-icon[data-input='sm'] { + left: var(--wui-spacing-s); + } + + .wui-size-md { + padding: 15px var(--wui-spacing-m) var(--wui-spacing-l) var(--wui-spacing-m); + } + + wui-icon + .wui-size-md, + wui-loading-spinner + .wui-size-md { + padding: 10.5px var(--wui-spacing-3xl) 10.5px var(--wui-spacing-3xl); + } + + wui-icon[data-input='md'] { + left: var(--wui-spacing-l); + } + + .wui-size-lg { + padding: var(--wui-spacing-s) var(--wui-spacing-s) var(--wui-spacing-s) var(--wui-spacing-l); + letter-spacing: var(--wui-letter-spacing-medium-title); + font-size: var(--wui-font-size-medium-title); + font-weight: var(--wui-font-weight-light); + line-height: 130%; + color: var(--wui-color-fg-100); + height: 64px; + } + + .wui-padding-right-xs { + padding-right: var(--wui-spacing-xs); + } + + .wui-padding-right-s { + padding-right: var(--wui-spacing-s); + } + + .wui-padding-right-m { + padding-right: var(--wui-spacing-m); + } + + .wui-padding-right-l { + padding-right: var(--wui-spacing-l); + } + + .wui-padding-right-xl { + padding-right: var(--wui-spacing-xl); + } + + .wui-padding-right-2xl { + padding-right: var(--wui-spacing-2xl); + } + + .wui-padding-right-3xl { + padding-right: var(--wui-spacing-3xl); + } + + .wui-padding-right-4xl { + padding-right: var(--wui-spacing-4xl); + } + + .wui-padding-right-5xl { + padding-right: var(--wui-spacing-5xl); + } + + wui-icon + .wui-size-lg, + wui-loading-spinner + .wui-size-lg { + padding-left: 50px; + } + + wui-icon[data-input='lg'] { + left: var(--wui-spacing-l); + } + + .wui-size-mdl { + padding: 17.25px var(--wui-spacing-m) 17.25px var(--wui-spacing-m); + } + wui-icon + .wui-size-mdl, + wui-loading-spinner + .wui-size-mdl { + padding: 17.25px var(--wui-spacing-3xl) 17.25px 40px; + } + wui-icon[data-input='mdl'] { + left: var(--wui-spacing-m); + } + + input:placeholder-shown ~ ::slotted(wui-input-element), + input:placeholder-shown ~ ::slotted(wui-icon) { + opacity: 0; + pointer-events: none; + } + + input::-webkit-outer-spin-button, + input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; + } + + input[type='number'] { + -moz-appearance: textfield; + } + + ::slotted(wui-input-element), + ::slotted(wui-icon) { + position: absolute; + top: 50%; + transform: translateY(-50%); + } + + ::slotted(wui-input-element) { + right: var(--wui-spacing-m); + } + + ::slotted(wui-icon) { + right: 0px; + } +`;var Tf=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Gl=class extends He{constructor(){super(...arguments),this.inputElementRef=v3(),this.size="md",this.disabled=!1,this.placeholder="",this.type="text",this.value=""}render(){const e=`wui-padding-right-${this.inputRightPadding}`,r={[`wui-size-${this.size}`]:!0,[e]:!!this.inputRightPadding};return K`${this.templateIcon()} + + `}templateIcon(){return this.icon?K``:null}dispatchInputChangeEvent(){this.dispatchEvent(new CustomEvent("inputChange",{detail:this.inputElementRef.value?.value,bubbles:!0,composed:!0}))}};Gl.styles=[Ht,lr,Wdt];Tf([ee()],Gl.prototype,"size",void 0);Tf([ee()],Gl.prototype,"icon",void 0);Tf([ee({type:Boolean})],Gl.prototype,"disabled",void 0);Tf([ee()],Gl.prototype,"placeholder",void 0);Tf([ee()],Gl.prototype,"type",void 0);Tf([ee()],Gl.prototype,"keyHint",void 0);Tf([ee()],Gl.prototype,"value",void 0);Tf([ee()],Gl.prototype,"inputRightPadding",void 0);Tf([ee()],Gl.prototype,"tabIdx",void 0);Gl=Tf([We("wui-input-text")],Gl);const Vdt=it` + :host { + position: relative; + display: inline-block; + width: 100%; + } +`;var Hdt=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let CB=class extends He{constructor(){super(...arguments),this.inputComponentRef=v3()}render(){return K` + + + + `}clearValue(){const n=this.inputComponentRef.value?.inputElementRef.value;n&&(n.value="",n.focus(),n.dispatchEvent(new Event("input")))}};CB.styles=[Ht,Vdt];CB=Hdt([We("wui-search-bar")],CB);const v0e=Kr` + +`,qdt=it` + :host { + display: flex; + flex-direction: column; + align-items: center; + width: 104px; + row-gap: var(--wui-spacing-xs); + padding: var(--wui-spacing-xs) 10px; + background-color: var(--wui-color-gray-glass-002); + border-radius: clamp(0px, var(--wui-border-radius-xs), 20px); + position: relative; + } + + wui-shimmer[data-type='network'] { + border: none; + -webkit-clip-path: var(--wui-path-network); + clip-path: var(--wui-path-network); + } + + svg { + position: absolute; + width: 48px; + height: 54px; + z-index: 1; + } + + svg > path { + stroke: var(--wui-color-gray-glass-010); + stroke-width: 1px; + } + + @media (max-width: 350px) { + :host { + width: 100%; + } + } +`;var x0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let aN=class extends He{constructor(){super(...arguments),this.type="wallet"}render(){return K` + ${this.shimmerTemplate()} + + `}shimmerTemplate(){return this.type==="network"?K` + ${v0e}`:K``}};aN.styles=[Ht,lr,qdt];x0e([ee()],aN.prototype,"type",void 0);aN=x0e([We("wui-card-select-loader")],aN);const Kdt=it` + :host { + display: grid; + width: inherit; + height: inherit; + } +`;var ru=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let ec=class extends He{render(){return this.style.cssText=` + grid-template-rows: ${this.gridTemplateRows}; + grid-template-columns: ${this.gridTemplateColumns}; + justify-items: ${this.justifyItems}; + align-items: ${this.alignItems}; + justify-content: ${this.justifyContent}; + align-content: ${this.alignContent}; + column-gap: ${this.columnGap&&`var(--wui-spacing-${this.columnGap})`}; + row-gap: ${this.rowGap&&`var(--wui-spacing-${this.rowGap})`}; + gap: ${this.gap&&`var(--wui-spacing-${this.gap})`}; + padding-top: ${this.padding&&qr.getSpacingStyles(this.padding,0)}; + padding-right: ${this.padding&&qr.getSpacingStyles(this.padding,1)}; + padding-bottom: ${this.padding&&qr.getSpacingStyles(this.padding,2)}; + padding-left: ${this.padding&&qr.getSpacingStyles(this.padding,3)}; + margin-top: ${this.margin&&qr.getSpacingStyles(this.margin,0)}; + margin-right: ${this.margin&&qr.getSpacingStyles(this.margin,1)}; + margin-bottom: ${this.margin&&qr.getSpacingStyles(this.margin,2)}; + margin-left: ${this.margin&&qr.getSpacingStyles(this.margin,3)}; + `,K``}};ec.styles=[Ht,Kdt];ru([ee()],ec.prototype,"gridTemplateRows",void 0);ru([ee()],ec.prototype,"gridTemplateColumns",void 0);ru([ee()],ec.prototype,"justifyItems",void 0);ru([ee()],ec.prototype,"alignItems",void 0);ru([ee()],ec.prototype,"justifyContent",void 0);ru([ee()],ec.prototype,"alignContent",void 0);ru([ee()],ec.prototype,"columnGap",void 0);ru([ee()],ec.prototype,"rowGap",void 0);ru([ee()],ec.prototype,"gap",void 0);ru([ee()],ec.prototype,"padding",void 0);ru([ee()],ec.prototype,"margin",void 0);ec=ru([We("wui-grid")],ec);const Gdt=it` + button { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + cursor: pointer; + width: 104px; + row-gap: var(--wui-spacing-xs); + padding: var(--wui-spacing-s) var(--wui-spacing-0); + background-color: var(--wui-color-gray-glass-002); + border-radius: clamp(0px, var(--wui-border-radius-xs), 20px); + transition: + color var(--wui-duration-lg) var(--wui-ease-out-power-1), + background-color var(--wui-duration-lg) var(--wui-ease-out-power-1), + border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1); + will-change: background-color, color, border-radius; + outline: none; + border: none; + } + + button > wui-flex > wui-text { + color: var(--wui-color-fg-100); + max-width: 86px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + justify-content: center; + } + + button > wui-flex > wui-text.certified { + max-width: 66px; + } + + button:hover:enabled { + background-color: var(--wui-color-gray-glass-005); + } + + button:disabled > wui-flex > wui-text { + color: var(--wui-color-gray-glass-015); + } + + [data-selected='true'] { + background-color: var(--wui-color-accent-glass-020); + } + + @media (hover: hover) and (pointer: fine) { + [data-selected='true']:hover:enabled { + background-color: var(--wui-color-accent-glass-015); + } + } + + [data-selected='true']:active:enabled { + background-color: var(--wui-color-accent-glass-010); + } + + @media (max-width: 350px) { + button { + width: 100%; + } + } +`;var E3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Oy=class extends He{constructor(){super(),this.observer=new IntersectionObserver(()=>{}),this.visible=!1,this.imageSrc=void 0,this.imageLoading=!1,this.wallet=void 0,this.observer=new IntersectionObserver(e=>{e.forEach(n=>{n.isIntersecting?(this.visible=!0,this.fetchImageSrc()):this.visible=!1})},{threshold:.01})}firstUpdated(){this.observer.observe(this)}disconnectedCallback(){this.observer.disconnect()}render(){const e=this.wallet?.badge_type==="certified";return K` + + `}imageTemplate(){return!this.visible&&!this.imageSrc||this.imageLoading?this.shimmerTemplate():K` + + + `}shimmerTemplate(){return K``}async fetchImageSrc(){this.wallet&&(this.imageSrc=nr.getWalletImage(this.wallet),!this.imageSrc&&(this.imageLoading=!0,this.imageSrc=await nr.fetchWalletImage(this.wallet.image_id),this.imageLoading=!1))}};Oy.styles=Gdt;E3([Ne()],Oy.prototype,"visible",void 0);E3([Ne()],Oy.prototype,"imageSrc",void 0);E3([Ne()],Oy.prototype,"imageLoading",void 0);E3([ee()],Oy.prototype,"wallet",void 0);Oy=E3([We("w3m-all-wallets-list-item")],Oy);const Zdt=it` + wui-grid { + max-height: clamp(360px, 400px, 80vh); + overflow: scroll; + scrollbar-width: none; + grid-auto-rows: min-content; + grid-template-columns: repeat(auto-fill, 104px); + } + + @media (max-width: 350px) { + wui-grid { + grid-template-columns: repeat(2, 1fr); + } + } + + wui-grid[data-scroll='false'] { + overflow: hidden; + } + + wui-grid::-webkit-scrollbar { + display: none; + } + + wui-loading-spinner { + padding-top: var(--wui-spacing-l); + padding-bottom: var(--wui-spacing-l); + justify-content: center; + grid-column: 1 / span 4; + } +`;var gx=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const pte="local-paginator";let m0=class extends He{constructor(){super(),this.unsubscribe=[],this.paginationObserver=void 0,this.loading=!mt.state.wallets.length,this.wallets=mt.state.wallets,this.recommended=mt.state.recommended,this.featured=mt.state.featured,this.filteredWallets=mt.state.filteredWallets,this.unsubscribe.push(mt.subscribeKey("wallets",e=>this.wallets=e),mt.subscribeKey("recommended",e=>this.recommended=e),mt.subscribeKey("featured",e=>this.featured=e),mt.subscribeKey("filteredWallets",e=>this.filteredWallets=e))}firstUpdated(){this.initialFetch(),this.createPaginationObserver()}disconnectedCallback(){this.unsubscribe.forEach(e=>e()),this.paginationObserver?.disconnect()}render(){return K` + + ${this.loading?this.shimmerTemplate(16):this.walletsTemplate()} + ${this.paginationLoaderTemplate()} + + `}async initialFetch(){this.loading=!0;const e=this.shadowRoot?.querySelector("wui-grid");e&&(await mt.fetchWalletsByPage({page:1}),await e.animate([{opacity:1},{opacity:0}],{duration:200,fill:"forwards",easing:"ease"}).finished,this.loading=!1,e.animate([{opacity:0},{opacity:1}],{duration:200,fill:"forwards",easing:"ease"}))}shimmerTemplate(e,n){return[...Array(e)].map(()=>K` + + `)}getWallets(){const e=[...this.featured,...this.recommended];this.filteredWallets?.length>0?e.push(...this.filteredWallets):e.push(...this.wallets);const n=De.uniqueBy(e,"id"),r=pf.markWalletsAsInstalled(n);return pf.markWalletsWithDisplayIndex(r)}walletsTemplate(){return this.getWallets().map(n=>K` + this.onConnectWallet(n)} + .wallet=${n} + > + `)}paginationLoaderTemplate(){const{wallets:e,recommended:n,featured:r,count:s}=mt.state,i=window.innerWidth<352?3:4,o=e.length+n.length;let c=Math.ceil(o/i)*i-o+i;return c-=e.length?r.length%i:0,s===0&&r.length>0?null:s===0||[...r,...e,...n].length{if(n?.isIntersecting&&!this.loading){const{page:r,count:s,wallets:i}=mt.state;i.length=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let i1=class extends He{constructor(){super(...arguments),this.prevQuery="",this.prevBadge=void 0,this.loading=!0,this.query=""}render(){return this.onSearch(),this.loading?K``:this.walletsTemplate()}async onSearch(){(this.query.trim()!==this.prevQuery.trim()||this.badge!==this.prevBadge)&&(this.prevQuery=this.query,this.prevBadge=this.badge,this.loading=!0,await mt.searchWallet({search:this.query,badge:this.badge}),this.loading=!1)}walletsTemplate(){const{search:e}=mt.state,n=pf.markWalletsAsInstalled(e);return e.length?K` + + ${n.map(r=>K` + this.onConnectWallet(r)} + .wallet=${r} + data-testid="wallet-search-item-${r.id}" + > + `)} + + `:K` + + + + No Wallet found + + + `}onConnectWallet(e){ke.selectWalletConnector(e)}};i1.styles=Ydt;Rk([Ne()],i1.prototype,"loading",void 0);Rk([ee()],i1.prototype,"query",void 0);Rk([ee()],i1.prototype,"badge",void 0);i1=Rk([We("w3m-all-wallets-search")],i1);var IW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let S_=class extends He{constructor(){super(...arguments),this.search="",this.onDebouncedSearch=De.debounce(e=>{this.search=e})}render(){const e=this.search.length>=2;return K` + + + + ${this.qrButtonTemplate()} + + ${e||this.badge?K``:K``} + `}onInputChange(e){this.onDebouncedSearch(e.detail)}onClick(){if(this.badge==="certified"){this.badge=void 0;return}this.badge="certified",Wn.showSvg("Only WalletConnect certified",{icon:"walletConnectBrown",iconColor:"accent-100"})}qrButtonTemplate(){return De.isMobile()?K` + + `:null}onWalletConnectQr(){ze.push("ConnectingWalletConnect")}};IW([Ne()],S_.prototype,"search",void 0);IW([Ne()],S_.prototype,"badge",void 0);S_=IW([We("w3m-all-wallets-view")],S_);const Xdt=it` + button { + column-gap: var(--wui-spacing-s); + padding: 16.5px var(--wui-spacing-l) 16.5px var(--wui-spacing-xs); + width: 100%; + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + color: var(--wui-color-fg-100); + justify-content: center; + align-items: center; + } + + button:disabled { + background-color: var(--wui-color-gray-glass-015); + color: var(--wui-color-gray-glass-015); + } +`;var Ok=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let o1=class extends He{constructor(){super(...arguments),this.text="",this.disabled=!1,this.tabIdx=void 0}render(){return K` + + `}};o1.styles=[Ht,lr,Xdt];Ok([ee()],o1.prototype,"text",void 0);Ok([ee({type:Boolean})],o1.prototype,"disabled",void 0);Ok([ee()],o1.prototype,"tabIdx",void 0);o1=Ok([We("wui-list-button")],o1);const Qdt=it` + :host { + position: relative; + display: inline-block; + } + + wui-text { + margin: var(--wui-spacing-xxs) var(--wui-spacing-m) var(--wui-spacing-0) var(--wui-spacing-m); + } +`;var C3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let $y=class extends He{constructor(){super(...arguments),this.disabled=!1}render(){return K` + + ${this.templateError()} + `}templateError(){return this.errorMessage?K`${this.errorMessage}`:null}};$y.styles=[Ht,Qdt];C3([ee()],$y.prototype,"errorMessage",void 0);C3([ee({type:Boolean})],$y.prototype,"disabled",void 0);C3([ee()],$y.prototype,"value",void 0);C3([ee()],$y.prototype,"tabIdx",void 0);$y=C3([We("wui-email-input")],$y);const Jdt=it` + wui-separator { + margin: var(--wui-spacing-s) calc(var(--wui-spacing-s) * -1); + width: calc(100% + var(--wui-spacing-s) * 2); + } + + wui-email-input { + width: 100%; + } + + form { + width: 100%; + display: block; + position: relative; + } + + wui-icon-link, + wui-loading-spinner { + position: absolute; + top: 50%; + transform: translateY(-50%); + } + + wui-icon-link { + right: var(--wui-spacing-xs); + } + + wui-loading-spinner { + right: var(--wui-spacing-m); + } + + wui-text { + margin: var(--wui-spacing-xxs) var(--wui-spacing-m) var(--wui-spacing-0) var(--wui-spacing-m); + } +`;var mx=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let y0=class extends He{constructor(){super(),this.unsubscribe=[],this.formRef=v3(),this.email="",this.loading=!1,this.error="",this.remoteFeatures=_e.state.remoteFeatures,this.unsubscribe.push(_e.subscribeKey("remoteFeatures",e=>{this.remoteFeatures=e}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}firstUpdated(){this.formRef.value?.addEventListener("keydown",e=>{e.key==="Enter"&&this.onSubmitEmail(e)})}render(){const e=Ue.hasAnyConnection(ye.CONNECTOR_ID.AUTH);return K` +
+ + + + ${this.submitButtonTemplate()}${this.loadingTemplate()} + +
+ ${this.templateError()} + `}submitButtonTemplate(){return!this.loading&&this.email.length>3?K` + + + `:null}loadingTemplate(){return this.loading?K``:null}templateError(){return this.error?K`${this.error}`:null}onEmailInputChange(e){this.email=e.detail.trim(),this.error=""}async onSubmitEmail(e){if(!ye.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(r=>r===G.state.activeChain)){const r=G.getFirstCaipNetworkSupportsAuthConnector();if(r){ze.push("SwitchNetwork",{network:r});return}}try{if(this.loading)return;this.loading=!0,e.preventDefault();const r=ke.getAuthConnector();if(!r)throw new Error("w3m-email-login-widget: Auth connector not found");const{action:s}=await r.provider.connectEmail({email:this.email});if(Lt.sendEvent({type:"track",event:"EMAIL_SUBMITTED"}),s==="VERIFY_OTP")Lt.sendEvent({type:"track",event:"EMAIL_VERIFICATION_CODE_SENT"}),ze.push("EmailVerifyOtp",{email:this.email});else if(s==="VERIFY_DEVICE")ze.push("EmailVerifyDevice",{email:this.email});else if(s==="CONNECT"){const i=this.remoteFeatures?.multiWallet;await Ue.connectExternal(r,G.state.activeChain),i?(ze.replace("ProfileWallets"),Wn.showSuccess("New Wallet Added")):ze.replace("Account")}}catch(r){De.parseError(r)?.includes("Invalid email")?this.error="Invalid email. Try again.":Wn.showError(r)}finally{this.loading=!1}}onFocusEvent(){Lt.sendEvent({type:"track",event:"EMAIL_LOGIN_SELECTED"})}};y0.styles=Jdt;mx([ee()],y0.prototype,"tabIdx",void 0);mx([Ne()],y0.prototype,"email",void 0);mx([Ne()],y0.prototype,"loading",void 0);mx([Ne()],y0.prototype,"error",void 0);mx([Ne()],y0.prototype,"remoteFeatures",void 0);y0=mx([We("w3m-email-login-widget")],y0);const eft=it` + label { + display: flex; + align-items: center; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + column-gap: var(--wui-spacing-1xs); + } + + label > input[type='checkbox'] { + height: 0; + width: 0; + opacity: 0; + pointer-events: none; + position: absolute; + } + + label > span { + width: var(--wui-spacing-xl); + height: var(--wui-spacing-xl); + min-width: var(--wui-spacing-xl); + min-height: var(--wui-spacing-xl); + border-radius: var(--wui-border-radius-3xs); + border-width: 1px; + border-style: solid; + border-color: var(--wui-color-gray-glass-010); + display: flex; + align-items: center; + justify-content: center; + transition: background-color var(--wui-ease-out-power-1) var(--wui-duration-lg); + will-change: background-color; + } + + label > span:hover, + label > input[type='checkbox']:focus-visible + span { + background-color: var(--wui-color-gray-glass-010); + } + + label input[type='checkbox']:checked + span { + background-color: var(--wui-color-blue-base-90); + } + + label > span > wui-icon { + opacity: 0; + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-lg); + will-change: opacity; + } + + label > input[type='checkbox']:checked + span wui-icon { + opacity: 1; + } +`;var E0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let cN=class extends He{constructor(){super(...arguments),this.inputElementRef=v3(),this.checked=void 0}render(){return K` + + `}dispatchChangeEvent(){this.dispatchEvent(new CustomEvent("checkboxChange",{detail:this.inputElementRef.value?.checked,bubbles:!0,composed:!0}))}};cN.styles=[Ht,eft];E0e([ee({type:Boolean})],cN.prototype,"checked",void 0);cN=E0e([We("wui-checkbox")],cN);const tft=it` + :host { + display: flex; + align-items: center; + justify-content: center; + } + wui-checkbox { + padding: var(--wui-spacing-s); + } + a { + text-decoration: none; + color: var(--wui-color-fg-150); + font-weight: 500; + } +`;var C0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let lN=class extends He{constructor(){super(),this.unsubscribe=[],this.checked=Vm.state.isLegalCheckboxChecked,this.unsubscribe.push(Vm.subscribeKey("isLegalCheckboxChecked",e=>{this.checked=e}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const{termsConditionsUrl:e,privacyPolicyUrl:n}=_e.state,r=_e.state.features?.legalCheckbox;return!e&&!n||!r?null:K` + + + I agree to our ${this.termsTemplate()} ${this.andTemplate()} ${this.privacyTemplate()} + + + `}andTemplate(){const{termsConditionsUrl:e,privacyPolicyUrl:n}=_e.state;return e&&n?"and":""}termsTemplate(){const{termsConditionsUrl:e}=_e.state;return e?K`terms of service`:null}privacyTemplate(){const{privacyPolicyUrl:e}=_e.state;return e?K`privacy policy`:null}onCheckboxChange(){Vm.setIsLegalCheckboxChecked(!this.checked)}};lN.styles=[tft];C0e([Ne()],lN.prototype,"checked",void 0);lN=C0e([We("w3m-legal-checkbox")],lN);const XOt=/[.*+?^${}()|[\]\\]/gu,QOt=/[0-9,.]/u,nft="https://reown.com",rft=it` + .reown-logo { + height: var(--wui-spacing-xxl); + } + + a { + text-decoration: none; + cursor: pointer; + } + + a:hover { + opacity: 0.9; + } +`;var sft=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let _B=class extends He{render(){return K` + + + UX by + + + + `}};_B.styles=[Ht,lr,rft];_B=sft([We("wui-ux-by-reown")],_B);const ift=it` + :host > wui-flex { + background-color: var(--wui-color-gray-glass-005); + } + + :host wui-ux-by-reown { + padding-top: 0; + } + + :host wui-ux-by-reown.branding-only { + padding-top: var(--wui-spacing-m); + } + + a { + text-decoration: none; + color: var(--wui-color-fg-175); + font-weight: 500; + } +`;var _0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let uN=class extends He{constructor(){super(),this.unsubscribe=[],this.remoteFeatures=_e.state.remoteFeatures,this.unsubscribe.push(_e.subscribeKey("remoteFeatures",e=>this.remoteFeatures=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const{termsConditionsUrl:e,privacyPolicyUrl:n}=_e.state,r=_e.state.features?.legalCheckbox;return!e&&!n||r?K` + ${this.reownBrandingTemplate(!0)} + `:K` + + + + By connecting your wallet, you agree to our
+ ${this.termsTemplate()} ${this.andTemplate()} ${this.privacyTemplate()} +
+
+ ${this.reownBrandingTemplate()} +
+ `}andTemplate(){const{termsConditionsUrl:e,privacyPolicyUrl:n}=_e.state;return e&&n?"and":""}termsTemplate(){const{termsConditionsUrl:e}=_e.state;return e?K`Terms of Service`:null}privacyTemplate(){const{privacyPolicyUrl:e}=_e.state;return e?K`Privacy Policy`:null}reownBrandingTemplate(e=!1){return this.remoteFeatures?.reownBranding?e?K``:K``:null}};uN.styles=[ift];_0e([Ne()],uN.prototype,"remoteFeatures",void 0);uN=_0e([We("w3m-legal-footer")],uN);const oft=it` + :host { + display: flex; + justify-content: center; + align-items: center; + width: 40px; + height: 40px; + border-radius: var(--wui-border-radius-3xl); + border: 1px solid var(--wui-color-gray-glass-005); + overflow: hidden; + } + + wui-icon { + width: 100%; + height: 100%; + } +`;var S0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let dN=class extends He{constructor(){super(...arguments),this.logo="google"}render(){return K` `}};dN.styles=[Ht,oft];S0e([ee()],dN.prototype,"logo",void 0);dN=S0e([We("wui-logo")],dN);const aft=it` + button { + column-gap: var(--wui-spacing-s); + padding: 7px var(--wui-spacing-l) 7px var(--wui-spacing-xs); + width: 100%; + justify-content: flex-start; + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + color: var(--wui-color-fg-100); + } + + wui-text { + text-transform: capitalize; + } + + wui-text[data-align='left'] { + display: flex; + flex: 1; + } + + wui-text[data-align='center'] { + display: flex; + flex: 1; + justify-content: center; + } + + .invisible { + opacity: 0; + pointer-events: none; + } + + button:disabled { + background-color: var(--wui-color-gray-glass-015); + color: var(--wui-color-gray-glass-015); + } +`;var yx=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let w0=class extends He{constructor(){super(...arguments),this.logo="google",this.name="Continue with google",this.align="left",this.disabled=!1}render(){return K` + + `}templatePlacement(){return this.align==="center"?K` `:null}};w0.styles=[Ht,lr,aft];yx([ee()],w0.prototype,"logo",void 0);yx([ee()],w0.prototype,"name",void 0);yx([ee()],w0.prototype,"align",void 0);yx([ee()],w0.prototype,"tabIdx",void 0);yx([ee({type:Boolean})],w0.prototype,"disabled",void 0);w0=yx([We("wui-list-social")],w0);const cft=it` + :host { + display: block; + width: 100%; + } + + button { + width: 100%; + height: 56px; + background: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + } +`;var $k=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let a1=class extends He{constructor(){super(...arguments),this.logo="google",this.disabled=!1,this.tabIdx=void 0}render(){return K` + + `}};a1.styles=[Ht,lr,cft];$k([ee()],a1.prototype,"logo",void 0);$k([ee({type:Boolean})],a1.prototype,"disabled",void 0);$k([ee()],a1.prototype,"tabIdx",void 0);a1=$k([We("wui-logo-select")],a1);const lft=it` + wui-separator { + margin: var(--wui-spacing-m) calc(var(--wui-spacing-m) * -1) var(--wui-spacing-m) + calc(var(--wui-spacing-m) * -1); + width: calc(100% + var(--wui-spacing-s) * 2); + } +`;var mw=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const gte=2,mte=6;let ip=class extends He{constructor(){super(),this.unsubscribe=[],this.walletGuide="get-started",this.tabIdx=void 0,this.connectors=ke.state.connectors,this.remoteFeatures=_e.state.remoteFeatures,this.authConnector=this.connectors.find(e=>e.type==="AUTH"),this.isPwaLoading=!1,this.unsubscribe.push(ke.subscribeKey("connectors",e=>{this.connectors=e,this.authConnector=this.connectors.find(n=>n.type==="AUTH")}),_e.subscribeKey("remoteFeatures",e=>this.remoteFeatures=e))}connectedCallback(){super.connectedCallback(),this.handlePwaFrameLoad()}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return K` + + ${this.topViewTemplate()}${this.bottomViewTemplate()} + + `}topViewTemplate(){const e=this.walletGuide==="explore";let n=this.remoteFeatures?.socials;return!n&&e?(n=wn.DEFAULT_SOCIALS,this.renderTopViewContent(n)):n?this.renderTopViewContent(n):null}renderTopViewContent(e){return e.length===2?K` + ${e.slice(0,gte).map(n=>K`{this.onSocialClick(n)}} + logo=${n} + tabIdx=${rt(this.tabIdx)} + ?disabled=${this.isPwaLoading||this.hasConnection()} + >`)} + `:K` {this.onSocialClick(e[0])}} + logo=${rt(e[0])} + align="center" + name=${`Continue with ${e[0]}`} + tabIdx=${rt(this.tabIdx)} + ?disabled=${this.isPwaLoading||this.hasConnection()} + >`}bottomViewTemplate(){let e=this.remoteFeatures?.socials;const n=this.walletGuide==="explore";return(!this.authConnector||!e||e.length===0)&&n&&(e=wn.DEFAULT_SOCIALS),!e||e.length<=gte?null:e&&e.length>mte?K` + ${e.slice(1,mte-1).map(s=>K`{this.onSocialClick(s)}} + logo=${s} + tabIdx=${rt(this.tabIdx)} + ?focusable=${this.tabIdx!==void 0&&this.tabIdx>=0} + ?disabled=${this.isPwaLoading||this.hasConnection()} + >`)} + + `:e?K` + ${e.slice(1,e.length).map(s=>K`{this.onSocialClick(s)}} + logo=${s} + tabIdx=${rt(this.tabIdx)} + ?focusable=${this.tabIdx!==void 0&&this.tabIdx>=0} + ?disabled=${this.isPwaLoading||this.hasConnection()} + >`)} + `:null}onMoreSocialsClick(){ze.push("ConnectSocials")}async onSocialClick(e){if(!ye.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(r=>r===G.state.activeChain)){const r=G.getFirstCaipNetworkSupportsAuthConnector();if(r){ze.push("SwitchNetwork",{network:r});return}}e&&await vut(e)}async handlePwaFrameLoad(){if(De.isPWA()){this.isPwaLoading=!0;try{this.authConnector?.provider instanceof bge&&await this.authConnector.provider.init()}catch(e){Xr.open({displayMessage:"Error loading embedded wallet in PWA",debugMessage:e.message},"error")}finally{this.isPwaLoading=!1}}}hasConnection(){return Ue.hasAnyConnection(ye.CONNECTOR_ID.AUTH)}};ip.styles=lft;mw([ee()],ip.prototype,"walletGuide",void 0);mw([ee()],ip.prototype,"tabIdx",void 0);mw([Ne()],ip.prototype,"connectors",void 0);mw([Ne()],ip.prototype,"remoteFeatures",void 0);mw([Ne()],ip.prototype,"authConnector",void 0);mw([Ne()],ip.prototype,"isPwaLoading",void 0);ip=mw([We("w3m-social-login-widget")],ip);const uft=it` + a { + border: 1px solid var(--wui-color-gray-glass-010); + border-radius: var(--wui-border-radius-3xl); + } + + wui-image { + border-radius: var(--wui-border-radius-3xl); + overflow: hidden; + } + + a.disabled > wui-icon:not(.image-icon), + a.disabled > wui-image { + filter: grayscale(1); + } + + a[data-variant='fill'] { + color: var(--wui-color-inverse-100); + background-color: var(--wui-color-accent-100); + } + + a[data-variant='shade'], + a[data-variant='shadeSmall'] { + background-color: transparent; + background-color: var(--wui-color-gray-glass-010); + color: var(--wui-color-fg-200); + } + + a[data-variant='success'] { + column-gap: var(--wui-spacing-xxs); + border: 1px solid var(--wui-color-success-glass-010); + background-color: var(--wui-color-success-glass-010); + color: var(--wui-color-success-100); + } + + a[data-variant='error'] { + column-gap: var(--wui-spacing-xxs); + border: 1px solid var(--wui-color-error-glass-010); + background-color: var(--wui-color-error-glass-010); + color: var(--wui-color-error-100); + } + + a[data-variant='transparent'] { + column-gap: var(--wui-spacing-xxs); + background-color: transparent; + color: var(--wui-color-fg-150); + } + + a[data-variant='transparent'], + a[data-variant='success'], + a[data-variant='shadeSmall'], + a[data-variant='error'] { + padding: 7px var(--wui-spacing-s) 7px 10px; + } + + a[data-variant='transparent']:has(wui-text:first-child), + a[data-variant='success']:has(wui-text:first-child), + a[data-variant='shadeSmall']:has(wui-text:first-child), + a[data-variant='error']:has(wui-text:first-child) { + padding: 7px var(--wui-spacing-s); + } + + a[data-variant='fill'], + a[data-variant='shade'] { + column-gap: var(--wui-spacing-xs); + padding: var(--wui-spacing-xxs) var(--wui-spacing-m) var(--wui-spacing-xxs) + var(--wui-spacing-xs); + } + + a[data-variant='fill']:has(wui-text:first-child), + a[data-variant='shade']:has(wui-text:first-child) { + padding: 9px var(--wui-spacing-m) 9px var(--wui-spacing-m); + } + + a[data-variant='fill'] > wui-image, + a[data-variant='shade'] > wui-image { + width: 24px; + height: 24px; + } + + a[data-variant='fill'] > wui-image { + box-shadow: inset 0 0 0 1px var(--wui-color-accent-090); + } + + a[data-variant='shade'] > wui-image, + a[data-variant='shadeSmall'] > wui-image { + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + } + + a[data-variant='fill'] > wui-icon:not(.image-icon), + a[data-variant='shade'] > wui-icon:not(.image-icon) { + width: 14px; + height: 14px; + } + + a[data-variant='transparent'] > wui-image, + a[data-variant='success'] > wui-image, + a[data-variant='shadeSmall'] > wui-image, + a[data-variant='error'] > wui-image { + width: 14px; + height: 14px; + } + + a[data-variant='transparent'] > wui-icon:not(.image-icon), + a[data-variant='success'] > wui-icon:not(.image-icon), + a[data-variant='shadeSmall'] > wui-icon:not(.image-icon), + a[data-variant='error'] > wui-icon:not(.image-icon) { + width: 12px; + height: 12px; + } + + a[data-variant='fill']:focus-visible { + background-color: var(--wui-color-accent-090); + } + + a[data-variant='shade']:focus-visible, + a[data-variant='shadeSmall']:focus-visible { + background-color: var(--wui-color-gray-glass-015); + } + + a[data-variant='transparent']:focus-visible { + background-color: var(--wui-color-gray-glass-005); + } + + a[data-variant='success']:focus-visible { + background-color: var(--wui-color-success-glass-015); + } + + a[data-variant='error']:focus-visible { + background-color: var(--wui-color-error-glass-015); + } + + a.disabled { + color: var(--wui-color-gray-glass-015); + background-color: var(--wui-color-gray-glass-015); + pointer-events: none; + } + + @media (hover: hover) and (pointer: fine) { + a[data-variant='fill']:hover { + background-color: var(--wui-color-accent-090); + } + + a[data-variant='shade']:hover, + a[data-variant='shadeSmall']:hover { + background-color: var(--wui-color-gray-glass-015); + } + + a[data-variant='transparent']:hover { + background-color: var(--wui-color-gray-glass-005); + } + + a[data-variant='success']:hover { + background-color: var(--wui-color-success-glass-015); + } + + a[data-variant='error']:hover { + background-color: var(--wui-color-error-glass-015); + } + } + + a[data-variant='fill']:active { + background-color: var(--wui-color-accent-080); + } + + a[data-variant='shade']:active, + a[data-variant='shadeSmall']:active { + background-color: var(--wui-color-gray-glass-020); + } + + a[data-variant='transparent']:active { + background-color: var(--wui-color-gray-glass-010); + } + + a[data-variant='success']:active { + background-color: var(--wui-color-success-glass-020); + } + + a[data-variant='error']:active { + background-color: var(--wui-color-error-glass-020); + } +`;var xp=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let ad=class extends He{constructor(){super(...arguments),this.variant="fill",this.imageSrc=void 0,this.imageIcon=void 0,this.imageIconSize="md",this.disabled=!1,this.icon="externalLink",this.href="",this.text=void 0}render(){const n=this.variant==="success"||this.variant==="transparent"||this.variant==="shadeSmall"?"small-600":"paragraph-600";return K` + + ${this.imageTemplate()} + + ${this.title?this.title:qr.getHostName(this.href)} + + + + `}imageTemplate(){return this.imageSrc?K``:this.imageIcon?K``:null}};ad.styles=[Ht,lr,uft];xp([ee()],ad.prototype,"variant",void 0);xp([ee()],ad.prototype,"imageSrc",void 0);xp([ee()],ad.prototype,"imageIcon",void 0);xp([ee()],ad.prototype,"imageIconSize",void 0);xp([ee({type:Boolean})],ad.prototype,"disabled",void 0);xp([ee()],ad.prototype,"icon",void 0);xp([ee()],ad.prototype,"href",void 0);xp([ee()],ad.prototype,"text",void 0);ad=xp([We("wui-chip")],ad);const dft=it` + wui-flex { + width: 100%; + } + + .wallet-guide { + width: 100%; + } + + .chip-box { + width: fit-content; + background-color: var(--wui-color-gray-glass-005); + border-radius: var(--wui-border-radius-3xl); + } +`;var TW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let A_=class extends He{constructor(){super(...arguments),this.walletGuide="get-started"}render(){return this.walletGuide==="explore"?K` + + Looking for a self-custody wallet? + + + + + + `:K` + Haven't got a wallet? + + Get started + + `}onGetStarted(){ze.push("Create")}};A_.styles=dft;TW([ee()],A_.prototype,"tabIdx",void 0);TW([ee()],A_.prototype,"walletGuide",void 0);A_=TW([We("w3m-wallet-guide")],A_);const fft=it` + :host { + position: relative; + border-radius: var(--wui-border-radius-xxs); + width: 40px; + height: 40px; + overflow: hidden; + background: var(--wui-color-gray-glass-002); + display: flex; + justify-content: center; + align-items: center; + flex-wrap: wrap; + gap: var(--wui-spacing-4xs); + padding: 3.75px !important; + } + + :host::after { + content: ''; + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + border-radius: inherit; + border: 1px solid var(--wui-color-gray-glass-010); + pointer-events: none; + } + + :host > wui-wallet-image { + width: 14px; + height: 14px; + border-radius: var(--wui-border-radius-5xs); + } + + :host > wui-flex { + padding: 2px; + position: fixed; + overflow: hidden; + left: 34px; + bottom: 8px; + background: var(--dark-background-150, #1e1f1f); + border-radius: 50%; + z-index: 2; + display: flex; + } +`;var A0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const xD=4;let fN=class extends He{constructor(){super(...arguments),this.walletImages=[]}render(){const e=this.walletImages.lengthK` + + `)} + ${e?[...Array(xD-this.walletImages.length)].map(()=>K` `):null} + + + `}};fN.styles=[Ht,fft];A0e([ee({type:Array})],fN.prototype,"walletImages",void 0);fN=A0e([We("wui-all-wallets-image")],fN);const hft=it` + button { + column-gap: var(--wui-spacing-s); + padding: 7px var(--wui-spacing-l) 7px var(--wui-spacing-xs); + width: 100%; + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + color: var(--wui-color-fg-100); + } + + button > wui-text:nth-child(2) { + display: flex; + flex: 1; + } + + button:disabled { + background-color: var(--wui-color-gray-glass-015); + color: var(--wui-color-gray-glass-015); + } + + button:disabled > wui-tag { + background-color: var(--wui-color-gray-glass-010); + color: var(--wui-color-fg-300); + } + + wui-icon { + color: var(--wui-color-fg-200) !important; + } +`;var ac=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Ro=class extends He{constructor(){super(...arguments),this.walletImages=[],this.imageSrc="",this.name="",this.tabIdx=void 0,this.installed=!1,this.disabled=!1,this.showAllWallets=!1,this.loading=!1,this.loadingSpinnerColor="accent-100"}render(){return K` + + `}templateAllWallets(){return this.showAllWallets&&this.imageSrc?K` `:this.showAllWallets&&this.walletIcon?K` `:null}templateWalletImage(){return!this.showAllWallets&&this.imageSrc?K``:!this.showAllWallets&&!this.imageSrc?K``:null}templateStatus(){return this.loading?K``:this.tagLabel&&this.tagVariant?K`${this.tagLabel}`:this.icon?K``:null}};Ro.styles=[Ht,lr,hft];ac([ee({type:Array})],Ro.prototype,"walletImages",void 0);ac([ee()],Ro.prototype,"imageSrc",void 0);ac([ee()],Ro.prototype,"name",void 0);ac([ee()],Ro.prototype,"tagLabel",void 0);ac([ee()],Ro.prototype,"tagVariant",void 0);ac([ee()],Ro.prototype,"icon",void 0);ac([ee()],Ro.prototype,"walletIcon",void 0);ac([ee()],Ro.prototype,"tabIdx",void 0);ac([ee({type:Boolean})],Ro.prototype,"installed",void 0);ac([ee({type:Boolean})],Ro.prototype,"disabled",void 0);ac([ee({type:Boolean})],Ro.prototype,"showAllWallets",void 0);ac([ee({type:Boolean})],Ro.prototype,"loading",void 0);ac([ee({type:String})],Ro.prototype,"loadingSpinnerColor",void 0);Ro=ac([We("wui-list-wallet")],Ro);var wx=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Dy=class extends He{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=ke.state.connectors,this.count=mt.state.count,this.filteredCount=mt.state.filteredWallets.length,this.isFetchingRecommendedWallets=mt.state.isFetchingRecommendedWallets,this.unsubscribe.push(ke.subscribeKey("connectors",e=>this.connectors=e),mt.subscribeKey("count",e=>this.count=e),mt.subscribeKey("filteredWallets",e=>this.filteredCount=e.length),mt.subscribeKey("isFetchingRecommendedWallets",e=>this.isFetchingRecommendedWallets=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const e=this.connectors.find(l=>l.id==="walletConnect"),{allWallets:n}=_e.state;if(!e||n==="HIDE"||n==="ONLY_MOBILE"&&!De.isMobile())return null;const r=mt.state.featured.length,s=this.count+r,i=s<10?s:Math.floor(s/10)*10,o=this.filteredCount>0?this.filteredCount:i;let a=`${o}`;this.filteredCount>0?a=`${this.filteredCount}`:o + `}onAllWallets(){Lt.sendEvent({type:"track",event:"CLICK_ALL_WALLETS"}),ze.push("AllWallets")}};wx([ee()],Dy.prototype,"tabIdx",void 0);wx([Ne()],Dy.prototype,"connectors",void 0);wx([Ne()],Dy.prototype,"count",void 0);wx([Ne()],Dy.prototype,"filteredCount",void 0);wx([Ne()],Dy.prototype,"isFetchingRecommendedWallets",void 0);Dy=wx([We("w3m-all-wallets-widget")],Dy);var Dk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let I_=class extends He{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=ke.state.connectors,this.connections=Ue.state.connections,this.unsubscribe.push(ke.subscribeKey("connectors",e=>this.connectors=e),Ue.subscribeKey("connections",e=>this.connections=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const e=this.connectors.filter(n=>n.type==="ANNOUNCED");return e?.length?K` + + ${e.filter(qu.showConnector).map(n=>{const s=(this.connections.get(n.chain)??[]).some(i=>Jn.isLowerCaseMatch(i.connectorId,n.id));return K` + this.onConnector(n)} + tagVariant=${s?"shade":"success"} + tagLabel=${s?"connected":"installed"} + data-testid=${`wallet-selector-${n.id}`} + .installed=${!0} + tabIdx=${rt(this.tabIdx)} + > + + `})} + + `:(this.style.cssText="display: none",null)}onConnector(e){e.id==="walletConnect"?De.isMobile()?ze.push("AllWallets"):ze.push("ConnectingWalletConnect"):ze.push("ConnectingExternal",{connector:e})}};Dk([ee()],I_.prototype,"tabIdx",void 0);Dk([Ne()],I_.prototype,"connectors",void 0);Dk([Ne()],I_.prototype,"connections",void 0);I_=Dk([We("w3m-connect-announced-widget")],I_);var Mk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let T_=class extends He{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=ke.state.connectors,this.loading=!1,this.unsubscribe.push(ke.subscribeKey("connectors",e=>this.connectors=e)),De.isTelegram()&&De.isIos()&&(this.loading=!Ue.state.wcUri,this.unsubscribe.push(Ue.subscribeKey("wcUri",e=>this.loading=!e)))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const{customWallets:e}=_e.state;if(!e?.length)return this.style.cssText="display: none",null;const n=this.filterOutDuplicateWallets(e),r=Ue.hasAnyConnection(ye.CONNECTOR_ID.WALLET_CONNECT);return K` + ${n.map(s=>K` + this.onConnectWallet(s)} + data-testid=${`wallet-selector-${s.id}`} + tabIdx=${rt(this.tabIdx)} + ?loading=${this.loading} + ?disabled=${r} + > + + `)} + `}filterOutDuplicateWallets(e){const n=Ge.getRecentWallets(),r=this.connectors.map(a=>a.info?.rdns).filter(Boolean),s=n.map(a=>a.rdns).filter(Boolean),i=r.concat(s);if(i.includes("io.metamask.mobile")&&De.isMobile()){const a=i.indexOf("io.metamask.mobile");i[a]="io.metamask"}return e.filter(a=>!i.includes(String(a?.rdns)))}onConnectWallet(e){this.loading||ze.push("ConnectingWalletConnect",{wallet:e})}};Mk([ee()],T_.prototype,"tabIdx",void 0);Mk([Ne()],T_.prototype,"connectors",void 0);Mk([Ne()],T_.prototype,"loading",void 0);T_=Mk([We("w3m-connect-custom-widget")],T_);var NW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let hN=class extends He{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=ke.state.connectors,this.unsubscribe.push(ke.subscribeKey("connectors",e=>this.connectors=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const r=this.connectors.filter(i=>i.type==="EXTERNAL").filter(qu.showConnector).filter(i=>i.id!==ye.CONNECTOR_ID.COINBASE_SDK);if(!r?.length)return this.style.cssText="display: none",null;const s=Ue.hasAnyConnection(ye.CONNECTOR_ID.WALLET_CONNECT);return K` + + ${r.map(i=>K` + this.onConnector(i)} + tabIdx=${rt(this.tabIdx)} + ?disabled=${s} + > + + `)} + + `}onConnector(e){ze.push("ConnectingExternal",{connector:e})}};NW([ee()],hN.prototype,"tabIdx",void 0);NW([Ne()],hN.prototype,"connectors",void 0);hN=NW([We("w3m-connect-external-widget")],hN);var PW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let pN=class extends He{constructor(){super(...arguments),this.tabIdx=void 0,this.wallets=[]}render(){if(!this.wallets.length)return this.style.cssText="display: none",null;const e=Ue.hasAnyConnection(ye.CONNECTOR_ID.WALLET_CONNECT);return K` + + ${this.wallets.map(n=>K` + this.onConnectWallet(n)} + tabIdx=${rt(this.tabIdx)} + ?disabled=${e} + > + + `)} + + `}onConnectWallet(e){ke.selectWalletConnector(e)}};PW([ee()],pN.prototype,"tabIdx",void 0);PW([ee()],pN.prototype,"wallets",void 0);pN=PW([We("w3m-connect-featured-widget")],pN);var Lk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let N_=class extends He{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=[],this.connections=Ue.state.connections,this.unsubscribe.push(Ue.subscribeKey("connections",e=>this.connections=e))}render(){const e=this.connectors.filter(qu.showConnector);return e.length===0?(this.style.cssText="display: none",null):K` + + ${e.map(n=>{const s=(this.connections.get(n.chain)??[]).some(i=>Jn.isLowerCaseMatch(i.connectorId,n.id));return K` + this.onConnector(n)} + tabIdx=${rt(this.tabIdx)} + > + + `})} + + `}onConnector(e){ke.setActiveConnector(e),ze.push("ConnectingExternal",{connector:e})}};Lk([ee()],N_.prototype,"tabIdx",void 0);Lk([ee()],N_.prototype,"connectors",void 0);Lk([Ne()],N_.prototype,"connections",void 0);N_=Lk([We("w3m-connect-injected-widget")],N_);var kW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let gN=class extends He{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=ke.state.connectors,this.unsubscribe.push(ke.subscribeKey("connectors",e=>this.connectors=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const e=this.connectors.filter(n=>n.type==="MULTI_CHAIN"&&n.name!=="WalletConnect");return e?.length?K` + + ${e.map(n=>K` + this.onConnector(n)} + tabIdx=${rt(this.tabIdx)} + > + + `)} + + `:(this.style.cssText="display: none",null)}onConnector(e){ke.setActiveConnector(e),ze.push("ConnectingMultiChain")}};kW([ee()],gN.prototype,"tabIdx",void 0);kW([Ne()],gN.prototype,"connectors",void 0);gN=kW([We("w3m-connect-multi-chain-widget")],gN);var Bk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let P_=class extends He{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=ke.state.connectors,this.loading=!1,this.unsubscribe.push(ke.subscribeKey("connectors",e=>this.connectors=e)),De.isTelegram()&&De.isIos()&&(this.loading=!Ue.state.wcUri,this.unsubscribe.push(Ue.subscribeKey("wcUri",e=>this.loading=!e)))}render(){const n=Ge.getRecentWallets().filter(s=>!pf.isExcluded(s)).filter(s=>!this.hasWalletConnector(s)).filter(s=>this.isWalletCompatibleWithCurrentChain(s));if(!n.length)return this.style.cssText="display: none",null;const r=Ue.hasAnyConnection(ye.CONNECTOR_ID.WALLET_CONNECT);return K` + + ${n.map(s=>K` + this.onConnectWallet(s)} + tagLabel="recent" + tagVariant="shade" + tabIdx=${rt(this.tabIdx)} + ?loading=${this.loading} + ?disabled=${r} + > + + `)} + + `}onConnectWallet(e){this.loading||ke.selectWalletConnector(e)}hasWalletConnector(e){return this.connectors.some(n=>n.id===e.id||n.name===e.name)}isWalletCompatibleWithCurrentChain(e){const n=G.state.activeChain;return n&&e.chains?e.chains.some(r=>{const s=r.split(":")[0];return n===s}):!0}};Bk([ee()],P_.prototype,"tabIdx",void 0);Bk([Ne()],P_.prototype,"connectors",void 0);Bk([Ne()],P_.prototype,"loading",void 0);P_=Bk([We("w3m-connect-recent-widget")],P_);var Uk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let k_=class extends He{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.wallets=[],this.loading=!1,De.isTelegram()&&De.isIos()&&(this.loading=!Ue.state.wcUri,this.unsubscribe.push(Ue.subscribeKey("wcUri",e=>this.loading=!e)))}render(){const{connectors:e}=ke.state,{customWallets:n,featuredWalletIds:r}=_e.state,s=Ge.getRecentWallets(),i=e.find(f=>f.id==="walletConnect"),a=e.filter(f=>f.type==="INJECTED"||f.type==="ANNOUNCED"||f.type==="MULTI_CHAIN").filter(f=>f.name!=="Browser Wallet");if(!i)return null;if(r||n||!this.wallets.length)return this.style.cssText="display: none",null;const c=a.length+s.length,l=Math.max(0,2-c),u=pf.filterOutDuplicateWallets(this.wallets).slice(0,l);if(!u.length)return this.style.cssText="display: none",null;const d=Ue.hasAnyConnection(ye.CONNECTOR_ID.WALLET_CONNECT);return K` + + ${u.map(f=>K` + this.onConnectWallet(f)} + tabIdx=${rt(this.tabIdx)} + ?loading=${this.loading} + ?disabled=${d} + > + + `)} + + `}onConnectWallet(e){if(this.loading)return;const n=ke.getConnector({id:e.id,rdns:e.rdns});n?ze.push("ConnectingExternal",{connector:n}):ze.push("ConnectingWalletConnect",{wallet:e})}};Uk([ee()],k_.prototype,"tabIdx",void 0);Uk([ee()],k_.prototype,"wallets",void 0);Uk([Ne()],k_.prototype,"loading",void 0);k_=Uk([We("w3m-connect-recommended-widget")],k_);var Fk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let R_=class extends He{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=ke.state.connectors,this.connectorImages=mi.state.connectorImages,this.unsubscribe.push(ke.subscribeKey("connectors",e=>this.connectors=e),mi.subscribeKey("connectorImages",e=>this.connectorImages=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){if(De.isMobile())return this.style.cssText="display: none",null;const e=this.connectors.find(s=>s.id==="walletConnect");if(!e)return this.style.cssText="display: none",null;const n=e.imageUrl||this.connectorImages[e?.imageId??""],r=Ue.hasAnyConnection(ye.CONNECTOR_ID.WALLET_CONNECT);return K` + this.onConnector(e)} + tagLabel="qr code" + tagVariant="main" + tabIdx=${rt(this.tabIdx)} + data-testid="wallet-selector-walletconnect" + ?disabled=${r} + > + + `}onConnector(e){ke.setActiveConnector(e),ze.push("ConnectingWalletConnect")}};Fk([ee()],R_.prototype,"tabIdx",void 0);Fk([Ne()],R_.prototype,"connectors",void 0);Fk([Ne()],R_.prototype,"connectorImages",void 0);R_=Fk([We("w3m-connect-walletconnect-widget")],R_);const pft=it` + :host { + margin-top: var(--wui-spacing-3xs); + } + wui-separator { + margin: var(--wui-spacing-m) calc(var(--wui-spacing-m) * -1) var(--wui-spacing-xs) + calc(var(--wui-spacing-m) * -1); + width: calc(100% + var(--wui-spacing-s) * 2); + } +`;var _3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let My=class extends He{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=ke.state.connectors,this.recommended=mt.state.recommended,this.featured=mt.state.featured,this.unsubscribe.push(ke.subscribeKey("connectors",e=>this.connectors=e),mt.subscribeKey("recommended",e=>this.recommended=e),mt.subscribeKey("featured",e=>this.featured=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return K` + ${this.connectorListTemplate()} + `}connectorListTemplate(){const{custom:e,recent:n,announced:r,injected:s,multiChain:i,recommended:o,featured:a,external:c}=qu.getConnectorsByType(this.connectors,this.recommended,this.featured);return qu.getConnectorTypeOrder({custom:e,recent:n,announced:r,injected:s,multiChain:i,recommended:o,featured:a,external:c}).map(u=>{switch(u){case"injected":return K` + ${i.length?K``:null} + ${r.length?K``:null} + ${s.length?K``:null} + `;case"walletConnect":return K``;case"recent":return K``;case"featured":return K``;case"custom":return K``;case"external":return K``;case"recommended":return K``;default:return console.warn(`Unknown connector type: ${u}`),null}})}};My.styles=pft;_3([ee()],My.prototype,"tabIdx",void 0);_3([Ne()],My.prototype,"connectors",void 0);_3([Ne()],My.prototype,"recommended",void 0);_3([Ne()],My.prototype,"featured",void 0);My=_3([We("w3m-connector-list")],My);var I0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let SB=class extends He{constructor(){super(...arguments),this.tabIdx=void 0}render(){return K` + + + + + `}};I0e([ee()],SB.prototype,"tabIdx",void 0);SB=I0e([We("w3m-wallet-login-list")],SB);const gft=it` + :host { + --connect-scroll--top-opacity: 0; + --connect-scroll--bottom-opacity: 0; + --connect-mask-image: none; + } + + .connect { + max-height: clamp(360px, 470px, 80vh); + scrollbar-width: none; + overflow-y: scroll; + overflow-x: hidden; + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + mask-image: var(--connect-mask-image); + } + + .guide { + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + } + + .connect::-webkit-scrollbar { + display: none; + } + + .all-wallets { + flex-flow: column; + } + + .connect.disabled, + .guide.disabled { + opacity: 0.3; + pointer-events: none; + user-select: none; + } + + wui-separator { + margin: var(--wui-spacing-s) calc(var(--wui-spacing-s) * -1); + width: calc(100% + var(--wui-spacing-s) * 2); + } +`;var su=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const mft=470;let oa=class extends He{constructor(){super(),this.unsubscribe=[],this.connectors=ke.state.connectors,this.authConnector=this.connectors.find(e=>e.type==="AUTH"),this.features=_e.state.features,this.remoteFeatures=_e.state.remoteFeatures,this.enableWallets=_e.state.enableWallets,this.noAdapters=G.state.noAdapters,this.walletGuide="get-started",this.checked=Vm.state.isLegalCheckboxChecked,this.isEmailEnabled=this.remoteFeatures?.email&&!G.state.noAdapters,this.isSocialEnabled=this.remoteFeatures?.socials&&this.remoteFeatures.socials.length>0&&!G.state.noAdapters,this.isAuthEnabled=this.checkIfAuthEnabled(this.connectors),this.unsubscribe.push(ke.subscribeKey("connectors",e=>{this.connectors=e,this.authConnector=this.connectors.find(n=>n.type==="AUTH"),this.isAuthEnabled=this.checkIfAuthEnabled(this.connectors)}),_e.subscribeKey("features",e=>{this.features=e}),_e.subscribeKey("remoteFeatures",e=>{this.remoteFeatures=e,this.setEmailAndSocialEnableCheck(this.noAdapters,this.remoteFeatures)}),_e.subscribeKey("enableWallets",e=>this.enableWallets=e),G.subscribeKey("noAdapters",e=>this.setEmailAndSocialEnableCheck(e,this.remoteFeatures)),Vm.subscribeKey("isLegalCheckboxChecked",e=>this.checked=e))}disconnectedCallback(){this.unsubscribe.forEach(n=>n()),this.resizeObserver?.disconnect(),this.shadowRoot?.querySelector(".connect")?.removeEventListener("scroll",this.handleConnectListScroll.bind(this))}firstUpdated(){const e=this.shadowRoot?.querySelector(".connect");e&&(requestAnimationFrame(this.handleConnectListScroll.bind(this)),e?.addEventListener("scroll",this.handleConnectListScroll.bind(this)),this.resizeObserver=new ResizeObserver(()=>{this.handleConnectListScroll()}),this.resizeObserver?.observe(e),this.handleConnectListScroll())}render(){const{termsConditionsUrl:e,privacyPolicyUrl:n}=_e.state,r=_e.state.features?.legalCheckbox,o=!!(e||n)&&!!r&&this.walletGuide==="get-started"&&!this.checked,a={connect:!0,disabled:o},c=_e.state.enableWalletGuide,l=this.enableWallets,u=this.isSocialEnabled||this.authConnector,d=o?-1:void 0;return K` + + ${this.legalCheckboxTemplate()} + + + ${this.renderConnectMethod(d)} + + + ${this.guideTemplate(o)} + + + `}setEmailAndSocialEnableCheck(e,n){this.isEmailEnabled=n?.email&&!e,this.isSocialEnabled=n?.socials&&n.socials.length>0&&!e,this.remoteFeatures=n,this.noAdapters=e}checkIfAuthEnabled(e){const n=e.filter(s=>s.type===Jr.CONNECTOR_TYPE_AUTH).map(s=>s.chain);return ye.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(s=>n.includes(s))}renderConnectMethod(e){const n=pf.getConnectOrderMethod(this.features,this.connectors);return K`${n.map((r,s)=>{switch(r){case"email":return K`${this.emailTemplate(e)} ${this.separatorTemplate(s,"email")}`;case"social":return K`${this.socialListTemplate(e)} + ${this.separatorTemplate(s,"social")}`;case"wallet":return K`${this.walletListTemplate(e)} + ${this.separatorTemplate(s,"wallet")}`;default:return null}})}`}checkMethodEnabled(e){switch(e){case"wallet":return this.enableWallets;case"social":return this.isSocialEnabled&&this.isAuthEnabled;case"email":return this.isEmailEnabled&&this.isAuthEnabled;default:return null}}checkIsThereNextMethod(e){const r=pf.getConnectOrderMethod(this.features,this.connectors)[e+1];return r?this.checkMethodEnabled(r)?r:this.checkIsThereNextMethod(e+1):void 0}separatorTemplate(e,n){const r=this.checkIsThereNextMethod(e),s=this.walletGuide==="explore";switch(n){case"wallet":return this.enableWallets&&r&&!s?K``:null;case"email":{const i=r==="social";return this.isAuthEnabled&&this.isEmailEnabled&&!i&&r?K``:null}case"social":{const i=r==="email";return this.isAuthEnabled&&this.isSocialEnabled&&!i&&r?K``:null}default:return null}}emailTemplate(e){return!this.isEmailEnabled||!this.isAuthEnabled?null:K``}socialListTemplate(e){return!this.isSocialEnabled||!this.isAuthEnabled?null:K``}walletListTemplate(e){const n=this.enableWallets,r=this.features?.emailShowWallets===!1,s=this.features?.collapseWallets,i=r||s;return!n||(De.isTelegram()&&(De.isSafari()||De.isIos())&&Ue.connectWalletConnect().catch(a=>({})),this.walletGuide==="explore")?null:this.isAuthEnabled&&(this.isEmailEnabled||this.isSocialEnabled)&&i?K``:K``}guideTemplate(e=!1){if(!_e.state.enableWalletGuide)return null;const r={guide:!0,disabled:e},s=e?-1:void 0;return!this.authConnector&&!this.isSocialEnabled?null:K` + ${this.walletGuide==="explore"&&!G.state.noAdapters?K``:null} + + `}legalCheckboxTemplate(){return this.walletGuide==="explore"?null:K``}handleConnectListScroll(){const e=this.shadowRoot?.querySelector(".connect");if(!e)return;e.scrollHeight>mft?(e.style.setProperty("--connect-mask-image",`linear-gradient( + to bottom, + rgba(0, 0, 0, calc(1 - var(--connect-scroll--top-opacity))) 0px, + rgba(200, 200, 200, calc(1 - var(--connect-scroll--top-opacity))) 1px, + black 40px, + black calc(100% - 40px), + rgba(155, 155, 155, calc(1 - var(--connect-scroll--bottom-opacity))) calc(100% - 1px), + rgba(0, 0, 0, calc(1 - var(--connect-scroll--bottom-opacity))) 100% + )`),e.style.setProperty("--connect-scroll--top-opacity",VT.interpolate([0,50],[0,1],e.scrollTop).toString()),e.style.setProperty("--connect-scroll--bottom-opacity",VT.interpolate([0,50],[0,1],e.scrollHeight-e.scrollTop-e.offsetHeight).toString())):(e.style.setProperty("--connect-mask-image","none"),e.style.setProperty("--connect-scroll--top-opacity","0"),e.style.setProperty("--connect-scroll--bottom-opacity","0"))}onContinueWalletClick(){ze.push("ConnectWallets")}};oa.styles=gft;su([Ne()],oa.prototype,"connectors",void 0);su([Ne()],oa.prototype,"authConnector",void 0);su([Ne()],oa.prototype,"features",void 0);su([Ne()],oa.prototype,"remoteFeatures",void 0);su([Ne()],oa.prototype,"enableWallets",void 0);su([Ne()],oa.prototype,"noAdapters",void 0);su([ee()],oa.prototype,"walletGuide",void 0);su([Ne()],oa.prototype,"checked",void 0);su([Ne()],oa.prototype,"isEmailEnabled",void 0);su([Ne()],oa.prototype,"isSocialEnabled",void 0);su([Ne()],oa.prototype,"isAuthEnabled",void 0);oa=su([We("w3m-connect-view")],oa);const yft=it` + :host { + display: block; + width: var(--wui-box-size-md); + height: var(--wui-box-size-md); + } + + svg { + width: var(--wui-box-size-md); + height: var(--wui-box-size-md); + } + + rect { + fill: none; + stroke: var(--wui-color-accent-100); + stroke-width: 4px; + stroke-linecap: round; + animation: dash 1s linear infinite; + } + + @keyframes dash { + to { + stroke-dashoffset: 0px; + } + } +`;var T0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let mN=class extends He{constructor(){super(...arguments),this.radius=36}render(){return this.svgLoaderTemplate()}svgLoaderTemplate(){const e=this.radius>50?50:this.radius,r=36-e,s=116+r,i=245+r,o=360+r*1.75;return K` + + + + `}};mN.styles=[Ht,yft];T0e([ee({type:Number})],mN.prototype,"radius",void 0);mN=T0e([We("wui-loading-thumbnail")],mN);const wft=it` + button { + border: none; + border-radius: var(--wui-border-radius-3xl); + } + + button[data-variant='main'] { + background-color: var(--wui-color-accent-100); + color: var(--wui-color-inverse-100); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + } + + button[data-variant='accent'] { + background-color: var(--wui-color-accent-glass-010); + color: var(--wui-color-accent-100); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-005); + } + + button[data-variant='gray'] { + background-color: transparent; + color: var(--wui-color-fg-200); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + } + + button[data-variant='shade'] { + background-color: transparent; + color: var(--wui-color-accent-100); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + } + + button[data-size='sm'] { + height: 32px; + padding: 0 var(--wui-spacing-s); + } + + button[data-size='md'] { + height: 40px; + padding: 0 var(--wui-spacing-l); + } + + button[data-size='sm'] > wui-image { + width: 16px; + height: 16px; + } + + button[data-size='md'] > wui-image { + width: 24px; + height: 24px; + } + + button[data-size='sm'] > wui-icon { + width: 12px; + height: 12px; + } + + button[data-size='md'] > wui-icon { + width: 14px; + height: 14px; + } + + wui-image { + border-radius: var(--wui-border-radius-3xl); + overflow: hidden; + } + + button.disabled > wui-icon, + button.disabled > wui-image { + filter: grayscale(1); + } + + button[data-variant='main'] > wui-image { + box-shadow: inset 0 0 0 1px var(--wui-color-accent-090); + } + + button[data-variant='shade'] > wui-image, + button[data-variant='gray'] > wui-image { + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + } + + @media (hover: hover) and (pointer: fine) { + button[data-variant='main']:focus-visible { + background-color: var(--wui-color-accent-090); + } + + button[data-variant='main']:hover:enabled { + background-color: var(--wui-color-accent-090); + } + + button[data-variant='main']:active:enabled { + background-color: var(--wui-color-accent-080); + } + + button[data-variant='accent']:hover:enabled { + background-color: var(--wui-color-accent-glass-015); + } + + button[data-variant='accent']:active:enabled { + background-color: var(--wui-color-accent-glass-020); + } + + button[data-variant='shade']:focus-visible, + button[data-variant='gray']:focus-visible, + button[data-variant='shade']:hover, + button[data-variant='gray']:hover { + background-color: var(--wui-color-gray-glass-002); + } + + button[data-variant='gray']:active, + button[data-variant='shade']:active { + background-color: var(--wui-color-gray-glass-005); + } + } + + button.disabled { + color: var(--wui-color-gray-glass-020); + background-color: var(--wui-color-gray-glass-002); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-002); + pointer-events: none; + } +`;var yw=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let op=class extends He{constructor(){super(...arguments),this.variant="accent",this.imageSrc="",this.disabled=!1,this.icon="externalLink",this.size="md",this.text=""}render(){const e=this.size==="sm"?"small-600":"paragraph-600";return K` + + `}};op.styles=[Ht,lr,wft];yw([ee()],op.prototype,"variant",void 0);yw([ee()],op.prototype,"imageSrc",void 0);yw([ee({type:Boolean})],op.prototype,"disabled",void 0);yw([ee()],op.prototype,"icon",void 0);yw([ee()],op.prototype,"size",void 0);yw([ee()],op.prototype,"text",void 0);op=yw([We("wui-chip-button")],op);const bft=it` + wui-flex { + width: 100%; + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + } +`;var jk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let c1=class extends He{constructor(){super(...arguments),this.disabled=!1,this.label="",this.buttonLabel=""}render(){return K` + + ${this.label} + + + + `}};c1.styles=[Ht,lr,bft];jk([ee({type:Boolean})],c1.prototype,"disabled",void 0);jk([ee()],c1.prototype,"label",void 0);jk([ee()],c1.prototype,"buttonLabel",void 0);c1=jk([We("wui-cta-button")],c1);const vft=it` + :host { + display: block; + padding: 0 var(--wui-spacing-xl) var(--wui-spacing-xl); + } +`;var N0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let yN=class extends He{constructor(){super(...arguments),this.wallet=void 0}render(){if(!this.wallet)return this.style.display="none",null;const{name:e,app_store:n,play_store:r,chrome_store:s,homepage:i}=this.wallet,o=De.isMobile(),a=De.isIos(),c=De.isAndroid(),l=[n,r,i,s].filter(Boolean).length>1,u=qr.getTruncateString({string:e,charsStart:12,charsEnd:0,truncate:"end"});return l&&!o?K` + ze.push("Downloads",{wallet:this.wallet})} + > + `:!l&&i?K` + + `:n&&a?K` + + `:r&&c?K` + + `:(this.style.display="none",null)}onAppStore(){this.wallet?.app_store&&De.openHref(this.wallet.app_store,"_blank")}onPlayStore(){this.wallet?.play_store&&De.openHref(this.wallet.play_store,"_blank")}onHomePage(){this.wallet?.homepage&&De.openHref(this.wallet.homepage,"_blank")}};yN.styles=[vft];N0e([ee({type:Object})],yN.prototype,"wallet",void 0);yN=N0e([We("w3m-mobile-download-links")],yN);const xft=it` + @keyframes shake { + 0% { + transform: translateX(0); + } + 25% { + transform: translateX(3px); + } + 50% { + transform: translateX(-3px); + } + 75% { + transform: translateX(3px); + } + 100% { + transform: translateX(0); + } + } + + wui-flex:first-child:not(:only-child) { + position: relative; + } + + wui-loading-thumbnail { + position: absolute; + } + + wui-icon-box { + position: absolute; + right: calc(var(--wui-spacing-3xs) * -1); + bottom: calc(var(--wui-spacing-3xs) * -1); + opacity: 0; + transform: scale(0.5); + transition-property: opacity, transform; + transition-duration: var(--wui-duration-lg); + transition-timing-function: var(--wui-ease-out-power-2); + will-change: opacity, transform; + } + + wui-text[align='center'] { + width: 100%; + padding: 0px var(--wui-spacing-l); + } + + [data-error='true'] wui-icon-box { + opacity: 1; + transform: scale(1); + } + + [data-error='true'] > wui-flex:first-child { + animation: shake 250ms cubic-bezier(0.36, 0.07, 0.19, 0.97) both; + } + + [data-retry='false'] wui-link { + display: none; + } + + [data-retry='true'] wui-link { + display: block; + opacity: 1; + } +`;var yd=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};class Ei extends He{constructor(){super(),this.wallet=ze.state.data?.wallet,this.connector=ze.state.data?.connector,this.timeout=void 0,this.secondaryBtnIcon="refresh",this.onConnect=void 0,this.onRender=void 0,this.onAutoConnect=void 0,this.isWalletConnect=!0,this.unsubscribe=[],this.imageSrc=nr.getWalletImage(this.wallet)??nr.getConnectorImage(this.connector),this.name=this.wallet?.name??this.connector?.name??"Wallet",this.isRetrying=!1,this.uri=Ue.state.wcUri,this.error=Ue.state.wcError,this.ready=!1,this.showRetry=!1,this.label=void 0,this.secondaryBtnLabel="Try again",this.secondaryLabel="Accept connection request in the wallet",this.isLoading=!1,this.isMobile=!1,this.onRetry=void 0,this.unsubscribe.push(Ue.subscribeKey("wcUri",e=>{this.uri=e,this.isRetrying&&this.onRetry&&(this.isRetrying=!1,this.onConnect?.())}),Ue.subscribeKey("wcError",e=>this.error=e)),(De.isTelegram()||De.isSafari())&&De.isIos()&&Ue.state.wcUri&&this.onConnect?.()}firstUpdated(){this.onAutoConnect?.(),this.showRetry=!this.onAutoConnect}disconnectedCallback(){this.unsubscribe.forEach(e=>e()),Ue.setWcError(!1),clearTimeout(this.timeout)}render(){this.onRender?.(),this.onShowRetry();const e=this.error?"Connection can be declined if a previous request is still active":this.secondaryLabel;let n="";return this.label?n=this.label:(n=`Continue in ${this.name}`,this.error&&(n="Connection declined")),K` + + + + + ${this.error?null:this.loaderTemplate()} + + + + + + + ${n} + + ${e} + + + ${this.secondaryBtnLabel?K` + + + ${this.secondaryBtnLabel} + + `:null} + + + ${this.isWalletConnect?K` + + + + Copy link + + + `:null} + + + `}onShowRetry(){this.error&&!this.showRetry&&(this.showRetry=!0,this.shadowRoot?.querySelector("wui-button")?.animate([{opacity:0},{opacity:1}],{fill:"forwards",easing:"ease"}))}onTryAgain(){Ue.setWcError(!1),this.onRetry?(this.isRetrying=!0,this.onRetry?.()):this.onConnect?.()}loaderTemplate(){const e=Bi.state.themeVariables["--w3m-border-radius-master"],n=e?parseInt(e.replace("px",""),10):4;return K``}onCopyUri(){try{this.uri&&(De.copyToClopboard(this.uri),Wn.showSuccess("Link copied"))}catch{Wn.showError("Failed to copy")}}}Ei.styles=xft;yd([Ne()],Ei.prototype,"isRetrying",void 0);yd([Ne()],Ei.prototype,"uri",void 0);yd([Ne()],Ei.prototype,"error",void 0);yd([Ne()],Ei.prototype,"ready",void 0);yd([Ne()],Ei.prototype,"showRetry",void 0);yd([Ne()],Ei.prototype,"label",void 0);yd([Ne()],Ei.prototype,"secondaryBtnLabel",void 0);yd([Ne()],Ei.prototype,"secondaryLabel",void 0);yd([Ne()],Ei.prototype,"isLoading",void 0);yd([ee({type:Boolean})],Ei.prototype,"isMobile",void 0);yd([ee()],Ei.prototype,"onRetry",void 0);var Eft=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let AB=class extends Ei{constructor(){if(super(),this.externalViewUnsubscribe=[],this.connectionsByNamespace=Ue.getConnections(this.connector?.chain),this.hasMultipleConnections=this.connectionsByNamespace.length>0,this.remoteFeatures=_e.state.remoteFeatures,this.currentActiveConnectorId=ke.state.activeConnectorIds[this.connector?.chain],!this.connector)throw new Error("w3m-connecting-view: No connector provided");const e=this.connector?.chain;this.isAlreadyConnected(this.connector)&&(this.secondaryBtnLabel=void 0,this.label=`This account is already linked, change your account in ${this.connector.name}`,this.secondaryLabel=`To link a new account, open ${this.connector.name} and switch to the account you want to link`),Lt.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.connector.name??"Unknown",platform:"browser",displayIndex:this.wallet?.display_index}}),this.onConnect=this.onConnectProxy.bind(this),this.onAutoConnect=this.onConnectProxy.bind(this),this.isWalletConnect=!1,this.externalViewUnsubscribe.push(ke.subscribeKey("activeConnectorIds",n=>{const r=n[e],s=this.remoteFeatures?.multiWallet;r!==this.currentActiveConnectorId&&(this.hasMultipleConnections&&s?(ze.replace("ProfileWallets"),Wn.showSuccess("New Wallet Added")):tn.close())}),Ue.subscribeKey("connections",this.onConnectionsChange.bind(this)))}disconnectedCallback(){this.externalViewUnsubscribe.forEach(e=>e())}async onConnectProxy(){try{if(this.error=!1,this.connector){if(this.isAlreadyConnected(this.connector))return;(this.connector.id!==ye.CONNECTOR_ID.COINBASE_SDK||!this.error)&&(await Ue.connectExternal(this.connector,this.connector.chain),Lt.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:"browser",name:this.connector.name||"Unknown",caipNetworkId:G.getActiveCaipNetwork()?.caipNetworkId}}))}}catch(e){Lt.sendEvent({type:"track",event:"CONNECT_ERROR",properties:{message:e?.message??"Unknown"}}),this.error=!0}}onConnectionsChange(e){if(this.connector?.chain&&e.get(this.connector.chain)&&this.isAlreadyConnected(this.connector)){const n=e.get(this.connector.chain)??[],r=this.remoteFeatures?.multiWallet;if(n.length===0)ze.replace("Connect");else{const s=Sl.getConnectionsByConnectorId(this.connectionsByNamespace,this.connector.id).flatMap(o=>o.accounts),i=Sl.getConnectionsByConnectorId(n,this.connector.id).flatMap(o=>o.accounts);i.length===0?this.hasMultipleConnections&&r?(ze.replace("ProfileWallets"),Wn.showSuccess("Wallet deleted")):tn.close():!s.every(a=>i.some(c=>Jn.isLowerCaseMatch(a.address,c.address)))&&r&&ze.replace("ProfileWallets")}}}isAlreadyConnected(e){return!!e&&this.connectionsByNamespace.some(n=>Jn.isLowerCaseMatch(n.connectorId,e.id))}};AB=Eft([We("w3m-connecting-external-view")],AB);const Cft=it` + wui-flex, + wui-list-wallet { + width: 100%; + } +`;var P0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let O_=class extends He{constructor(){super(),this.unsubscribe=[],this.activeConnector=ke.state.activeConnector,this.unsubscribe.push(ke.subscribeKey("activeConnector",e=>this.activeConnector=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return K` + + + + + + + Select Chain for ${this.activeConnector?.name} + + Select which chain to connect to your multi chain wallet + + + ${this.networksTemplate()} + + + `}networksTemplate(){return this.activeConnector?.connectors?.map(e=>e.name?K` + this.onConnector(e)} + data-testid="wui-list-chain-${e.chain}" + > + `:null)}onConnector(e){const n=this.activeConnector?.connectors?.find(r=>r.chain===e.chain);if(!n){Wn.showError("Failed to find connector");return}n.id==="walletConnect"?De.isMobile()?ze.push("AllWallets"):ze.push("ConnectingWalletConnect"):ze.push("ConnectingExternal",{connector:n})}};O_.styles=Cft;P0e([Ne()],O_.prototype,"activeConnector",void 0);O_=P0e([We("w3m-connecting-multi-chain-view")],O_);var RW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let wN=class extends He{constructor(){super(...arguments),this.platformTabs=[],this.unsubscribe=[],this.platforms=[],this.onSelectPlatfrom=void 0}disconnectCallback(){this.unsubscribe.forEach(e=>e())}render(){const e=this.generateTabs();return K` + + + + `}generateTabs(){const e=this.platforms.map(n=>n==="browser"?{label:"Browser",icon:"extension",platform:"browser"}:n==="mobile"?{label:"Mobile",icon:"mobile",platform:"mobile"}:n==="qrcode"?{label:"Mobile",icon:"mobile",platform:"qrcode"}:n==="web"?{label:"Webapp",icon:"browser",platform:"web"}:n==="desktop"?{label:"Desktop",icon:"desktop",platform:"desktop"}:{label:"Browser",icon:"extension",platform:"unsupported"});return this.platformTabs=e.map(({platform:n})=>n),e}onTabChange(e){const n=this.platformTabs[e];n&&this.onSelectPlatfrom?.(n)}};RW([ee({type:Array})],wN.prototype,"platforms",void 0);RW([ee()],wN.prototype,"onSelectPlatfrom",void 0);wN=RW([We("w3m-connecting-header")],wN);var _ft=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let yte=class extends Ei{constructor(){if(super(),!this.wallet)throw new Error("w3m-connecting-wc-browser: No wallet provided");this.onConnect=this.onConnectProxy.bind(this),this.onAutoConnect=this.onConnectProxy.bind(this),Lt.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet.name,platform:"browser",displayIndex:this.wallet?.display_index}})}async onConnectProxy(){try{this.error=!1;const{connectors:e}=ke.state,n=e.find(r=>r.type==="ANNOUNCED"&&r.info?.rdns===this.wallet?.rdns||r.type==="INJECTED"||r.name===this.wallet?.name);if(n)await Ue.connectExternal(n,n.chain);else throw new Error("w3m-connecting-wc-browser: No connector found");tn.close(),Lt.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:"browser",name:this.wallet?.name||"Unknown",caipNetworkId:G.getActiveCaipNetwork()?.caipNetworkId}})}catch(e){Lt.sendEvent({type:"track",event:"CONNECT_ERROR",properties:{message:e?.message??"Unknown"}}),this.error=!0}}};yte=_ft([We("w3m-connecting-wc-browser")],yte);var Sft=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let wte=class extends Ei{constructor(){if(super(),!this.wallet)throw new Error("w3m-connecting-wc-desktop: No wallet provided");this.onConnect=this.onConnectProxy.bind(this),this.onRender=this.onRenderProxy.bind(this),Lt.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet.name,platform:"desktop",displayIndex:this.wallet?.display_index}})}onRenderProxy(){!this.ready&&this.uri&&(this.ready=!0,this.onConnect?.())}onConnectProxy(){if(this.wallet?.desktop_link&&this.uri)try{this.error=!1;const{desktop_link:e,name:n}=this.wallet,{redirect:r,href:s}=De.formatNativeUrl(e,this.uri);Ue.setWcLinking({name:n,href:s}),Ue.setRecentWallet(this.wallet),De.openHref(r,"_blank")}catch{this.error=!0}}};wte=Sft([We("w3m-connecting-wc-desktop")],wte);var bx=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Ly=class extends Ei{constructor(){if(super(),this.btnLabelTimeout=void 0,this.redirectDeeplink=void 0,this.redirectUniversalLink=void 0,this.target=void 0,this.preferUniversalLinks=_e.state.experimental_preferUniversalLinks,this.isLoading=!0,this.onConnect=()=>{if(this.wallet?.mobile_link&&this.uri)try{this.error=!1;const{mobile_link:e,link_mode:n,name:r}=this.wallet,{redirect:s,redirectUniversalLink:i,href:o}=De.formatNativeUrl(e,this.uri,n);this.redirectDeeplink=s,this.redirectUniversalLink=i,this.target=De.isIframe()?"_top":"_self",Ue.setWcLinking({name:r,href:o}),Ue.setRecentWallet(this.wallet),this.preferUniversalLinks&&this.redirectUniversalLink?De.openHref(this.redirectUniversalLink,this.target):De.openHref(this.redirectDeeplink,this.target)}catch(e){Lt.sendEvent({type:"track",event:"CONNECT_PROXY_ERROR",properties:{message:e instanceof Error?e.message:"Error parsing the deeplink",uri:this.uri,mobile_link:this.wallet.mobile_link,name:this.wallet.name}}),this.error=!0}},!this.wallet)throw new Error("w3m-connecting-wc-mobile: No wallet provided");this.secondaryBtnLabel="Open",this.secondaryLabel=wn.CONNECT_LABELS.MOBILE,this.secondaryBtnIcon="externalLink",this.onHandleURI(),this.unsubscribe.push(Ue.subscribeKey("wcUri",()=>{this.onHandleURI()})),Lt.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet.name,platform:"mobile",displayIndex:this.wallet?.display_index}})}disconnectedCallback(){super.disconnectedCallback(),clearTimeout(this.btnLabelTimeout)}onHandleURI(){this.isLoading=!this.uri,!this.ready&&this.uri&&(this.ready=!0,this.onConnect?.())}onTryAgain(){Ue.setWcError(!1),this.onConnect?.()}};bx([Ne()],Ly.prototype,"redirectDeeplink",void 0);bx([Ne()],Ly.prototype,"redirectUniversalLink",void 0);bx([Ne()],Ly.prototype,"target",void 0);bx([Ne()],Ly.prototype,"preferUniversalLinks",void 0);bx([Ne()],Ly.prototype,"isLoading",void 0);Ly=bx([We("w3m-connecting-wc-mobile")],Ly);var S3={},Aft=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},k0e={},Xc={};let OW;const Ift=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Xc.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};Xc.getSymbolTotalCodewords=function(e){return Ift[e]};Xc.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Xc.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');OW=e};Xc.isKanjiModeEnabled=function(){return typeof OW<"u"};Xc.toSJIS=function(e){return OW(e)};var zk={};(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},t.from=function(r,s){if(t.isValid(r))return r;try{return e(r)}catch{return s}}})(zk);function R0e(){this.buffer=[],this.length=0}R0e.prototype={get:function(t){const e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let n=0;n>>e-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var Tft=R0e;function A3(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}A3.prototype.set=function(t,e,n,r){const s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};A3.prototype.get=function(t,e){return this.data[t*this.size+e]};A3.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};A3.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};var Nft=A3,O0e={};(function(t){const e=Xc.getSymbolSize;t.getRowColCoords=function(r){if(r===1)return[];const s=Math.floor(r/7)+2,i=e(r),o=i===145?26:Math.ceil((i-13)/(2*s-2))*2,a=[i-7];for(let c=1;c=0&&s<=7},t.from=function(s){return t.isValid(s)?parseInt(s,10):void 0},t.getPenaltyN1=function(s){const i=s.size;let o=0,a=0,c=0,l=null,u=null;for(let d=0;d=5&&(o+=e.N1+(a-5)),l=p,a=1),p=s.get(f,d),p===u?c++:(c>=5&&(o+=e.N1+(c-5)),u=p,c=1)}a>=5&&(o+=e.N1+(a-5)),c>=5&&(o+=e.N1+(c-5))}return o},t.getPenaltyN2=function(s){const i=s.size;let o=0;for(let a=0;a=10&&(a===1488||a===93)&&o++,c=c<<1&2047|s.get(u,l),u>=10&&(c===1488||c===93)&&o++}return o*e.N3},t.getPenaltyN4=function(s){let i=0;const o=s.data.length;for(let c=0;c=0;){const o=i[0];for(let c=0;c0){const i=new Uint8Array(this.degree);return i.set(r,s),i}return r};var kft=$W,B0e={},M0={},DW={};DW.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40};var Nf={};const U0e="[0-9]+",Rft="[A-Z $%*+\\-./:]+";let $_="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";$_=$_.replace(/u/g,"\\u");const Oft="(?:(?![A-Z0-9 $%*+\\-./:]|"+$_+`)(?:.|[\r +]))+`;Nf.KANJI=new RegExp($_,"g");Nf.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Nf.BYTE=new RegExp(Oft,"g");Nf.NUMERIC=new RegExp(U0e,"g");Nf.ALPHANUMERIC=new RegExp(Rft,"g");const $ft=new RegExp("^"+$_+"$"),Dft=new RegExp("^"+U0e+"$"),Mft=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Nf.testKanji=function(e){return $ft.test(e)};Nf.testNumeric=function(e){return Dft.test(e)};Nf.testAlphanumeric=function(e){return Mft.test(e)};(function(t){const e=DW,n=Nf;t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(i,o){if(!i.ccBits)throw new Error("Invalid mode: "+i);if(!e.isValid(o))throw new Error("Invalid version: "+o);return o>=1&&o<10?i.ccBits[0]:o<27?i.ccBits[1]:i.ccBits[2]},t.getBestModeForData=function(i){return n.testNumeric(i)?t.NUMERIC:n.testAlphanumeric(i)?t.ALPHANUMERIC:n.testKanji(i)?t.KANJI:t.BYTE},t.toString=function(i){if(i&&i.id)return i.id;throw new Error("Invalid mode")},t.isValid=function(i){return i&&i.bit&&i.ccBits};function r(s){if(typeof s!="string")throw new Error("Param is not a string");switch(s.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+s)}}t.from=function(i,o){if(t.isValid(i))return i;try{return r(i)}catch{return o}}})(M0);(function(t){const e=Xc,n=Wk,r=zk,s=M0,i=DW,o=7973,a=e.getBCHDigit(o);function c(f,p,m){for(let y=1;y<=40;y++)if(p<=t.getCapacity(y,m,f))return y}function l(f,p){return s.getCharCountIndicator(f,p)+4}function u(f,p){let m=0;return f.forEach(function(y){const b=l(y.mode,p);m+=b+y.getBitsLength()}),m}function d(f,p){for(let m=1;m<=40;m++)if(u(f,m)<=t.getCapacity(m,p,s.MIXED))return m}t.from=function(p,m){return i.isValid(p)?parseInt(p,10):m},t.getCapacity=function(p,m,y){if(!i.isValid(p))throw new Error("Invalid QR Code version");typeof y>"u"&&(y=s.BYTE);const b=e.getSymbolTotalCodewords(p),v=n.getTotalCodewordsCount(p,m),x=(b-v)*8;if(y===s.MIXED)return x;const E=x-l(y,p);switch(y){case s.NUMERIC:return Math.floor(E/10*3);case s.ALPHANUMERIC:return Math.floor(E/11*2);case s.KANJI:return Math.floor(E/13);case s.BYTE:default:return Math.floor(E/8)}},t.getBestVersionForData=function(p,m){let y;const b=r.from(m,r.M);if(Array.isArray(p)){if(p.length>1)return d(p,b);if(p.length===0)return 1;y=p[0]}else y=p;return c(y.mode,y.getLength(),b)},t.getEncodedBits=function(p){if(!i.isValid(p)||p<7)throw new Error("Invalid QR Code version");let m=p<<12;for(;e.getBCHDigit(m)-a>=0;)m^=o<=0;)s^=j0e<0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};var Uft=l1;const Fft=M0,ED=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function u1(t){this.mode=Fft.ALPHANUMERIC,this.data=t}u1.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};u1.prototype.getLength=function(){return this.data.length};u1.prototype.getBitsLength=function(){return u1.getBitsLength(this.data.length)};u1.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=ED.indexOf(this.data[n])*45;r+=ED.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(ED.indexOf(this.data[n]),6)};var jft=u1,zft=function(e){for(var n=[],r=e.length,s=0;s=55296&&i<=56319&&r>s+1){var o=e.charCodeAt(s+1);o>=56320&&o<=57343&&(i=(i-55296)*1024+o-56320+65536,s+=1)}if(i<128){n.push(i);continue}if(i<2048){n.push(i>>6|192),n.push(i&63|128);continue}if(i<55296||i>=57344&&i<65536){n.push(i>>12|224),n.push(i>>6&63|128),n.push(i&63|128);continue}if(i>=65536&&i<=1114111){n.push(i>>18|240),n.push(i>>12&63|128),n.push(i>>6&63|128),n.push(i&63|128);continue}n.push(239,191,189)}return new Uint8Array(n).buffer};const Wft=zft,Vft=M0;function d1(t){this.mode=Vft.BYTE,typeof t=="string"&&(t=Wft(t)),this.data=new Uint8Array(t)}d1.getBitsLength=function(e){return e*8};d1.prototype.getLength=function(){return this.data.length};d1.prototype.getBitsLength=function(){return d1.getBitsLength(this.data.length)};d1.prototype.write=function(t){for(let e=0,n=this.data.length;e=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` +Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};var Gft=f1,W0e={exports:{}};(function(t){var e={single_source_shortest_paths:function(n,r,s){var i={},o={};o[r]=0;var a=e.PriorityQueue.make();a.push(r,0);for(var c,l,u,d,f,p,m,y,b;!a.empty();){c=a.pop(),l=c.value,d=c.cost,f=n[l]||{};for(u in f)f.hasOwnProperty(u)&&(p=f[u],m=d+p,y=o[u],b=typeof o[u]>"u",(b||y>m)&&(o[u]=m,a.push(u,m),i[u]=l))}if(typeof s<"u"&&typeof o[s]>"u"){var v=["Could not find a path from ",r," to ",s,"."].join("");throw new Error(v)}return i},extract_shortest_path_from_predecessor_list:function(n,r){for(var s=[],i=r;i;)s.push(i),n[i],i=n[i];return s.reverse(),s},find_path:function(n,r,s){var i=e.single_source_shortest_paths(n,r,s);return e.extract_shortest_path_from_predecessor_list(i,s)},PriorityQueue:{make:function(n){var r=e.PriorityQueue,s={},i;n=n||{};for(i in r)r.hasOwnProperty(i)&&(s[i]=r[i]);return s.queue=[],s.sorter=n.sorter||r.default_sorter,s},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var s={value:n,cost:r};this.queue.push(s),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(W0e);var Zft=W0e.exports;(function(t){const e=M0,n=Uft,r=jft,s=Hft,i=Gft,o=Nf,a=Xc,c=Zft;function l(v){return unescape(encodeURIComponent(v)).length}function u(v,x,E){const A=[];let _;for(;(_=v.exec(E))!==null;)A.push({data:_[0],index:_.index,mode:x,length:_[0].length});return A}function d(v){const x=u(o.NUMERIC,e.NUMERIC,v),E=u(o.ALPHANUMERIC,e.ALPHANUMERIC,v);let A,_;return a.isKanjiModeEnabled()?(A=u(o.BYTE,e.BYTE,v),_=u(o.KANJI,e.KANJI,v)):(A=u(o.BYTE_KANJI,e.BYTE,v),_=[]),x.concat(E,A,_).sort(function(B,W){return B.index-W.index}).map(function(B){return{data:B.data,mode:B.mode,length:B.length}})}function f(v,x){switch(x){case e.NUMERIC:return n.getBitsLength(v);case e.ALPHANUMERIC:return r.getBitsLength(v);case e.KANJI:return i.getBitsLength(v);case e.BYTE:return s.getBitsLength(v)}}function p(v){return v.reduce(function(x,E){const A=x.length-1>=0?x[x.length-1]:null;return A&&A.mode===E.mode?(x[x.length-1].data+=E.data,x):(x.push(E),x)},[])}function m(v){const x=[];for(let E=0;E=0&&a<=6&&(c===0||c===6)||c>=0&&c<=6&&(a===0||a===6)||a>=2&&a<=4&&c>=2&&c<=4?t.set(i+a,o+c,!0,!0):t.set(i+a,o+c,!1,!0))}}function sht(t){const e=t.size;for(let n=8;n>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function SD(t,e,n){const r=t.size,s=tht.getEncodedBits(e,n);let i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function aht(t,e){const n=t.size;let r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let c=0;c<2;c++)if(!t.isReserved(s,a-c)){let l=!1;o>>i&1)===1),t.set(s,a-c,l),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function cht(t,e,n){const r=new Yft;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),nht.getCharCountIndicator(c.mode,t)),c.write(r)});const s=Hk.getSymbolTotalCodewords(t),i=NB.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const a=(o-r.getLengthInBits())/8;for(let c=0;c=7&&oht(c,e),aht(c,o),isNaN(r)&&(r=TB.getBestMask(c,SD.bind(null,c,n))),TB.applyMask(r,c),SD(c,n,r),{modules:c,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}k0e.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=CD.M,s,i;return typeof n<"u"&&(r=CD.from(n.errorCorrectionLevel,CD.M),s=vN.from(n.version),i=TB.from(n.maskPattern),n.toSJISFunc&&Hk.setToSJISFunction(n.toSJISFunc)),uht(e,s,r,i)};var V0e={},MW={};(function(t){function e(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(i){return[i,i]}))),r.length===6&&r.push("F","F");const s=parseInt(r.join(""),16);return{r:s>>24&255,g:s>>16&255,b:s>>8&255,a:s&255,hex:"#"+r.slice(0,6).join("")}}t.getOptions=function(r){r||(r={}),r.color||(r.color={});const s=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,i=r.width&&r.width>=21?r.width:void 0,o=r.scale||4;return{width:i,scale:i?4:o,margin:s,color:{dark:e(r.color.dark||"#000000ff"),light:e(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},t.getScale=function(r,s){return s.width&&s.width>=r+s.margin*2?s.width/(r+s.margin*2):s.scale},t.getImageWidth=function(r,s){const i=t.getScale(r,s);return Math.floor((r+s.margin*2)*i)},t.qrToImageData=function(r,s,i){const o=s.modules.size,a=s.modules.data,c=t.getScale(o,i),l=Math.floor((o+i.margin*2)*c),u=i.margin*c,d=[i.color.light,i.color.dark];for(let f=0;f=u&&p>=u&&f"u"&&(!o||!o.getContext)&&(c=o,o=void 0),o||(l=r()),c=e.getOptions(c);const u=e.getImageWidth(i.modules.size,c),d=l.getContext("2d"),f=d.createImageData(u,u);return e.qrToImageData(f.data,i,c),n(d,l,u),d.putImageData(f,0,0),l},t.renderToDataURL=function(i,o,a){let c=a;typeof c>"u"&&(!o||!o.getContext)&&(c=o,o=void 0),c||(c={});const l=t.render(i,o,c),u=c.type||"image/png",d=c.rendererOpts||{};return l.toDataURL(u,d.quality)}})(V0e);var H0e={};const dht=MW;function xte(t,e){const n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function AD(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function fht(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a0&&c>0&&t[a-1]||(r+=i?AD("M",c+n,.5+l+n):AD("m",s,0),s=0,i=!1),c+1':"",l="',u='viewBox="0 0 '+a+" "+a+'"',f=''+c+l+` +`;return typeof r=="function"&&r(null,f),f};const hht=Aft,PB=k0e,q0e=V0e,pht=H0e;function LW(t,e,n,r,s){const i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!hht())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(c,l){try{const u=PB.create(n,r);c(t(u,e,r))}catch(u){l(u)}})}try{const c=PB.create(n,r);s(null,t(c,e,r))}catch(c){s(c)}}S3.create=PB.create;S3.toCanvas=LW.bind(null,q0e.render);S3.toDataURL=LW.bind(null,q0e.renderToDataURL);S3.toString=LW.bind(null,function(t,e,n){return pht.render(t,n)});const ght=.1,Ete=2.5,nh=7;function ID(t,e,n){return t===e?!1:(t-e<0?e-t:t-e)<=n+ght}function mht(t,e){const n=Array.prototype.slice.call(S3.create(t,{errorCorrectionLevel:e}).modules.data,0),r=Math.sqrt(n.length);return n.reduce((s,i,o)=>(o%r===0?s.push([i]):s[s.length-1].push(i))&&s,[])}const yht={generate({uri:t,size:e,logoSize:n,dotColor:r="#141414"}){const s="transparent",o=[],a=mht(t,"Q"),c=e/a.length,l=[{x:0,y:0},{x:1,y:0},{x:0,y:1}];l.forEach(({x:y,y:b})=>{const v=(a.length-nh)*c*y,x=(a.length-nh)*c*b,E=.45;for(let A=0;A + `)}});const u=Math.floor((n+25)/c),d=a.length/2-u/2,f=a.length/2+u/2-1,p=[];a.forEach((y,b)=>{y.forEach((v,x)=>{if(a[b][x]&&!(ba.length-(nh+1)&&xa.length-(nh+1))&&!(b>d&&bd&&x{m[y]?m[y]?.push(b):m[y]=[b]}),Object.entries(m).map(([y,b])=>{const v=b.filter(x=>b.every(E=>!ID(x,E,c)));return[Number(y),v]}).forEach(([y,b])=>{b.forEach(v=>{o.push(Kr``)})}),Object.entries(m).filter(([y,b])=>b.length>1).map(([y,b])=>{const v=b.filter(x=>b.some(E=>ID(x,E,c)));return[Number(y),v]}).map(([y,b])=>{b.sort((x,E)=>xA.some(_=>ID(x,_,c)));E?E.push(x):v.push([x])}return[y,v.map(x=>[x[0],x[x.length-1]])]}).forEach(([y,b])=>{b.forEach(([v,x])=>{o.push(Kr` + + `)})}),o}},wht=it` + :host { + position: relative; + user-select: none; + display: block; + overflow: hidden; + aspect-ratio: 1 / 1; + width: var(--local-size); + } + + :host([data-theme='dark']) { + border-radius: clamp(0px, var(--wui-border-radius-l), 40px); + background-color: var(--wui-color-inverse-100); + padding: var(--wui-spacing-l); + } + + :host([data-theme='light']) { + box-shadow: 0 0 0 1px var(--wui-color-bg-125); + background-color: var(--wui-color-bg-125); + } + + :host([data-clear='true']) > wui-icon { + display: none; + } + + svg:first-child, + wui-image, + wui-icon { + position: absolute; + top: 50%; + left: 50%; + transform: translateY(-50%) translateX(-50%); + } + + wui-image { + width: 25%; + height: 25%; + border-radius: var(--wui-border-radius-xs); + } + + wui-icon { + width: 100%; + height: 100%; + color: var(--local-icon-color) !important; + transform: translateY(-50%) translateX(-50%) scale(0.25); + } +`;var Ep=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const bht="#3396ff";let cd=class extends He{constructor(){super(...arguments),this.uri="",this.size=0,this.theme="dark",this.imageSrc=void 0,this.alt=void 0,this.arenaClear=void 0,this.farcaster=void 0}render(){return this.dataset.theme=this.theme,this.dataset.clear=String(this.arenaClear),this.style.cssText=` + --local-size: ${this.size}px; + --local-icon-color: ${this.color??bht} + `,K`${this.templateVisual()} ${this.templateSvg()}`}templateSvg(){const e=this.theme==="light"?this.size:this.size-32;return Kr` + + ${yht.generate({uri:this.uri,size:e,logoSize:this.arenaClear?0:e/4,dotColor:this.color})} + + `}templateVisual(){return this.imageSrc?K``:this.farcaster?K``:K``}};cd.styles=[Ht,wht];Ep([ee()],cd.prototype,"uri",void 0);Ep([ee({type:Number})],cd.prototype,"size",void 0);Ep([ee()],cd.prototype,"theme",void 0);Ep([ee()],cd.prototype,"imageSrc",void 0);Ep([ee()],cd.prototype,"alt",void 0);Ep([ee()],cd.prototype,"color",void 0);Ep([ee({type:Boolean})],cd.prototype,"arenaClear",void 0);Ep([ee({type:Boolean})],cd.prototype,"farcaster",void 0);cd=Ep([We("wui-qr-code")],cd);const vht=it` + @keyframes fadein { + from { + opacity: 0; + } + to { + opacity: 1; + } + } + + wui-shimmer { + width: 100%; + aspect-ratio: 1 / 1; + border-radius: clamp(0px, var(--wui-border-radius-l), 40px) !important; + } + + wui-qr-code { + opacity: 0; + animation-duration: 200ms; + animation-timing-function: ease; + animation-name: fadein; + animation-fill-mode: forwards; + } +`;var xht=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let kB=class extends Ei{constructor(){super(),this.forceUpdate=()=>{this.requestUpdate()},window.addEventListener("resize",this.forceUpdate),Lt.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet?.name??"WalletConnect",platform:"qrcode",displayIndex:this.wallet?.display_index}})}disconnectedCallback(){super.disconnectedCallback(),this.unsubscribe?.forEach(e=>e()),window.removeEventListener("resize",this.forceUpdate)}render(){return this.onRenderProxy(),K` + + ${this.qrCodeTemplate()} + + + Scan this QR Code with your phone + + ${this.copyTemplate()} + + + `}onRenderProxy(){!this.ready&&this.uri&&(this.timeout=setTimeout(()=>{this.ready=!0},200))}qrCodeTemplate(){if(!this.uri||!this.ready)return null;const e=this.getBoundingClientRect().width-40,n=this.wallet?this.wallet.name:void 0;return Ue.setWcLinking(void 0),Ue.setRecentWallet(this.wallet),K` `}copyTemplate(){const e=!this.uri||!this.ready;return K` + + Copy link + `}};kB.styles=vht;kB=xht([We("w3m-connecting-wc-qrcode")],kB);var Eht=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let Cte=class extends He{constructor(){if(super(),this.wallet=ze.state.data?.wallet,!this.wallet)throw new Error("w3m-connecting-wc-unsupported: No wallet provided");Lt.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet.name,platform:"browser",displayIndex:this.wallet?.display_index}})}render(){return K` + + + + Not Detected + + + + `}};Cte=Eht([We("w3m-connecting-wc-unsupported")],Cte);var K0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let RB=class extends Ei{constructor(){if(super(),this.isLoading=!0,!this.wallet)throw new Error("w3m-connecting-wc-web: No wallet provided");this.onConnect=this.onConnectProxy.bind(this),this.secondaryBtnLabel="Open",this.secondaryLabel=wn.CONNECT_LABELS.MOBILE,this.secondaryBtnIcon="externalLink",this.updateLoadingState(),this.unsubscribe.push(Ue.subscribeKey("wcUri",()=>{this.updateLoadingState()})),Lt.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet.name,platform:"web",displayIndex:this.wallet?.display_index}})}updateLoadingState(){this.isLoading=!this.uri}onConnectProxy(){if(this.wallet?.webapp_link&&this.uri)try{this.error=!1;const{webapp_link:e,name:n}=this.wallet,{redirect:r,href:s}=De.formatUniversalUrl(e,this.uri);Ue.setWcLinking({name:n,href:s}),Ue.setRecentWallet(this.wallet),De.openHref(r,"_blank")}catch{this.error=!0}}};K0e([Ne()],RB.prototype,"isLoading",void 0);RB=K0e([We("w3m-connecting-wc-web")],RB);var I3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let By=class extends He{constructor(){super(),this.wallet=ze.state.data?.wallet,this.unsubscribe=[],this.platform=void 0,this.platforms=[],this.isSiwxEnabled=!!_e.state.siwx,this.remoteFeatures=_e.state.remoteFeatures,this.determinePlatforms(),this.initializeConnection(),this.unsubscribe.push(_e.subscribeKey("remoteFeatures",e=>this.remoteFeatures=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return K` + ${this.headerTemplate()} +
${this.platformTemplate()}
+ ${this.reownBrandingTemplate()} + `}reownBrandingTemplate(){return this.remoteFeatures?.reownBranding?K``:null}async initializeConnection(e=!1){if(!(this.platform==="browser"||_e.state.manualWCControl&&!e))try{const{wcPairingExpiry:n,status:r}=Ue.state;if(e||_e.state.enableEmbedded||De.isPairingExpired(n)||r==="connecting"){const s=Ue.getConnections(G.state.activeChain),i=this.remoteFeatures?.multiWallet,o=s.length>0;await Ue.connectWalletConnect(),this.isSiwxEnabled||(o&&i?(ze.replace("ProfileWallets"),Wn.showSuccess("New Wallet Added")):tn.close())}}catch(n){if(n instanceof Error&&n.message.includes("An error occurred when attempting to switch chain")&&!_e.state.enableNetworkSwitch&&G.state.activeChain){G.setActiveCaipNetwork(Du.getUnsupportedNetwork(`${G.state.activeChain}:${G.state.activeCaipNetwork?.id}`)),G.showUnsupportedChainUI();return}Lt.sendEvent({type:"track",event:"CONNECT_ERROR",properties:{message:n?.message??"Unknown"}}),Ue.setWcError(!0),Wn.showError(n.message??"Connection error"),Ue.resetWcConnection(),ze.goBack()}}determinePlatforms(){if(!this.wallet){this.platforms.push("qrcode"),this.platform="qrcode";return}if(this.platform)return;const{mobile_link:e,desktop_link:n,webapp_link:r,injected:s,rdns:i}=this.wallet,o=s?.map(({injected_id:m})=>m).filter(Boolean),a=[...i?[i]:o??[]],c=_e.state.isUniversalProvider?!1:a.length,l=e,u=r,d=Ue.checkInstalled(a),f=c&&d,p=n&&!De.isMobile();f&&!G.state.noAdapters&&this.platforms.push("browser"),l&&this.platforms.push(De.isMobile()?"mobile":"qrcode"),u&&this.platforms.push("web"),p&&this.platforms.push("desktop"),!f&&c&&!G.state.noAdapters&&this.platforms.push("unsupported"),this.platform=this.platforms[0]}platformTemplate(){switch(this.platform){case"browser":return K``;case"web":return K``;case"desktop":return K` + this.initializeConnection(!0)}> + + `;case"mobile":return K` + this.initializeConnection(!0)}> + + `;case"qrcode":return K``;default:return K``}}headerTemplate(){return this.platforms.length>1?K` + + + `:null}async onSelectPlatform(e){const n=this.shadowRoot?.querySelector("div");n&&(await n.animate([{opacity:1},{opacity:0}],{duration:200,fill:"forwards",easing:"ease"}).finished,this.platform=e,n.animate([{opacity:0},{opacity:1}],{duration:200,fill:"forwards",easing:"ease"}))}};I3([Ne()],By.prototype,"platform",void 0);I3([Ne()],By.prototype,"platforms",void 0);I3([Ne()],By.prototype,"isSiwxEnabled",void 0);I3([Ne()],By.prototype,"remoteFeatures",void 0);By=I3([We("w3m-connecting-wc-view")],By);var G0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let xN=class extends He{constructor(){super(...arguments),this.isMobile=De.isMobile()}render(){if(this.isMobile){const{featured:e,recommended:n}=mt.state,{customWallets:r}=_e.state,s=Ge.getRecentWallets(),i=e.length||n.length||r?.length||s.length;return K` + ${i?K``:null} + + `}return K` + + + `}};G0e([Ne()],xN.prototype,"isMobile",void 0);xN=G0e([We("w3m-connecting-wc-basic-view")],xN);const Cht=it` + .continue-button-container { + width: 100%; + } +`;var Z0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let D_=class extends He{constructor(){super(...arguments),this.loading=!1}render(){return K` + + ${this.onboardingTemplate()} ${this.buttonsTemplate()} + {De.openHref(PBe.URLS.FAQ,"_blank")}} + > + Learn more about names + + + + `}onboardingTemplate(){return K` + + + + + + Choose your account name + + + Finally say goodbye to 0x addresses, name your account to make it easier to exchange + assets + + + `}buttonsTemplate(){return K` + Choose name + + `}handleContinue(){ze.push("RegisterAccountName"),Lt.sendEvent({type:"track",event:"OPEN_ENS_FLOW",properties:{isSmartAccount:Ss(G.state.activeChain)===_r.ACCOUNT_TYPES.SMART_ACCOUNT}})}};D_.styles=Cht;Z0e([Ne()],D_.prototype,"loading",void 0);D_=Z0e([We("w3m-choose-account-name-view")],D_);var _ht=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let OB=class extends He{constructor(){super(...arguments),this.wallet=ze.state.data?.wallet}render(){if(!this.wallet)throw new Error("w3m-downloads-view");return K` + + ${this.chromeTemplate()} ${this.iosTemplate()} ${this.androidTemplate()} + ${this.homepageTemplate()} + + `}chromeTemplate(){return this.wallet?.chrome_store?K` + Chrome Extension + `:null}iosTemplate(){return this.wallet?.app_store?K` + iOS App + `:null}androidTemplate(){return this.wallet?.play_store?K` + Android App + `:null}homepageTemplate(){return this.wallet?.homepage?K` + + Website + + `:null}onChromeStore(){this.wallet?.chrome_store&&De.openHref(this.wallet.chrome_store,"_blank")}onAppStore(){this.wallet?.app_store&&De.openHref(this.wallet.app_store,"_blank")}onPlayStore(){this.wallet?.play_store&&De.openHref(this.wallet.play_store,"_blank")}onHomePage(){this.wallet?.homepage&&De.openHref(this.wallet.homepage,"_blank")}};OB=_ht([We("w3m-downloads-view")],OB);var Sht=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const Aht="https://walletconnect.com/explorer";let $B=class extends He{render(){return K` + + ${this.recommendedWalletsTemplate()} + {De.openHref("https://walletconnect.com/explorer?type=wallet","_blank")}} + > + + `}recommendedWalletsTemplate(){const{recommended:e,featured:n}=mt.state,{customWallets:r}=_e.state;return[...n,...r??[],...e].slice(0,4).map(i=>K` + {De.openHref(i.homepage??Aht,"_blank")}} + > + `)}};$B=Sht([We("w3m-get-wallet-view")],$B);const Iht=Kr` + + + + + + + + + + + +`,Tht=Kr` + + + + + + + + `,Nht=Kr` + + + + + + + + + + + + + + + + `,Pht=Kr` + + + + + + + + + + + + +`,kht=Kr` + + + + + + + + + + + + + `,Rht=Kr` + + + + + + + + + + + + + + + `,Oht=Kr` + + + + + + + + + +`,$ht=Kr` + + + + + +`,Dht=Kr` + + + + + + + + + + + + + + + + +`,Mht=Kr` + + + + + +`,Lht=Kr` + + + + + + + + + + `,Bht=Kr` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +`,Uht=Kr` + + + + + + + + + + + + + + + +`,Fht=Kr` + + + + + + + + + + `,jht=Kr` + + + + + + + + +`,zht=Kr` + + + + + + + + + + + + +`,Wht=Kr` + + + + + + + + + + + + + + + + + + +`,Vht=Kr` + + + + + + + + + + + + + + + `,Hht=Kr` + + + + + + + + + + + + + + + + + `,qht=Kr` + + + + + + + + + + + + + + `,Kht=it` + :host { + display: block; + width: var(--local-size); + height: var(--local-size); + } + + :host svg { + width: 100%; + height: 100%; + } +`;var BW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const Ght={browser:Tht,dao:Nht,defi:Pht,defiAlt:kht,eth:Rht,layers:$ht,lock:Mht,login:Lht,network:Uht,nft:Fht,noun:jht,profile:Vht,system:qht,meld:Bht,onrampCard:zht,google:Oht,pencil:Wht,lightbulb:Dht,solana:Hht,bitcoin:Iht};let M_=class extends He{constructor(){super(...arguments),this.name="browser",this.size="md"}render(){return this.style.cssText=` + --local-size: var(--wui-visual-size-${this.size}); + `,K`${Ght[this.name]}`}};M_.styles=[Ht,Kht];BW([ee()],M_.prototype,"name",void 0);BW([ee()],M_.prototype,"size",void 0);M_=BW([We("wui-visual")],M_);var Y0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let DB=class extends He{constructor(){super(...arguments),this.data=[]}render(){return K` + + ${this.data.map(e=>K` + + + ${e.images.map(n=>K``)} + + + + + ${e.title} + + ${e.text} + + `)} + + `}};Y0e([ee({type:Array})],DB.prototype,"data",void 0);DB=Y0e([We("w3m-help-widget")],DB);var Zht=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const Yht=[{images:["login","profile","lock"],title:"One login for all of web3",text:"Log in to any app by connecting your wallet. Say goodbye to countless passwords!"},{images:["defi","nft","eth"],title:"A home for your digital assets",text:"A wallet lets you store, send and receive digital assets like cryptocurrencies and NFTs."},{images:["browser","noun","dao"],title:"Your gateway to a new web",text:"With your wallet, you can explore and interact with DeFi, NFTs, DAOs, and much more."}];let MB=class extends He{render(){return K` + + + + + Get a wallet + + + `}onGetWallet(){Lt.sendEvent({type:"track",event:"CLICK_GET_WALLET"}),ze.push("GetWallet")}};MB=Zht([We("w3m-what-is-a-wallet-view")],MB);const Xht=it` + wui-flex { + max-height: clamp(360px, 540px, 80vh); + overflow: scroll; + scrollbar-width: none; + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + } + wui-flex::-webkit-scrollbar { + display: none; + } + wui-flex.disabled { + opacity: 0.3; + pointer-events: none; + user-select: none; + } +`;var X0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let L_=class extends He{constructor(){super(),this.unsubscribe=[],this.checked=Vm.state.isLegalCheckboxChecked,this.unsubscribe.push(Vm.subscribeKey("isLegalCheckboxChecked",e=>{this.checked=e}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const{termsConditionsUrl:e,privacyPolicyUrl:n}=_e.state,r=_e.state.features?.legalCheckbox,i=!!(e||n)&&!!r,o=i&&!this.checked,a=o?-1:void 0;return K` + + + + + + `}};L_.styles=Xht;X0e([Ne()],L_.prototype,"checked",void 0);L_=X0e([We("w3m-connect-wallets-view")],L_);const Qht=it` + :host { + display: block; + width: var(--wui-box-size-lg); + height: var(--wui-box-size-lg); + } + + svg { + width: var(--wui-box-size-lg); + height: var(--wui-box-size-lg); + fill: none; + stroke: transparent; + stroke-linecap: round; + } + + use { + stroke: var(--wui-color-accent-100); + stroke-width: 2px; + stroke-dasharray: 54, 118; + stroke-dashoffset: 172; + animation: dash 1s linear infinite; + } + + @keyframes dash { + to { + stroke-dashoffset: 0px; + } + } +`;var Jht=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let LB=class extends He{render(){return K` + + + + + `}};LB.styles=[Ht,Qht];LB=Jht([We("wui-loading-hexagon")],LB);const ept=Kr` + +`,tpt=Kr` + + + +`,npt=it` + :host { + position: relative; + border-radius: inherit; + display: flex; + justify-content: center; + align-items: center; + width: var(--local-width); + height: var(--local-height); + } + + :host([data-round='true']) { + background: var(--wui-color-gray-glass-002); + border-radius: 100%; + outline: 1px solid var(--wui-color-gray-glass-005); + } + + svg { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 1; + fill: var(--wui-color-gray-glass-002); + } + + svg > path { + stroke: var(--local-stroke); + } + + wui-image { + width: 100%; + height: 100%; + -webkit-clip-path: var(--local-path); + clip-path: var(--local-path); + background: var(--wui-color-gray-glass-002); + } + + wui-icon { + transform: translateY(-5%); + width: var(--local-icon-size); + height: var(--local-icon-size); + } +`;var ww=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let ap=class extends He{constructor(){super(...arguments),this.size="md",this.name="uknown",this.networkImagesBySize={sm:tpt,md:v0e,lg:ept},this.selected=!1,this.round=!1}render(){return this.round?(this.dataset.round="true",this.style.cssText=` + --local-width: var(--wui-spacing-3xl); + --local-height: var(--wui-spacing-3xl); + --local-icon-size: var(--wui-spacing-l); + `):this.style.cssText=` + + --local-path: var(--wui-path-network-${this.size}); + --local-width: var(--wui-width-network-${this.size}); + --local-height: var(--wui-height-network-${this.size}); + --local-icon-size: var(--wui-icon-size-network-${this.size}); + `,K`${this.templateVisual()} ${this.svgTemplate()} `}svgTemplate(){return this.round?null:this.networkImagesBySize[this.size]}templateVisual(){return this.imageSrc?K``:K``}};ap.styles=[Ht,npt];ww([ee()],ap.prototype,"size",void 0);ww([ee()],ap.prototype,"name",void 0);ww([ee({type:Object})],ap.prototype,"networkImagesBySize",void 0);ww([ee()],ap.prototype,"imageSrc",void 0);ww([ee({type:Boolean})],ap.prototype,"selected",void 0);ww([ee({type:Boolean})],ap.prototype,"round",void 0);ap=ww([We("wui-network-image")],ap);const rpt=it` + @keyframes shake { + 0% { + transform: translateX(0); + } + 25% { + transform: translateX(3px); + } + 50% { + transform: translateX(-3px); + } + 75% { + transform: translateX(3px); + } + 100% { + transform: translateX(0); + } + } + + wui-flex:first-child:not(:only-child) { + position: relative; + } + + wui-loading-hexagon { + position: absolute; + } + + wui-icon-box { + position: absolute; + right: 4px; + bottom: 0; + opacity: 0; + transform: scale(0.5); + z-index: 1; + } + + wui-button { + display: none; + } + + [data-error='true'] wui-icon-box { + opacity: 1; + transform: scale(1); + } + + [data-error='true'] > wui-flex:first-child { + animation: shake 250ms cubic-bezier(0.36, 0.07, 0.19, 0.97) both; + } + + wui-button[data-retry='true'] { + display: block; + opacity: 1; + } +`;var UW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let h1=class extends He{constructor(){super(),this.network=ze.state.data?.network,this.unsubscribe=[],this.showRetry=!1,this.error=!1}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}firstUpdated(){this.onSwitchNetwork()}render(){if(!this.network)throw new Error("w3m-network-switch-view: No network provided");this.onShowRetry();const e=this.getLabel(),n=this.getSubLabel();return K` + + + + + ${this.error?null:K``} + + + + + + ${e} + ${n} + + + + + Try again + + + `}getSubLabel(){const e=ke.getConnectorId(G.state.activeChain);return ke.getAuthConnector()&&e===ye.CONNECTOR_ID.AUTH?"":this.error?"Switch can be declined if chain is not supported by a wallet or previous request is still active":"Accept connection request in your wallet"}getLabel(){const e=ke.getConnectorId(G.state.activeChain);return ke.getAuthConnector()&&e===ye.CONNECTOR_ID.AUTH?`Switching to ${this.network?.name??"Unknown"} network...`:this.error?"Switch declined":"Approve in wallet"}onShowRetry(){this.error&&!this.showRetry&&(this.showRetry=!0,this.shadowRoot?.querySelector("wui-button")?.animate([{opacity:0},{opacity:1}],{fill:"forwards",easing:"ease"}))}async onSwitchNetwork(){try{this.error=!1,G.state.activeChain!==this.network?.chainNamespace&&G.setIsSwitchingNamespace(!0),this.network&&await G.switchActiveNetwork(this.network)}catch{this.error=!0}}};h1.styles=rpt;UW([Ne()],h1.prototype,"showRetry",void 0);UW([Ne()],h1.prototype,"error",void 0);h1=UW([We("w3m-network-switch-view")],h1);const spt=it` + button { + column-gap: var(--wui-spacing-s); + padding: 7px var(--wui-spacing-l) 7px var(--wui-spacing-xs); + width: 100%; + transition: all var(--wui-ease-out-power-1) var(--wui-duration-md); + border-radius: var(--wui-border-radius-xs); + color: var(--wui-color-fg-100); + } + + button > wui-text:nth-child(2) { + display: flex; + flex: 1; + } + + button[data-transparent='true'] { + pointer-events: none; + background-color: transparent; + } + + button:hover { + background-color: var(--wui-color-gray-glass-002); + } + + button:active { + background-color: var(--wui-color-gray-glass-005); + } + + wui-image { + width: var(--wui-spacing-3xl); + height: var(--wui-spacing-3xl); + border-radius: 100%; + } + + button:disabled { + background-color: var(--wui-color-gray-glass-002); + opacity: 0.5; + cursor: not-allowed; + } + + button:disabled > wui-tag { + background-color: var(--wui-color-gray-glass-010); + color: var(--wui-color-fg-300); + } +`;var vx=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let b0=class extends He{constructor(){super(...arguments),this.imageSrc="",this.name="",this.disabled=!1,this.selected=!1,this.transparent=!1}render(){return K` + + `}checkmarkTemplate(){return this.selected?K``:null}templateNetworkImage(){return this.imageSrc?K``:this.imageSrc?null:K``}};b0.styles=[Ht,lr,spt];vx([ee()],b0.prototype,"imageSrc",void 0);vx([ee()],b0.prototype,"name",void 0);vx([ee({type:Boolean})],b0.prototype,"disabled",void 0);vx([ee({type:Boolean})],b0.prototype,"selected",void 0);vx([ee({type:Boolean})],b0.prototype,"transparent",void 0);b0=vx([We("wui-list-network")],b0);const ipt=it` + .container { + max-height: 360px; + overflow: auto; + } + + .container::-webkit-scrollbar { + display: none; + } +`;var T3=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let v0=class extends He{constructor(){super(),this.unsubscribe=[],this.network=G.state.activeCaipNetwork,this.requestedCaipNetworks=G.getCaipNetworks(),this.search="",this.onDebouncedSearch=De.debounce(e=>{this.search=e},100),this.unsubscribe.push(mi.subscribeNetworkImages(()=>this.requestUpdate()),G.subscribeKey("activeCaipNetwork",e=>this.network=e),G.subscribe(()=>{this.requestedCaipNetworks=G.getAllRequestedCaipNetworks()}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return K` + ${this.templateSearchInput()} + + ${this.networksTemplate()} + + + + + + + Your connected wallet may not support some of the networks available for this dApp + + + + What is a network + + + `}templateSearchInput(){return K` + + + + `}onInputChange(e){this.onDebouncedSearch(e.detail)}onNetworkHelp(){Lt.sendEvent({type:"track",event:"CLICK_NETWORK_HELP"}),ze.push("WhatIsANetwork")}networksTemplate(){const e=G.getAllApprovedCaipNetworkIds(),n=De.sortRequestedNetworks(e,this.requestedCaipNetworks);return this.search?this.filteredNetworks=n?.filter(r=>r?.name?.toLowerCase().includes(this.search.toLowerCase())):this.filteredNetworks=n,this.filteredNetworks?.map(r=>K` + this.onSwitchNetwork(r)} + .disabled=${this.getNetworkDisabled(r)} + data-testid=${`w3m-network-switch-${r.name??r.id}`} + > + `)}getNetworkDisabled(e){const n=e.chainNamespace,r=nt.getCaipAddress(n),s=G.getAllApprovedCaipNetworkIds(),i=G.getNetworkProp("supportsAllNetworks",n)!==!1,o=ke.getConnectorId(n),a=ke.getAuthConnector(),c=o===ye.CONNECTOR_ID.AUTH&&a;return!r||i||c?!1:!s?.includes(e.caipNetworkId)}onSwitchNetwork(e){Zde.onSwitchNetwork({network:e})}};v0.styles=ipt;T3([Ne()],v0.prototype,"network",void 0);T3([Ne()],v0.prototype,"requestedCaipNetworks",void 0);T3([Ne()],v0.prototype,"filteredNetworks",void 0);T3([Ne()],v0.prototype,"search",void 0);v0=T3([We("w3m-networks-view")],v0);const opt=it` + @keyframes shake { + 0% { + transform: translateX(0); + } + 25% { + transform: translateX(3px); + } + 50% { + transform: translateX(-3px); + } + 75% { + transform: translateX(3px); + } + 100% { + transform: translateX(0); + } + } + + wui-flex:first-child:not(:only-child) { + position: relative; + } + + wui-loading-thumbnail { + position: absolute; + } + + wui-visual { + width: var(--wui-wallet-image-size-lg); + height: var(--wui-wallet-image-size-lg); + border-radius: calc(var(--wui-border-radius-5xs) * 9 - var(--wui-border-radius-xxs)); + position: relative; + overflow: hidden; + } + + wui-visual::after { + content: ''; + display: block; + width: 100%; + height: 100%; + position: absolute; + inset: 0; + border-radius: calc(var(--wui-border-radius-5xs) * 9 - var(--wui-border-radius-xxs)); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-005); + } + + wui-icon-box { + position: absolute; + right: calc(var(--wui-spacing-3xs) * -1); + bottom: calc(var(--wui-spacing-3xs) * -1); + opacity: 0; + transform: scale(0.5); + transition: + opacity var(--wui-ease-out-power-2) var(--wui-duration-lg), + transform var(--wui-ease-out-power-2) var(--wui-duration-lg); + will-change: opacity, transform; + } + + wui-text[align='center'] { + width: 100%; + padding: 0px var(--wui-spacing-l); + } + + [data-error='true'] wui-icon-box { + opacity: 1; + transform: scale(1); + } + + [data-error='true'] > wui-flex:first-child { + animation: shake 250ms cubic-bezier(0.36, 0.07, 0.19, 0.97) both; + } + + [data-retry='false'] wui-link { + display: none; + } + + [data-retry='true'] wui-link { + display: block; + opacity: 1; + } + + wui-link { + padding: var(--wui-spacing-4xs) var(--wui-spacing-xxs); + } + + .capitalize { + text-transform: capitalize; + } +`;var Q0e=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const apt={eip155:"eth",solana:"solana",bip122:"bitcoin",polkadot:void 0};let B_=class extends He{constructor(){super(...arguments),this.unsubscribe=[],this.switchToChain=ze.state.data?.switchToChain,this.caipNetwork=ze.state.data?.network,this.activeChain=G.state.activeChain}firstUpdated(){this.unsubscribe.push(G.subscribeKey("activeChain",e=>this.activeChain=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const e=this.switchToChain?ye.CHAIN_NAME_MAP[this.switchToChain]:"supported";if(!this.switchToChain)return null;const n=ye.CHAIN_NAME_MAP[this.switchToChain];return K` + + + + Switch to ${n} + + Connected wallet doesn't support connecting to ${e} chain. You + need to connect with a different wallet. + + Switch + + + `}async switchActiveChain(){this.switchToChain&&(G.setIsSwitchingNamespace(!0),ke.setFilterByNamespace(this.switchToChain),this.caipNetwork?await G.switchActiveNetwork(this.caipNetwork):G.setActiveNamespace(this.switchToChain),ze.reset("Connect"))}};B_.styles=opt;Q0e([ee()],B_.prototype,"activeChain",void 0);B_=Q0e([We("w3m-switch-active-chain-view")],B_);var cpt=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const lpt=[{images:["network","layers","system"],title:"The system’s nuts and bolts",text:"A network is what brings the blockchain to life, as this technical infrastructure allows apps to access the ledger and smart contract services."},{images:["noun","defiAlt","dao"],title:"Designed for different uses",text:"Each network is designed differently, and may therefore suit certain apps and experiences."}];let BB=class extends He{render(){return K` + + + {De.openHref("https://ethereum.org/en/developers/docs/networks/","_blank")}} + > + Learn more + + + + `}};BB=cpt([We("w3m-what-is-a-network-view")],BB);const upt=it` + :host > wui-flex { + max-height: clamp(360px, 540px, 80vh); + overflow: scroll; + scrollbar-width: none; + } + + :host > wui-flex::-webkit-scrollbar { + display: none; + } +`;var FW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let p1=class extends He{constructor(){super(),this.swapUnsupportedChain=ze.state.data?.swapUnsupportedChain,this.unsubscribe=[],this.disconnecting=!1,this.remoteFeatures=_e.state.remoteFeatures,this.unsubscribe.push(mi.subscribeNetworkImages(()=>this.requestUpdate()),_e.subscribeKey("remoteFeatures",e=>{this.remoteFeatures=e}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return K` + + + ${this.descriptionTemplate()} + + + + ${this.networksTemplate()} + + + + + + Disconnect + + + + `}descriptionTemplate(){return this.swapUnsupportedChain?K` + + The swap feature doesn’t support your current network. Switch to an available option to + continue. + + `:K` + + This app doesn’t support your current network. Switch to an available option to continue. + + `}networksTemplate(){const e=G.getAllRequestedCaipNetworks(),n=G.getAllApprovedCaipNetworkIds(),r=De.sortRequestedNetworks(n,e);return(this.swapUnsupportedChain?r.filter(i=>wn.SWAP_SUPPORTED_NETWORKS.includes(i.caipNetworkId)):r).map(i=>K` + this.onSwitchNetwork(i)} + > + + `)}async onDisconnect(){try{this.disconnecting=!0;const e=G.state.activeChain,r=Ue.getConnections(e).length>0,s=e&&ke.state.activeConnectorIds[e],i=this.remoteFeatures?.multiWallet;await Ue.disconnect(i?{id:s,namespace:e}:{}),r&&i&&(ze.push("ProfileWallets"),Wn.showSuccess("Wallet deleted"))}catch{Lt.sendEvent({type:"track",event:"DISCONNECT_ERROR"}),Wn.showError("Failed to disconnect")}finally{this.disconnecting=!1}}async onSwitchNetwork(e){const n=nt.state.caipAddress,r=G.getAllApprovedCaipNetworkIds(),s=G.getNetworkProp("supportsAllNetworks",e.chainNamespace),i=ze.state.data;n?r?.includes(e.caipNetworkId)?await G.switchActiveNetwork(e):s?ze.push("SwitchNetwork",{...i,network:e}):ze.push("SwitchNetwork",{...i,network:e}):n||(G.setActiveCaipNetwork(e),ze.push("Connect"))}};p1.styles=upt;FW([Ne()],p1.prototype,"disconnecting",void 0);FW([Ne()],p1.prototype,"remoteFeatures",void 0);p1=FW([We("w3m-unsupported-chain-view")],p1);const dpt=it` + wui-flex { + width: 100%; + background-color: var(--wui-color-gray-glass-005); + border-radius: var(--wui-border-radius-s); + padding: var(--wui-spacing-1xs) var(--wui-spacing-s) var(--wui-spacing-1xs) + var(--wui-spacing-1xs); + } +`;var jW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let U_=class extends He{constructor(){super(...arguments),this.icon="externalLink",this.text=""}render(){return K` + + + ${this.text} + + `}};U_.styles=[Ht,lr,dpt];jW([ee()],U_.prototype,"icon",void 0);jW([ee()],U_.prototype,"text",void 0);U_=jW([We("wui-banner")],U_);const fpt=it` + :host > wui-flex { + max-height: clamp(360px, 540px, 80vh); + overflow: scroll; + scrollbar-width: none; + } + + :host > wui-flex::-webkit-scrollbar { + display: none; + } +`;var hpt=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let EN=class extends He{constructor(){super(),this.unsubscribe=[]}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return K` + + ${this.networkTemplate()} + `}networkTemplate(){const e=G.getAllRequestedCaipNetworks(),n=G.getAllApprovedCaipNetworkIds(),r=G.state.activeCaipNetwork,s=G.checkIfSmartAccountEnabled();let i=De.sortRequestedNetworks(n,e);if(s&&Ss(r?.chainNamespace)===_r.ACCOUNT_TYPES.SMART_ACCOUNT){if(!r)return null;i=[r]}return i.filter(a=>a.chainNamespace===r?.chainNamespace).map(a=>K` + + + `)}};EN.styles=fpt;EN=hpt([We("w3m-wallet-compatible-networks-view")],EN);const ppt=it` + :host { + display: flex; + justify-content: center; + align-items: center; + width: var(--wui-icon-box-size-xl); + height: var(--wui-icon-box-size-xl); + box-shadow: 0 0 0 8px var(--wui-thumbnail-border); + border-radius: var(--local-border-radius); + overflow: hidden; + } + + wui-icon { + width: 32px; + height: 32px; + } +`;var qk=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let g1=class extends He{render(){return this.style.cssText=`--local-border-radius: ${this.borderRadiusFull?"1000px":"20px"}; background-color: var(--wui-color-modal-bg);`,K`${this.templateVisual()}`}templateVisual(){return this.imageSrc?K``:K``}};g1.styles=[Ht,ppt];qk([ee()],g1.prototype,"imageSrc",void 0);qk([ee()],g1.prototype,"alt",void 0);qk([ee({type:Boolean})],g1.prototype,"borderRadiusFull",void 0);g1=qk([We("wui-visual-thumbnail")],g1);const gpt=it` + :host { + display: flex; + justify-content: center; + gap: var(--wui-spacing-2xl); + } + + wui-visual-thumbnail:nth-child(1) { + z-index: 1; + } +`;var mpt=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let UB=class extends He{constructor(){super(...arguments),this.dappImageUrl=_e.state.metadata?.icons,this.walletImageUrl=nt.state.connectedWalletInfo?.icon}firstUpdated(){const e=this.shadowRoot?.querySelectorAll("wui-visual-thumbnail");e?.[0]&&this.createAnimation(e[0],"translate(18px)"),e?.[1]&&this.createAnimation(e[1],"translate(-18px)")}render(){return K` + + + `}createAnimation(e,n){e.animate([{transform:"translateX(0px)"},{transform:n}],{duration:1600,easing:"cubic-bezier(0.56, 0, 0.48, 1)",direction:"alternate",iterations:1/0})}};UB.styles=gpt;UB=mpt([We("w3m-siwx-sign-message-thumbnails")],UB);var zW=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};let F_=class extends He{constructor(){super(...arguments),this.dappName=_e.state.metadata?.name,this.isCancelling=!1,this.isSigning=!1}render(){return K` + + + + + ${this.dappName??"Dapp"} needs to connect to your wallet + + + Sign this message to prove you own this wallet and proceed. Canceling will disconnect + you. + + + + ${this.isCancelling?"Cancelling...":"Cancel"} + + + ${this.isSigning?"Signing...":"Sign"} + + + `}async onSign(){this.isSigning=!0;try{await Da.requestSignMessage()}catch(e){if(e instanceof Error&&e.message.includes("OTP is required")){Wn.showError({message:"Something went wrong. We need to verify your account again."}),ze.replace("DataCapture");return}throw e}finally{this.isSigning=!1}}async onCancel(){this.isCancelling=!0,await Da.cancelSignMessage().finally(()=>this.isCancelling=!1)}};zW([Ne()],F_.prototype,"isCancelling",void 0);zW([Ne()],F_.prototype,"isSigning",void 0);F_=zW([We("w3m-siwx-sign-message-view")],F_);const ypt=Object.freeze(Object.defineProperty({__proto__:null,get AppKitAccountButton(){return QT},get AppKitButton(){return JT},get AppKitConnectButton(){return eN},get AppKitNetworkButton(){return tN},get W3mAccountButton(){return pB},get W3mAccountSettingsView(){return ql},get W3mAccountView(){return nN},get W3mAllWalletsView(){return S_},get W3mButton(){return gB},get W3mChooseAccountNameView(){return D_},get W3mConnectButton(){return mB},get W3mConnectView(){return oa},get W3mConnectWalletsView(){return L_},get W3mConnectingExternalView(){return AB},get W3mConnectingMultiChainView(){return O_},get W3mConnectingWcBasicView(){return xN},get W3mConnectingWcView(){return By},get W3mDownloadsView(){return OB},get W3mGetWalletView(){return $B},get W3mNetworkButton(){return yB},get W3mNetworkSwitchView(){return h1},get W3mNetworksView(){return v0},get W3mProfileWalletsView(){return Ki},get W3mRouter(){return t1},get W3mSIWXSignMessageView(){return F_},get W3mSwitchActiveChainView(){return B_},get W3mUnsupportedChainView(){return p1},get W3mWalletCompatibleNetworksView(){return EN},get W3mWhatIsANetworkView(){return BB},get W3mWhatIsAWalletView(){return MB}},Symbol.toStringTag,{value:"Module"}));Ik({tagName:"appkit-button",elementClass:JT,react:qe});Ik({tagName:"appkit-network-button",elementClass:tN,react:qe});Ik({tagName:"appkit-connect-button",elementClass:eN,react:qe});Ik({tagName:"appkit-account-button",elementClass:QT,react:qe});let TD=null;function wpt(t){return TD||(TD=vpt(t)),TD}function bpt({children:t,...e}){return wpt(e),t}let Rg;function vpt(t){return Rg||(Rg=new yat({...t,sdkVersion:De.generateSdkVersion(t.adapters??[],"react",wat)}),xut(Rg)),Rg}const WW=I.createContext(void 0);function xpt({children:t}){const[e,n]=I.useState(null),[r,s]=I.useState(!1),[i,o]=I.useState(Ct.WALLET_UNCONNECTED),{toast:a}=xf(),c=g0({namespace:"bip122"}),l=g0({namespace:"eip155"}),u=c.isConnected,d=l.isConnected,f=u||d,m=(u?c:l).address,y=I.useMemo(()=>new vh,[]);I.useEffect(()=>{if(Rg&&(c.isConnected||l.isConnected))try{Ui.create(Rg,c,l)}catch(z){console.warn("Failed to create WalletManager:",z),Ui.clear()}else Ui.clear()},[c,l]);const b=async()=>{try{return await ct.loadUser()}catch(z){return console.error("Failed to load stored user data",z),null}},v=async z=>{try{await ct.storeUser(z)}catch(N){console.error("Failed to save user data",N)}},x=async z=>{if(z.walletType==="bitcoin")return{...z,ordinalDetails:{ordinalId:"mock",ordinalDetails:"Mock ordinal for testing"},verificationStatus:Ct.ENS_ORDINAL_VERIFIED,lastChecked:Date.now()};if(z.walletType==="ethereum")try{const N=Ui.hasInstance()?await Ui.getInstance().getWalletInfo():null,T=!!N?.ensName,U=N?.ensName;return{...z,ensDetails:T&&U?{ensName:U}:void 0,verificationStatus:T?Ct.ENS_ORDINAL_VERIFIED:Ct.WALLET_CONNECTED,lastChecked:Date.now()}}catch(N){return console.error("Error verifying ENS ownership:",N),{...z,ensDetails:void 0,verificationStatus:Ct.WALLET_CONNECTED,lastChecked:Date.now()}}else throw new Error("Unknown wallet type")},E=async(z,N="7days")=>{try{if(!Ui.hasInstance())throw new Error("Wallet not connected. Please ensure your wallet is connected.");const T=Ui.getInstance();if(T.getWalletType()!==z.walletType)throw new Error(`Expected ${z.walletType} wallet, but ${T.getWalletType()} is connected.`);return await y.delegate(z.address,z.walletType,N,U=>T.signMessage(U))}catch(T){return console.error(`Error creating key delegation for ${z.walletType}:`,T),!1}};I.useEffect(()=>{f&&m?b().then(async z=>{if(z&&z.address===m)n(z),o(B(z));else{const N={address:m,walletType:u?"bitcoin":"ethereum",verificationStatus:Ct.WALLET_CONNECTED,displayPreference:_l.WALLET_ADDRESS,lastChecked:Date.now()};if(d)try{Ui.getInstance().getWalletInfo().then(async H=>{if(H?.ensName){const Y={...N,ensDetails:{ensName:H.ensName},verificationStatus:Ct.ENS_ORDINAL_VERIFIED};n(Y),o(Ct.ENS_ORDINAL_VERIFIED),await v(Y)}else n(N),o(Ct.WALLET_CONNECTED),await v(N)}).catch(async()=>{n(N),o(Ct.WALLET_CONNECTED),await v(N)})}catch{n(N),o(Ct.WALLET_CONNECTED),await v(N)}else n(N),o(Ct.WALLET_CONNECTED),await v(N);const T=u?"Bitcoin":"Ethereum",U=`${m.slice(0,6)}...${m.slice(-4)}`;a({title:"Wallet Connected",description:`Connected to ${T} with ${U}`}),a({title:"Action Required",description:`You can participate in the forum now! Verify your ${u?"Ordinal ownership":"ENS ownership"} for premium features and delegate a signing key for better UX.`})}}):(n(null),o(Ct.WALLET_UNCONNECTED))},[f,m,u,d,a]);const{disconnect:A}=l0e(),_=async()=>{try{return Rg?(await Rg.open(),!0):!1}catch(z){return console.error("Error connecting wallet:",z),!1}},k=()=>{A()},B=z=>z.walletType==="bitcoin"?z.ordinalDetails?Ct.ENS_ORDINAL_VERIFIED:Ct.WALLET_CONNECTED:z.walletType==="ethereum"?z.ensDetails?Ct.ENS_ORDINAL_VERIFIED:Ct.WALLET_CONNECTED:Ct.WALLET_UNCONNECTED,W=async()=>{if(!e||!e.address)return a({title:"Not Connected",description:"Please connect your wallet first.",variant:"destructive"}),!1;s(!0),o(Ct.WALLET_CONNECTED);try{const z=e.walletType==="bitcoin"?"Ordinal":"ENS";a({title:`Verifying ${z}`,description:`Checking your wallet for ${z} ownership...`});const N=await x(e);if(n(N),await v(N),o(B(N)),N.walletType==="bitcoin"&&N.ordinalDetails)a({title:"Ordinal Verified",description:"You now have premium access with higher relevance bonuses. We recommend delegating a key for better UX."});else if(N.walletType==="ethereum"&&N.ensDetails)a({title:"ENS Verified",description:"You now have premium access with higher relevance bonuses. We recommend delegating a key for better UX."});else{const T=N.walletType==="bitcoin"?"Ordinal Operators":"ENS domain";a({title:"Basic Access Granted",description:`No ${T} found, but you can still participate in the forum with your connected wallet.`,variant:"default"})}return!!(N.walletType==="bitcoin"&&N.ordinalDetails||N.walletType==="ethereum"&&N.ensDetails)}catch(z){console.error("Error verifying ownership:",z),o(Ct.WALLET_UNCONNECTED);let N="Failed to verify ownership. Please try again.";return z instanceof Error&&(N=z.message),a({title:"Verification Error",description:N,variant:"destructive"}),!1}finally{s(!1)}},S=async(z="7days")=>{if(!e)return a({title:"No User Found",description:"Please connect your wallet first.",variant:"destructive"}),!1;s(!0);try{if(a({title:"Starting Key Delegation",description:`This will let you post, comment, and vote without approving each action for ${z==="7days"?"1 week":"30 days"}.`}),!await E(e,z))throw new Error("Failed to create key delegation");const U=await y.getStatus(e.address,e.walletType),L={...e,browserPubKey:U.publicKey||void 0,delegationSignature:U.isValid?"valid":void 0,delegationExpiry:U.timeRemaining?Date.now()+U.timeRemaining:void 0};n(L),await v(L);const H=new Date(L.delegationExpiry).toLocaleString();return a({title:"Key Delegation Successful",description:`You can now interact with the forum without additional wallet approvals until ${H}.`}),!0}catch(N){console.error("Error delegating key:",N);let T="Failed to delegate key. Please try again.";return N instanceof Error&&(T=N.message),a({title:"Delegation Error",description:T,variant:"destructive"}),!1}finally{s(!1)}},$=async()=>await y.getStatus(e?.address,e?.walletType),R=async()=>{if(await y.clear(),e){const z={...e,delegationExpiry:void 0,browserPublicKey:void 0};n(z),await v(z)}a({title:"Delegation Cleared",description:"Your delegated signing key has been removed. You'll need to delegate a new key to continue posting and voting."})},M={signMessage:async z=>await y.signMessage(z),verifyMessage:async z=>await y.verify(z)},j={currentUser:e,isAuthenticating:r,isAuthenticated:!!(e&&f),verificationStatus:i,connectWallet:_,disconnectWallet:k,verifyOwnership:W,delegateKey:S,getDelegationStatus:$,clearDelegation:R,signMessage:M.signMessage,verifyMessage:M.verifyMessage};return w.jsx(WW.Provider,{value:j,children:t})}const Ri=[];for(let t=0;t<256;++t)Ri.push((t+256).toString(16).slice(1));function Ept(t,e=0){return(Ri[t[e+0]]+Ri[t[e+1]]+Ri[t[e+2]]+Ri[t[e+3]]+"-"+Ri[t[e+4]]+Ri[t[e+5]]+"-"+Ri[t[e+6]]+Ri[t[e+7]]+"-"+Ri[t[e+8]]+Ri[t[e+9]]+"-"+Ri[t[e+10]]+Ri[t[e+11]]+Ri[t[e+12]]+Ri[t[e+13]]+Ri[t[e+14]]+Ri[t[e+15]]).toLowerCase()}let ND;const Cpt=new Uint8Array(16);function _pt(){if(!ND){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ND=crypto.getRandomValues.bind(crypto)}return ND(Cpt)}const Spt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),_te={randomUUID:Spt};function kd(t,e,n){if(_te.randomUUID&&!e&&!t)return _te.randomUUID();t=t||{};const r=t.random??t.rng?.()??_pt();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Ept(r)}function Mt(t=0){return new Uint8Array(t)}function qc(t=0){return new Uint8Array(t)}const Apt=Math.pow(2,7),Ipt=Math.pow(2,14),Tpt=Math.pow(2,21),VW=Math.pow(2,28),HW=Math.pow(2,35),qW=Math.pow(2,42),KW=Math.pow(2,49),Pr=128,xo=127;function Vi(t){if(tNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function CN(t,e,n=0){switch(Vi(t)){case 8:e[n++]=t&255|Pr,t/=128;case 7:e[n++]=t&255|Pr,t/=128;case 6:e[n++]=t&255|Pr,t/=128;case 5:e[n++]=t&255|Pr,t/=128;case 4:e[n++]=t&255|Pr,t>>>=7;case 3:e[n++]=t&255|Pr,t>>>=7;case 2:e[n++]=t&255|Pr,t>>>=7;case 1:{e[n++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Npt(t,e,n=0){switch(Vi(t)){case 8:e.set(n++,t&255|Pr),t/=128;case 7:e.set(n++,t&255|Pr),t/=128;case 6:e.set(n++,t&255|Pr),t/=128;case 5:e.set(n++,t&255|Pr),t/=128;case 4:e.set(n++,t&255|Pr),t>>>=7;case 3:e.set(n++,t&255|Pr),t>>>=7;case 2:e.set(n++,t&255|Pr),t>>>=7;case 1:{e.set(n++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function J0e(t,e){let n=t[e],r=0;if(r+=n&xo,n>>31>0){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(n+r*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(BigInt(n)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,n=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?n===0?e<16384?e<128?1:2:e<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return Gm;if(eMpt)return this.fromNumber(Number(e));const n=e<0n;n&&(e=-e);let r=e>>32n,s=e-(r<<32n);return n&&(r=~r|0n,s=~s|0n,++s>Ste&&(s=0n,++r>Ste&&(r=0n))),new So(Number(s),Number(r))}static fromNumber(e){if(e===0)return Gm;const n=e<0;n&&(e=-e);let r=e>>>0,s=(e-r)/4294967296>>>0;return n&&(s=~s>>>0,r=~r>>>0,++r>4294967295&&(r=0,++s>4294967295&&(s=0))),new So(r,s)}static from(e){return typeof e=="number"?So.fromNumber(e):typeof e=="bigint"?So.fromBigInt(e):typeof e=="string"?So.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new So(e.low>>>0,e.high>>>0):Gm}}const Gm=new So(0,0);Gm.toBigInt=function(){return 0n};Gm.zzEncode=Gm.zzDecode=function(){return this};Gm.length=function(){return 1};const Ste=4294967296n;function Lpt(t){let e=0,n=0;for(let r=0;r191&&a<224?i[o++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,o>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s!=null?(o>0&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function eme(t,e,n){const r=n;let s,i;for(let o=0;o>6|192,e[n++]=s&63|128):(s&64512)===55296&&((i=t.charCodeAt(o+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++o,e[n++]=s>>18|240,e[n++]=s>>12&63|128,e[n++]=s>>6&63|128,e[n++]=s&63|128):(e[n++]=s>>12|224,e[n++]=s>>6&63|128,e[n++]=s&63|128);return n-r}function wu(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function ZA(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class Upt{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,wu(this,10);return e}int32(){return this.uint32()|0}sint32(){const e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw wu(this,4);return ZA(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw wu(this,4);return ZA(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw wu(this,4);const e=Rpt(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw wu(this,4);const e=$pt(this.buf,this.pos);return this.pos+=8,e}bytes(){const e=this.uint32(),n=this.pos,r=this.pos+e;if(r>this.len)throw wu(this,e);return this.pos+=e,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const e=this.bytes();return Bpt(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw wu(this,e);this.pos+=e}else do if(this.pos>=this.len)throw wu(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new So(0,0);let n=0;if(this.len-this.pos>4){for(;n<4;++n)if(e.lo=(e.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;n=0}else{for(;n<3;++n){if(this.pos>=this.len)throw wu(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<>>0,e}if(this.len-this.pos>4){for(;n<5;++n)if(e.hi=(e.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}else for(;n<5;++n){if(this.pos>=this.len)throw wu(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw wu(this,8);const e=ZA(this.buf,this.pos+=4),n=ZA(this.buf,this.pos+=4);return new So(e,n)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=J0e(this.buf,this.pos);return this.pos+=Vi(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Fpt(t){return new Upt(t instanceof Uint8Array?t:t.subarray())}function ln(t,e,n){const r=Fpt(t);return e.decode(r,void 0,n)}function jpt(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r>>0,A=new Uint8Array(E);v!==x;){for(var _=m[v],k=0,B=E-1;(_!==0||k>>0,A[B]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");b=k,v++}for(var W=E-b;W!==E&&A[W]===0;)W++;for(var S=c.repeat(y);W>>0,E=new Uint8Array(x);m[y];){var A=n[m.charCodeAt(y)];if(A===255)return;for(var _=0,k=x-1;(A!==0||_>>0,E[k]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");v=_,y++}if(m[y]!==" "){for(var B=x-v;B!==x&&E[B]===0;)B++;for(var W=new Uint8Array(b+(x-B)),S=b;B!==x;)W[S++]=E[B++];return W}}}function p(m){var y=f(m);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:p}}var Hpt=Vpt,qpt=Hpt;let Kpt=class{name;prefix;baseEncode;constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Gpt=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,n,r){this.name=e,this.prefix=n;const s=n.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return tme(this,e)}};class Zpt{decoders;constructor(e){this.decoders=e}or(e){return tme(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function tme(t,e){return new Zpt({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class Ypt{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,n,r,s){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new Kpt(e,n,r),this.decoder=new Gpt(e,n,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function Gk({name:t,prefix:e,encode:n,decode:r}){return new Ypt(t,e,n,r)}function P3({name:t,prefix:e,alphabet:n}){const{encode:r,decode:s}=qpt(n,t);return Gk({prefix:e,name:t,encode:r,decode:i=>Kk(s(i))})}function Xpt(t,e,n,r){let s=t.length;for(;t[s-1]==="=";)--s;const i=new Uint8Array(s*n/8|0);let o=0,a=0,c=0;for(let l=0;l=8&&(o-=8,i[c++]=255&a>>o)}if(o>=n||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return i}function Qpt(t,e,n){const r=e[e.length-1]==="=",s=(1<n;)o-=n,i+=e[s&a>>o];if(o!==0&&(i+=e[s&a<(t[n]=e,t),[]),cgt=nme.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function lgt(t){return t.reduce((e,n)=>(e+=agt[n],e),"")}function ugt(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const s=cgt[r];if(s==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(s)}return new Uint8Array(e)}const dgt=Gk({prefix:"🚀",name:"base256emoji",encode:lgt,decode:ugt}),fgt=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:dgt},Symbol.toStringTag,{value:"Module"})),e0=Ji({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hgt=Ji({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),pgt=Ji({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ggt=Ji({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mgt=Ji({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ygt=Ji({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wgt=Ji({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),bgt=Ji({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vgt=Ji({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),xgt=Object.freeze(Object.defineProperty({__proto__:null,base32:e0,base32hex:mgt,base32hexpad:wgt,base32hexpadupper:bgt,base32hexupper:ygt,base32pad:pgt,base32padupper:ggt,base32upper:hgt,base32z:vgt},Symbol.toStringTag,{value:"Module"})),r6=P3({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Egt=P3({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Cgt=Object.freeze(Object.defineProperty({__proto__:null,base36:r6,base36upper:Egt},Symbol.toStringTag,{value:"Module"})),ps=P3({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),_gt=P3({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Sgt=Object.freeze(Object.defineProperty({__proto__:null,base58btc:ps,base58flickr:_gt},Symbol.toStringTag,{value:"Module"})),rme=Ji({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Agt=Ji({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),YW=Ji({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Igt=Ji({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Tgt=Object.freeze(Object.defineProperty({__proto__:null,base64:rme,base64pad:Agt,base64url:YW,base64urlpad:Igt},Symbol.toStringTag,{value:"Module"})),Ngt=Ji({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Pgt=Object.freeze(Object.defineProperty({__proto__:null,base8:Ngt},Symbol.toStringTag,{value:"Module"})),kgt=Gk({prefix:"\0",name:"identity",encode:t=>Wpt(t),decode:t=>zpt(t)}),Rgt=Object.freeze(Object.defineProperty({__proto__:null,identity:kgt},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;var Ogt=sme,Ate=128,$gt=127,Dgt=~$gt,Mgt=Math.pow(2,31);function sme(t,e,n){e=e||[],n=n||0;for(var r=n;t>=Mgt;)e[n++]=t&255|Ate,t/=128;for(;t&Dgt;)e[n++]=t&255|Ate,t>>>=7;return e[n]=t|0,sme.bytes=n-r+1,e}var Lgt=FB,Bgt=128,Ite=127;function FB(t,r){var n=0,r=r||0,s=0,i=r,o,a=t.length;do{if(i>=a)throw FB.bytes=0,new RangeError("Could not decode varint");o=t[i++],n+=s<28?(o&Ite)<=Bgt);return FB.bytes=i-r,n}var Ugt=Math.pow(2,7),Fgt=Math.pow(2,14),jgt=Math.pow(2,21),zgt=Math.pow(2,28),Wgt=Math.pow(2,35),Vgt=Math.pow(2,42),Hgt=Math.pow(2,49),qgt=Math.pow(2,56),Kgt=Math.pow(2,63),Ggt=function(t){return tt.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return k3(ime,ome(t))}const L0={code:ime,name:Xgt,encode:ome,digest:Qgt},Jgt=20;function e0t({name:t,code:e,encode:n,minDigestLength:r,maxDigestLength:s}){return new t0t(t,e,n,r,s)}class t0t{name;code;encode;minDigestLength;maxDigestLength;constructor(e,n,r,s,i){this.name=e,this.code=n,this.encode=r,this.minDigestLength=s??Jgt,this.maxDigestLength=i}digest(e,n){if(n?.truncate!=null){if(n.truncatethis.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Tte(r,this.code,n?.truncate):r.then(s=>Tte(s,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function Tte(t,e,n){if(n!=null&&n!==t.byteLength){if(n>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,n)}return k3(e,t)}function n0t(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const QW=e0t({name:"sha2-256",code:18,encode:n0t("SHA-256")});function Nte(t,e){const{bytes:n,version:r}=t;switch(r){case 0:return s0t(n,zB(t),e??ps.encoder);default:return i0t(n,zB(t),e??e0.encoder)}}const Pte=new WeakMap;function zB(t){const e=Pte.get(t);if(e==null){const n=new Map;return Pte.set(t,n),n}return e}class Cr{code;version;multihash;bytes;"/";constructor(e,n,r,s){this.code=n,this.version=e,this.multihash=r,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:n}=this;if(e!==x2)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==o0t)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Cr.createV0(n)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:n}=this.multihash,r=k3(e,n);return Cr.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return Cr.equals(this,e)}static equals(e,n){const r=n;return r!=null&&e.code===r.code&&e.version===r.version&&Ygt(e.multihash,r.multihash)}toString(e){return Nte(this,e)}toJSON(){return{"/":Nte(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;const n=e;if(n instanceof Cr)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:s,multihash:i,bytes:o}=n;return new Cr(r,s,i,o??kte(r,s,i.bytes))}else if(n[a0t]===!0){const{version:r,multihash:s,code:i}=n,o=Zk(s);return Cr.create(r,i,o)}else return null}static create(e,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(n!==x2)throw new Error(`Version 0 CID must use dag-pb (code: ${x2}) block encoding`);return new Cr(e,n,r,r.bytes)}case 1:{const s=kte(e,n,r.bytes);return new Cr(e,n,r,s)}default:throw new Error("Invalid version")}}static createV0(e){return Cr.create(0,x2,e)}static createV1(e,n){return Cr.create(1,e,n)}static decode(e){const[n,r]=Cr.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(e){const n=Cr.inspectBytes(e),r=n.size-n.multihashSize,s=Kk(e.subarray(r,r+n.multihashSize));if(s.byteLength!==n.multihashSize)throw new Error("Incorrect length");const i=s.subarray(n.multihashSize-n.digestSize),o=new XW(n.multihashCode,n.digestSize,i,s);return[n.version===0?Cr.createV0(o):Cr.createV1(n.codec,o),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[d,f]=jB(e.subarray(n));return n+=f,d};let s=r(),i=x2;if(s===18?(s=0,n=0):i=r(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);const o=n,a=r(),c=r(),l=n+c,u=l-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,n){const[r,s]=r0t(e,n),i=Cr.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return zB(i).set(r,e),i}}function r0t(t,e){switch(t[0]){case"Q":{const n=e??ps;return[ps.prefix,n.decode(`${ps.prefix}${t}`)]}case ps.prefix:{const n=e??ps;return[ps.prefix,n.decode(t)]}case e0.prefix:{const n=e??e0;return[e0.prefix,n.decode(t)]}case r6.prefix:{const n=e??r6;return[r6.prefix,n.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function s0t(t,e,n){const{prefix:r}=n;if(r!==ps.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const s=e.get(r);if(s==null){const i=n.encode(t).slice(1);return e.set(r,i),i}else return s}function i0t(t,e,n){const{prefix:r}=n,s=e.get(r);if(s==null){const i=n.encode(t);return e.set(r,i),i}else return s}const x2=112,o0t=18;function kte(t,e,n){const r=AN(t),s=r+AN(e),i=new Uint8Array(s+n.byteLength);return SN(t,i,0),SN(e,i,r),i.set(n,s),i}const a0t=Symbol.for("@ipld/js-cid/CID"),WB={...Rgt,...ogt,...Pgt,...tgt,...sgt,...xgt,...Cgt,...Sgt,...Tgt,...fgt};function ame(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Rte=ame("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),PD=ame("ascii","a",t=>{let e="a";for(let n=0;n{t=t.substring(1);const e=qc(t.length);for(let n=0;n4096)return qc(o);s+o>8192&&(r=qc(8192),s=0);const a=r.subarray(s,s+=o);return s&7&&(s=(s|7)+1),a}}class Z2{fn;len;next;val;constructor(e,n,r){this.fn=e,this.len=n,this.next=void 0,this.val=r}}function kD(){}class l0t{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const u0t=c0t();function d0t(t){return globalThis.Buffer!=null?qc(t):u0t(t)}class VB{len;head;tail;states;constructor(){this.len=0,this.head=new Z2(kD,0,0),this.tail=this.head,this.states=null}_push(e,n,r){return this.tail=this.tail.next=new Z2(e,n,r),this.len+=n,this}uint32(e){return this.len+=(this.tail=this.tail.next=new h0t((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(YA,10,So.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const n=So.fromBigInt(e);return this._push(YA,n.length(),n)}uint64Number(e){return this._push(CN,Vi(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const n=So.fromBigInt(e).zzEncode();return this._push(YA,n.length(),n)}sint64Number(e){const n=So.fromNumber(e).zzEncode();return this._push(YA,n.length(),n)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(RD,1,e?1:0)}fixed32(e){return this._push(E2,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const n=So.fromBigInt(e);return this._push(E2,4,n.lo)._push(E2,4,n.hi)}fixed64Number(e){const n=So.fromNumber(e);return this._push(E2,4,n.lo)._push(E2,4,n.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(kpt,4,e)}double(e){return this._push(Opt,8,e)}bytes(e){const n=e.length>>>0;return n===0?this._push(RD,1,0):this.uint32(n)._push(p0t,n,e)}string(e){const n=Lpt(e);return n!==0?this.uint32(n)._push(eme,n,e):this._push(RD,1,0)}fork(){return this.states=new l0t(this),this.head=this.tail=new Z2(kD,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Z2(kD,0,0),this.len=0),this}ldelim(){const e=this.head,n=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=e.next,this.tail=n,this.len+=r),this}finish(){let e=this.head.next;const n=d0t(this.len);let r=0;for(;e!=null;)e.fn(e.val,n,r),r+=e.len,e=e.next;return n}}function RD(t,e,n){e[n]=t&255}function f0t(t,e,n){for(;t>127;)e[n++]=t&127|128,t>>>=7;e[n]=t}class h0t extends Z2{next;constructor(e,n){super(f0t,e,n),this.next=void 0}}function YA(t,e,n){for(;t.hi!==0;)e[n++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=t.lo&127|128,t.lo=t.lo>>>7;e[n++]=t.lo}function E2(t,e,n){e[n]=t&255,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function p0t(t,e,n){e.set(t,n)}globalThis.Buffer!=null&&(VB.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(g0t,e,t),this},VB.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(m0t,e,t),this});function g0t(t,e,n){e.set(t,n)}function m0t(t,e,n){t.length<40?eme(t,e,n):e.utf8Write!=null?e.utf8Write(t,n):e.set(Jt(t),n)}function y0t(){return new VB}function un(t,e){const n=y0t();return e.encode(t,n,{lengthDelimited:!1}),n.finish()}var IN;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(IN||(IN={}));function lme(t,e,n,r){return{name:t,type:e,encode:n,decode:r}}function JW(t){function e(s){if(t[s.toString()]==null)throw new Error("Invalid enum value");return t[s]}const n=function(i,o){const a=e(i);o.int32(a)},r=function(i){const o=i.int32();return e(o)};return lme("enum",IN.VARINT,n,r)}function dn(t,e){return lme("message",IN.LENGTH_DELIMITED,t,e)}class Gi extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class Ote extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}var TN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.proof!=null&&n.proof.byteLength>0&&(r.uint32(10),r.bytes(n.proof)),n.merkleRoot!=null&&n.merkleRoot.byteLength>0&&(r.uint32(18),r.bytes(n.merkleRoot)),n.epoch!=null&&n.epoch.byteLength>0&&(r.uint32(26),r.bytes(n.epoch)),n.shareX!=null&&n.shareX.byteLength>0&&(r.uint32(34),r.bytes(n.shareX)),n.shareY!=null&&n.shareY.byteLength>0&&(r.uint32(42),r.bytes(n.shareY)),n.nullifier!=null&&n.nullifier.byteLength>0&&(r.uint32(50),r.bytes(n.nullifier)),n.rlnIdentifier!=null&&n.rlnIdentifier.byteLength>0&&(r.uint32(58),r.bytes(n.rlnIdentifier)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={proof:Mt(0),merkleRoot:Mt(0),epoch:Mt(0),shareX:Mt(0),shareY:Mt(0),nullifier:Mt(0),rlnIdentifier:Mt(0)},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.proof=n.bytes();break}case 2:{i.merkleRoot=n.bytes();break}case 3:{i.epoch=n.bytes();break}case 4:{i.shareX=n.bytes();break}case 5:{i.shareY=n.bytes();break}case 6:{i.nullifier=n.bytes();break}case 7:{i.rlnIdentifier=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(TN||(TN={}));var NN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.payload!=null&&n.payload.byteLength>0&&(r.uint32(10),r.bytes(n.payload)),n.contentTopic!=null&&n.contentTopic!==""&&(r.uint32(18),r.string(n.contentTopic)),n.version!=null&&(r.uint32(24),r.uint32(n.version)),n.timestamp!=null&&(r.uint32(80),r.sint64(n.timestamp)),n.meta!=null&&(r.uint32(90),r.bytes(n.meta)),n.rateLimitProof!=null&&(r.uint32(170),TN.codec().encode(n.rateLimitProof,r)),n.ephemeral!=null&&(r.uint32(248),r.bool(n.ephemeral)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={payload:Mt(0),contentTopic:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.payload=n.bytes();break}case 2:{i.contentTopic=n.string();break}case 3:{i.version=n.uint32();break}case 10:{i.timestamp=n.sint64();break}case 11:{i.meta=n.bytes();break}case 21:{i.rateLimitProof=TN.codec().decode(n,n.uint32(),{limits:s.limits?.rateLimitProof});break}case 31:{i.ephemeral=n.bool();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(NN||(NN={}));var PN;(function(t){(function(n){let r;n.codec=()=>(r==null&&(r=dn((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.contentTopic!=null&&s.contentTopic!==""&&(i.uint32(10),i.string(s.contentTopic)),o.lengthDelimited!==!1&&i.ldelim()},(s,i,o={})=>{const a={contentTopic:""},c=i==null?s.len:s.pos+i;for(;s.pos>>3){case 1:{a.contentTopic=s.string();break}default:{s.skipType(l&7);break}}}return a})),r),n.encode=s=>un(s,n.codec()),n.decode=(s,i)=>ln(s,n.codec(),i)})(t.ContentFilter||(t.ContentFilter={}));let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.subscribe!=null&&n.subscribe!==!1&&(r.uint32(8),r.bool(n.subscribe)),n.topic!=null&&n.topic!==""&&(r.uint32(18),r.string(n.topic)),n.contentFilters!=null)for(const i of n.contentFilters)r.uint32(26),t.ContentFilter.codec().encode(i,r);s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={subscribe:!1,topic:"",contentFilters:[]},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.subscribe=n.bool();break}case 2:{i.topic=n.string();break}case 3:{if(s.limits?.contentFilters!=null&&i.contentFilters.length===s.limits.contentFilters)throw new Gi('Decode error - map field "contentFilters" had too many elements');i.contentFilters.push(t.ContentFilter.codec().decode(n,n.uint32(),{limits:s.limits?.contentFilters$}));break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(PN||(PN={}));var kN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.messages!=null)for(const i of n.messages)r.uint32(10),ON.codec().encode(i,r);s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={messages:[]},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{if(s.limits?.messages!=null&&i.messages.length===s.limits.messages)throw new Gi('Decode error - map field "messages" had too many elements');i.messages.push(ON.codec().decode(n,n.uint32(),{limits:s.limits?.messages$}));break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(kN||(kN={}));var $te;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.requestId!=null&&n.requestId!==""&&(r.uint32(10),r.string(n.requestId)),n.request!=null&&(r.uint32(18),PN.codec().encode(n.request,r)),n.push!=null&&(r.uint32(26),kN.codec().encode(n.push,r)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={requestId:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.requestId=n.string();break}case 2:{i.request=PN.codec().decode(n,n.uint32(),{limits:s.limits?.request});break}case 3:{i.push=kN.codec().decode(n,n.uint32(),{limits:s.limits?.push});break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})($te||($te={}));var RN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.proof!=null&&n.proof.byteLength>0&&(r.uint32(10),r.bytes(n.proof)),n.merkleRoot!=null&&n.merkleRoot.byteLength>0&&(r.uint32(18),r.bytes(n.merkleRoot)),n.epoch!=null&&n.epoch.byteLength>0&&(r.uint32(26),r.bytes(n.epoch)),n.shareX!=null&&n.shareX.byteLength>0&&(r.uint32(34),r.bytes(n.shareX)),n.shareY!=null&&n.shareY.byteLength>0&&(r.uint32(42),r.bytes(n.shareY)),n.nullifier!=null&&n.nullifier.byteLength>0&&(r.uint32(50),r.bytes(n.nullifier)),n.rlnIdentifier!=null&&n.rlnIdentifier.byteLength>0&&(r.uint32(58),r.bytes(n.rlnIdentifier)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={proof:Mt(0),merkleRoot:Mt(0),epoch:Mt(0),shareX:Mt(0),shareY:Mt(0),nullifier:Mt(0),rlnIdentifier:Mt(0)},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.proof=n.bytes();break}case 2:{i.merkleRoot=n.bytes();break}case 3:{i.epoch=n.bytes();break}case 4:{i.shareX=n.bytes();break}case 5:{i.shareY=n.bytes();break}case 6:{i.nullifier=n.bytes();break}case 7:{i.rlnIdentifier=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(RN||(RN={}));var ON;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.payload!=null&&n.payload.byteLength>0&&(r.uint32(10),r.bytes(n.payload)),n.contentTopic!=null&&n.contentTopic!==""&&(r.uint32(18),r.string(n.contentTopic)),n.version!=null&&(r.uint32(24),r.uint32(n.version)),n.timestamp!=null&&(r.uint32(80),r.sint64(n.timestamp)),n.meta!=null&&(r.uint32(90),r.bytes(n.meta)),n.rateLimitProof!=null&&(r.uint32(170),RN.codec().encode(n.rateLimitProof,r)),n.ephemeral!=null&&(r.uint32(248),r.bool(n.ephemeral)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={payload:Mt(0),contentTopic:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.payload=n.bytes();break}case 2:{i.contentTopic=n.string();break}case 3:{i.version=n.uint32();break}case 10:{i.timestamp=n.sint64();break}case 11:{i.meta=n.bytes();break}case 21:{i.rateLimitProof=RN.codec().decode(n,n.uint32(),{limits:s.limits?.rateLimitProof});break}case 31:{i.ephemeral=n.bool();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(ON||(ON={}));var Dte;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.contentTopic!=null&&n.contentTopic!==""&&(r.uint32(18),r.string(n.contentTopic)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={contentTopic:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 2:{i.contentTopic=n.string();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(Dte||(Dte={}));var gg;(function(t){let e;(function(s){s.SUBSCRIBER_PING="SUBSCRIBER_PING",s.SUBSCRIBE="SUBSCRIBE",s.UNSUBSCRIBE="UNSUBSCRIBE",s.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"})(e=t.FilterSubscribeType||(t.FilterSubscribeType={}));let n;(function(s){s[s.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",s[s.SUBSCRIBE=1]="SUBSCRIBE",s[s.UNSUBSCRIBE=2]="UNSUBSCRIBE",s[s.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"})(n||(n={})),function(s){s.codec=()=>JW(n)}(e=t.FilterSubscribeType||(t.FilterSubscribeType={}));let r;t.codec=()=>(r==null&&(r=dn((s,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),s.requestId!=null&&s.requestId!==""&&(i.uint32(10),i.string(s.requestId)),s.filterSubscribeType!=null&&n[s.filterSubscribeType]!==0&&(i.uint32(16),t.FilterSubscribeType.codec().encode(s.filterSubscribeType,i)),s.pubsubTopic!=null&&(i.uint32(82),i.string(s.pubsubTopic)),s.contentTopics!=null)for(const a of s.contentTopics)i.uint32(90),i.string(a);o.lengthDelimited!==!1&&i.ldelim()},(s,i,o={})=>{const a={requestId:"",filterSubscribeType:e.SUBSCRIBER_PING,contentTopics:[]},c=i==null?s.len:s.pos+i;for(;s.pos>>3){case 1:{a.requestId=s.string();break}case 2:{a.filterSubscribeType=t.FilterSubscribeType.codec().decode(s);break}case 10:{a.pubsubTopic=s.string();break}case 11:{if(o.limits?.contentTopics!=null&&a.contentTopics.length===o.limits.contentTopics)throw new Gi('Decode error - map field "contentTopics" had too many elements');a.contentTopics.push(s.string());break}default:{s.skipType(l&7);break}}}return a})),r),t.encode=s=>un(s,t.codec()),t.decode=(s,i)=>ln(s,t.codec(),i)})(gg||(gg={}));var $N;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.requestId!=null&&n.requestId!==""&&(r.uint32(10),r.string(n.requestId)),n.statusCode!=null&&n.statusCode!==0&&(r.uint32(80),r.uint32(n.statusCode)),n.statusDesc!=null&&(r.uint32(90),r.string(n.statusDesc)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={requestId:"",statusCode:0},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.requestId=n.string();break}case 10:{i.statusCode=n.uint32();break}case 11:{i.statusDesc=n.string();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})($N||($N={}));var DN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.wakuMessage!=null&&(r.uint32(10),LN.codec().encode(n.wakuMessage,r)),n.pubsubTopic!=null&&(r.uint32(18),r.string(n.pubsubTopic)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.wakuMessage=LN.codec().decode(n,n.uint32(),{limits:s.limits?.wakuMessage});break}case 2:{i.pubsubTopic=n.string();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(DN||(DN={}));var MN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.proof!=null&&n.proof.byteLength>0&&(r.uint32(10),r.bytes(n.proof)),n.merkleRoot!=null&&n.merkleRoot.byteLength>0&&(r.uint32(18),r.bytes(n.merkleRoot)),n.epoch!=null&&n.epoch.byteLength>0&&(r.uint32(26),r.bytes(n.epoch)),n.shareX!=null&&n.shareX.byteLength>0&&(r.uint32(34),r.bytes(n.shareX)),n.shareY!=null&&n.shareY.byteLength>0&&(r.uint32(42),r.bytes(n.shareY)),n.nullifier!=null&&n.nullifier.byteLength>0&&(r.uint32(50),r.bytes(n.nullifier)),n.rlnIdentifier!=null&&n.rlnIdentifier.byteLength>0&&(r.uint32(58),r.bytes(n.rlnIdentifier)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={proof:Mt(0),merkleRoot:Mt(0),epoch:Mt(0),shareX:Mt(0),shareY:Mt(0),nullifier:Mt(0),rlnIdentifier:Mt(0)},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.proof=n.bytes();break}case 2:{i.merkleRoot=n.bytes();break}case 3:{i.epoch=n.bytes();break}case 4:{i.shareX=n.bytes();break}case 5:{i.shareY=n.bytes();break}case 6:{i.nullifier=n.bytes();break}case 7:{i.rlnIdentifier=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(MN||(MN={}));var LN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.payload!=null&&n.payload.byteLength>0&&(r.uint32(10),r.bytes(n.payload)),n.contentTopic!=null&&n.contentTopic!==""&&(r.uint32(18),r.string(n.contentTopic)),n.version!=null&&(r.uint32(24),r.uint32(n.version)),n.timestamp!=null&&(r.uint32(80),r.sint64(n.timestamp)),n.meta!=null&&(r.uint32(90),r.bytes(n.meta)),n.rateLimitProof!=null&&(r.uint32(170),MN.codec().encode(n.rateLimitProof,r)),n.ephemeral!=null&&(r.uint32(248),r.bool(n.ephemeral)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={payload:Mt(0),contentTopic:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.payload=n.bytes();break}case 2:{i.contentTopic=n.string();break}case 3:{i.version=n.uint32();break}case 10:{i.timestamp=n.sint64();break}case 11:{i.meta=n.bytes();break}case 21:{i.rateLimitProof=MN.codec().decode(n,n.uint32(),{limits:s.limits?.rateLimitProof});break}case 31:{i.ephemeral=n.bool();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(LN||(LN={}));var BN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.pubsubTopic!=null&&n.pubsubTopic!==""&&(r.uint32(10),r.string(n.pubsubTopic)),n.message!=null&&(r.uint32(18),m1.codec().encode(n.message,r)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={pubsubTopic:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.pubsubTopic=n.string();break}case 2:{i.message=m1.codec().decode(n,n.uint32(),{limits:s.limits?.message});break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(BN||(BN={}));var UN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.isSuccess!=null&&n.isSuccess!==!1&&(r.uint32(8),r.bool(n.isSuccess)),n.info!=null&&(r.uint32(18),r.string(n.info)),n.statusCode!=null&&(r.uint32(80),r.uint32(n.statusCode)),n.statusDesc!=null&&(r.uint32(90),r.string(n.statusDesc)),n.relayPeerCount!=null&&(r.uint32(96),r.uint32(n.relayPeerCount)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={isSuccess:!1},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.isSuccess=n.bool();break}case 2:{i.info=n.string();break}case 10:{i.statusCode=n.uint32();break}case 11:{i.statusDesc=n.string();break}case 12:{i.relayPeerCount=n.uint32();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(UN||(UN={}));var FN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.requestId!=null&&n.requestId!==""&&(r.uint32(10),r.string(n.requestId)),n.request!=null&&(r.uint32(18),BN.codec().encode(n.request,r)),n.response!=null&&(r.uint32(26),UN.codec().encode(n.response,r)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={requestId:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.requestId=n.string();break}case 2:{i.request=BN.codec().decode(n,n.uint32(),{limits:s.limits?.request});break}case 3:{i.response=UN.codec().decode(n,n.uint32(),{limits:s.limits?.response});break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(FN||(FN={}));var Mte;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.requestId!=null&&n.requestId!==""&&(r.uint32(10),r.string(n.requestId)),n.pubsubTopic!=null&&(r.uint32(162),r.string(n.pubsubTopic)),n.message!=null&&(r.uint32(170),m1.codec().encode(n.message,r)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={requestId:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.requestId=n.string();break}case 20:{i.pubsubTopic=n.string();break}case 21:{i.message=m1.codec().decode(n,n.uint32(),{limits:s.limits?.message});break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(Mte||(Mte={}));var Lte;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.requestId!=null&&n.requestId!==""&&(r.uint32(10),r.string(n.requestId)),n.statusCode!=null&&n.statusCode!==0&&(r.uint32(80),r.uint32(n.statusCode)),n.statusDesc!=null&&(r.uint32(90),r.string(n.statusDesc)),n.relayPeerCount!=null&&(r.uint32(96),r.uint32(n.relayPeerCount)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={requestId:"",statusCode:0},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.requestId=n.string();break}case 10:{i.statusCode=n.uint32();break}case 11:{i.statusDesc=n.string();break}case 12:{i.relayPeerCount=n.uint32();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(Lte||(Lte={}));var jN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.proof!=null&&n.proof.byteLength>0&&(r.uint32(10),r.bytes(n.proof)),n.merkleRoot!=null&&n.merkleRoot.byteLength>0&&(r.uint32(18),r.bytes(n.merkleRoot)),n.epoch!=null&&n.epoch.byteLength>0&&(r.uint32(26),r.bytes(n.epoch)),n.shareX!=null&&n.shareX.byteLength>0&&(r.uint32(34),r.bytes(n.shareX)),n.shareY!=null&&n.shareY.byteLength>0&&(r.uint32(42),r.bytes(n.shareY)),n.nullifier!=null&&n.nullifier.byteLength>0&&(r.uint32(50),r.bytes(n.nullifier)),n.rlnIdentifier!=null&&n.rlnIdentifier.byteLength>0&&(r.uint32(58),r.bytes(n.rlnIdentifier)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={proof:Mt(0),merkleRoot:Mt(0),epoch:Mt(0),shareX:Mt(0),shareY:Mt(0),nullifier:Mt(0),rlnIdentifier:Mt(0)},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.proof=n.bytes();break}case 2:{i.merkleRoot=n.bytes();break}case 3:{i.epoch=n.bytes();break}case 4:{i.shareX=n.bytes();break}case 5:{i.shareY=n.bytes();break}case 6:{i.nullifier=n.bytes();break}case 7:{i.rlnIdentifier=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(jN||(jN={}));var m1;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.payload!=null&&n.payload.byteLength>0&&(r.uint32(10),r.bytes(n.payload)),n.contentTopic!=null&&n.contentTopic!==""&&(r.uint32(18),r.string(n.contentTopic)),n.version!=null&&(r.uint32(24),r.uint32(n.version)),n.timestamp!=null&&(r.uint32(80),r.sint64(n.timestamp)),n.meta!=null&&(r.uint32(90),r.bytes(n.meta)),n.rateLimitProof!=null&&(r.uint32(170),jN.codec().encode(n.rateLimitProof,r)),n.ephemeral!=null&&(r.uint32(248),r.bool(n.ephemeral)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={payload:Mt(0),contentTopic:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.payload=n.bytes();break}case 2:{i.contentTopic=n.string();break}case 3:{i.version=n.uint32();break}case 10:{i.timestamp=n.sint64();break}case 11:{i.meta=n.bytes();break}case 21:{i.rateLimitProof=jN.codec().decode(n,n.uint32(),{limits:s.limits?.rateLimitProof});break}case 31:{i.ephemeral=n.bool();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(m1||(m1={}));var zN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.messageHash!=null&&(r.uint32(10),r.bytes(n.messageHash)),n.message!=null&&(r.uint32(18),qN.codec().encode(n.message,r)),n.pubsubTopic!=null&&(r.uint32(26),r.string(n.pubsubTopic)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.messageHash=n.bytes();break}case 2:{i.message=qN.codec().decode(n,n.uint32(),{limits:s.limits?.message});break}case 3:{i.pubsubTopic=n.string();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(zN||(zN={}));var WN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.requestId!=null&&n.requestId!==""&&(r.uint32(10),r.string(n.requestId)),n.includeData!=null&&n.includeData!==!1&&(r.uint32(16),r.bool(n.includeData)),n.pubsubTopic!=null&&(r.uint32(82),r.string(n.pubsubTopic)),n.contentTopics!=null)for(const i of n.contentTopics)r.uint32(90),r.string(i);if(n.timeStart!=null&&(r.uint32(96),r.sint64(n.timeStart)),n.timeEnd!=null&&(r.uint32(104),r.sint64(n.timeEnd)),n.messageHashes!=null)for(const i of n.messageHashes)r.uint32(162),r.bytes(i);n.paginationCursor!=null&&(r.uint32(410),r.bytes(n.paginationCursor)),n.paginationForward!=null&&n.paginationForward!==!1&&(r.uint32(416),r.bool(n.paginationForward)),n.paginationLimit!=null&&(r.uint32(424),r.uint64(n.paginationLimit)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.requestId=n.string();break}case 2:{i.includeData=n.bool();break}case 10:{i.pubsubTopic=n.string();break}case 11:{if(s.limits?.contentTopics!=null&&i.contentTopics.length===s.limits.contentTopics)throw new Gi('Decode error - map field "contentTopics" had too many elements');i.contentTopics.push(n.string());break}case 12:{i.timeStart=n.sint64();break}case 13:{i.timeEnd=n.sint64();break}case 20:{if(s.limits?.messageHashes!=null&&i.messageHashes.length===s.limits.messageHashes)throw new Gi('Decode error - map field "messageHashes" had too many elements');i.messageHashes.push(n.bytes());break}case 51:{i.paginationCursor=n.bytes();break}case 52:{i.paginationForward=n.bool();break}case 53:{i.paginationLimit=n.uint64();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(WN||(WN={}));var VN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.requestId!=null&&n.requestId!==""&&(r.uint32(10),r.string(n.requestId)),n.statusCode!=null&&(r.uint32(80),r.uint32(n.statusCode)),n.statusDesc!=null&&(r.uint32(90),r.string(n.statusDesc)),n.messages!=null)for(const i of n.messages)r.uint32(162),zN.codec().encode(i,r);n.paginationCursor!=null&&(r.uint32(410),r.bytes(n.paginationCursor)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={requestId:"",messages:[]},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.requestId=n.string();break}case 10:{i.statusCode=n.uint32();break}case 11:{i.statusDesc=n.string();break}case 20:{if(s.limits?.messages!=null&&i.messages.length===s.limits.messages)throw new Gi('Decode error - map field "messages" had too many elements');i.messages.push(zN.codec().decode(n,n.uint32(),{limits:s.limits?.messages$}));break}case 51:{i.paginationCursor=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(VN||(VN={}));var HN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.proof!=null&&n.proof.byteLength>0&&(r.uint32(10),r.bytes(n.proof)),n.merkleRoot!=null&&n.merkleRoot.byteLength>0&&(r.uint32(18),r.bytes(n.merkleRoot)),n.epoch!=null&&n.epoch.byteLength>0&&(r.uint32(26),r.bytes(n.epoch)),n.shareX!=null&&n.shareX.byteLength>0&&(r.uint32(34),r.bytes(n.shareX)),n.shareY!=null&&n.shareY.byteLength>0&&(r.uint32(42),r.bytes(n.shareY)),n.nullifier!=null&&n.nullifier.byteLength>0&&(r.uint32(50),r.bytes(n.nullifier)),n.rlnIdentifier!=null&&n.rlnIdentifier.byteLength>0&&(r.uint32(58),r.bytes(n.rlnIdentifier)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={proof:Mt(0),merkleRoot:Mt(0),epoch:Mt(0),shareX:Mt(0),shareY:Mt(0),nullifier:Mt(0),rlnIdentifier:Mt(0)},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.proof=n.bytes();break}case 2:{i.merkleRoot=n.bytes();break}case 3:{i.epoch=n.bytes();break}case 4:{i.shareX=n.bytes();break}case 5:{i.shareY=n.bytes();break}case 6:{i.nullifier=n.bytes();break}case 7:{i.rlnIdentifier=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(HN||(HN={}));var qN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.payload!=null&&n.payload.byteLength>0&&(r.uint32(10),r.bytes(n.payload)),n.contentTopic!=null&&n.contentTopic!==""&&(r.uint32(18),r.string(n.contentTopic)),n.version!=null&&(r.uint32(24),r.uint32(n.version)),n.timestamp!=null&&(r.uint32(80),r.sint64(n.timestamp)),n.meta!=null&&(r.uint32(90),r.bytes(n.meta)),n.rateLimitProof!=null&&(r.uint32(170),HN.codec().encode(n.rateLimitProof,r)),n.ephemeral!=null&&(r.uint32(248),r.bool(n.ephemeral)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={payload:Mt(0),contentTopic:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.payload=n.bytes();break}case 2:{i.contentTopic=n.string();break}case 3:{i.version=n.uint32();break}case 10:{i.timestamp=n.sint64();break}case 11:{i.meta=n.bytes();break}case 21:{i.rateLimitProof=HN.codec().decode(n,n.uint32(),{limits:s.limits?.rateLimitProof});break}case 31:{i.ephemeral=n.bool();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(qN||(qN={}));var KN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.enr!=null&&(r.uint32(10),r.bytes(n.enr)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.enr=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(KN||(KN={}));var GN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.numPeers!=null&&(r.uint32(8),r.uint64(n.numPeers)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.numPeers=n.uint64();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(GN||(GN={}));var ZN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.peerInfos!=null)for(const i of n.peerInfos)r.uint32(10),KN.codec().encode(i,r);s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={peerInfos:[]},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{if(s.limits?.peerInfos!=null&&i.peerInfos.length===s.limits.peerInfos)throw new Gi('Decode error - map field "peerInfos" had too many elements');i.peerInfos.push(KN.codec().decode(n,n.uint32(),{limits:s.limits?.peerInfos$}));break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(ZN||(ZN={}));var YN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.query!=null&&(r.uint32(10),GN.codec().encode(n.query,r)),n.response!=null&&(r.uint32(18),ZN.codec().encode(n.response,r)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.query=GN.codec().decode(n,n.uint32(),{limits:s.limits?.query});break}case 2:{i.response=ZN.codec().decode(n,n.uint32(),{limits:s.limits?.response});break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(YN||(YN={}));var HB;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.clusterId!=null&&(r.uint32(8),r.uint32(n.clusterId)),n.shards!=null)for(const i of n.shards)r.uint32(16),r.uint32(i);s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={shards:[]},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.clusterId=n.uint32();break}case 2:{if(s.limits?.shards!=null&&i.shards.length===s.limits.shards)throw new Gi('Decode error - map field "shards" had too many elements');i.shards.push(n.uint32());break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(HB||(HB={}));var XN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.clusterId!=null&&(r.uint32(8),r.uint32(n.clusterId)),n.shards!=null)for(const i of n.shards)r.uint32(16),r.uint32(i);s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={shards:[]},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.clusterId=n.uint32();break}case 2:{if(s.limits?.shards!=null&&i.shards.length===s.limits.shards)throw new Gi('Decode error - map field "shards" had too many elements');i.shards.push(n.uint32());break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(XN||(XN={}));var QN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.messageId!=null&&n.messageId!==""&&(r.uint32(10),r.string(n.messageId)),n.retrievalHint!=null&&(r.uint32(18),r.bytes(n.retrievalHint)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={messageId:""},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.messageId=n.string();break}case 2:{i.retrievalHint=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(QN||(QN={}));var JN;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.senderId!=null&&n.senderId!==""&&(r.uint32(10),r.string(n.senderId)),n.messageId!=null&&n.messageId!==""&&(r.uint32(18),r.string(n.messageId)),n.channelId!=null&&n.channelId!==""&&(r.uint32(26),r.string(n.channelId)),n.lamportTimestamp!=null&&(r.uint32(80),r.int32(n.lamportTimestamp)),n.causalHistory!=null)for(const i of n.causalHistory)r.uint32(90),QN.codec().encode(i,r);n.bloomFilter!=null&&(r.uint32(98),r.bytes(n.bloomFilter)),n.content!=null&&(r.uint32(162),r.bytes(n.content)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={senderId:"",messageId:"",channelId:"",causalHistory:[]},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.senderId=n.string();break}case 2:{i.messageId=n.string();break}case 3:{i.channelId=n.string();break}case 10:{i.lamportTimestamp=n.int32();break}case 11:{if(s.limits?.causalHistory!=null&&i.causalHistory.length===s.limits.causalHistory)throw new Gi('Decode error - map field "causalHistory" had too many elements');i.causalHistory.push(QN.codec().decode(n,n.uint32(),{limits:s.limits?.causalHistory$}));break}case 12:{i.bloomFilter=n.bytes();break}case 20:{i.content=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(JN||(JN={}));function eV(t){return!!t}function w0t(t){if(t.length<=1)return t;const e=()=>Math.floor(Math.random()*Math.floor(t.length));for(let n=0;nt.length/b0t<=v0t;function C0t(t){return"clusterId"in t&&"numShardsInCluster"in t}function hn(t,e="utf8"){const n=cme[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}function ume(t){if(typeof t=="string"){const e=t.replace(/^0x/i,"");return Jt(e.toLowerCase(),"base16")}return t}function _0t(t){const e=new ArrayBuffer(8),n=new DataView(e);return typeof t=="number"?n.setFloat64(0,t,!1):n.setBigInt64(0,t,!1),new Uint8Array(e)}const Yk=t=>hn(t,"base16"),j_=t=>hn(t,"utf8"),y1=t=>Jt(t,"utf8");function dme(t,e){const n=t.reduce((i,o)=>i+o.length,0),r=new Uint8Array(n);let s=0;for(const i of t)r.set(i,s),s+=i.length;return r}const fme=(t,e)=>`/waku/2/rs/${t}/${e}`,hme=t=>{const e=t.split("/");if(e.length!=6||e[1]!=="waku"||e[2]!=="2"||e[3]!=="rs")throw new Error("Invalid pubsub topic");const n=parseInt(e[4]),r=parseInt(e[5]);if(isNaN(n)||isNaN(r))throw new Error("Invalid clusterId or shard");return{clusterId:n,shard:r}};function pme(t){const e=t.split("/");if(e.length<5||e.length>6)throw Error(`Content topic format is invalid: ${t}`);let n=0;if(e.length==6){if(n=parseInt(e[1]),isNaN(n))throw new Error(`Invalid generation field in content topic: ${t}`);if(n>0)throw new Error(`Generation greater than 0 is not supported: ${t}`)}const r=e.splice(-4);if(r[0].length==0)throw new Error(`Application field cannot be empty: ${t}`);if(r[1].length==0)throw new Error(`Version field cannot be empty: ${t}`);if(r[2].length==0)throw new Error(`Topic name field cannot be empty: ${t}`);if(r[3].length==0)throw new Error(`Encoding field cannot be empty: ${t}`);return{generation:n,application:r[0],version:r[1],topicName:r[2],encoding:r[3]}}function S0t(t,e){const{application:n,version:r}=pme(t),s=Th(dme([y1(n),y1(r)])),i=new DataView(s.buffer.slice(-8));return Number(i.getBigUint64(0,!1)%BigInt(e))}class gme{networkConfig;pubsubTopic;shardId;constructor(e,n,r){this.networkConfig=e,this.pubsubTopic=n,this.shardId=r}}class tV extends gme{networkConfig;pubsubTopic;shardId;contentTopic;static fromContentTopic(e,n){pme(e);const r=S0t(e,n.numShardsInCluster),s=fme(n.clusterId,r);return new tV(n,s,r,e)}constructor(e,n,r,s){super(e,n,r),this.networkConfig=e,this.pubsubTopic=n,this.shardId=r,this.contentTopic=s}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!0}get isStaticSharding(){return!1}}class z_ extends gme{networkConfig;pubsubTopic;shardId;static fromShard(e,n){const r=fme(n.clusterId,e);return new z_(n,r,e)}static fromPubsubTopic(e,n){const{clusterId:r,shard:s}=hme(e);if(r!=n.clusterId)throw"Pubsub topic does not match network config's cluster id";return new z_(n,e,s)}constructor(e,n,r){super(e,n,r),this.networkConfig=e,this.pubsubTopic=n,this.shardId=r}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!1}get isStaticSharding(){return!0}}function mme(t,e){if(C0t(t)){if(e.contentTopic)return tV.fromContentTopic(e.contentTopic,t);throw new Error("AutoSharding requires contentTopic")}else{if(e.shardId!==void 0)return z_.fromShard(e.shardId,t);if(e.pubsubTopic)return z_.fromPubsubTopic(e.pubsubTopic,t);throw new Error("StaticSharding requires shardId or pubsubTopic")}}const qB=t=>{if(t=new Uint8Array(t),t.length<3)throw new Error("Insufficient data");const e=new DataView(t.buffer),n=e.getUint16(0),r=[];if(t.length===130)for(let s=0;s<1024;s++){const i=Math.floor(s/8)+2,o=7-s%8;e.getUint8(i)&1<=t.length)throw new Error("Unexpected end of data");r.push(e.getUint16(o))}}return{clusterId:n,shards:r}},nV=t=>{const{clusterId:e,shards:n}=t,r=n.length>=64?130:3+2*n.length,s=new ArrayBuffer(r),i=new DataView(s);if(i.setUint16(0,e),n.length>=64)for(const o of n){const a=Math.floor(o/8)+2,c=7-o%8;i.setUint8(a,i.getUint8(a)|1<0)return o(u);if(f==="number"&&isFinite(u))return d.long?c(u):a(u);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(u))};function o(u){if(u=String(u),!(u.length>100)){var d=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(u);if(d){var f=parseFloat(d[1]),p=(d[2]||"ms").toLowerCase();switch(p){case"years":case"year":case"yrs":case"yr":case"y":return f*i;case"weeks":case"week":case"w":return f*s;case"days":case"day":case"d":return f*r;case"hours":case"hour":case"hrs":case"hr":case"h":return f*n;case"minutes":case"minute":case"mins":case"min":case"m":return f*e;case"seconds":case"second":case"secs":case"sec":case"s":return f*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function a(u){var d=Math.abs(u);return d>=r?Math.round(u/r)+"d":d>=n?Math.round(u/n)+"h":d>=e?Math.round(u/e)+"m":d>=t?Math.round(u/t)+"s":u+"ms"}function c(u){var d=Math.abs(u);return d>=r?l(u,d,r,"day"):d>=n?l(u,d,n,"hour"):d>=e?l(u,d,e,"minute"):d>=t?l(u,d,t,"second"):u+" ms"}function l(u,d,f,p){var m=d>=f*1.5;return Math.round(u/f)+" "+p+(m?"s":"")}return OD}function I0t(t){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=s,n.enabled=a,n.humanize=A0t(),n.destroy=l,Object.keys(t).forEach(u=>{n[u]=t[u]}),n.names=[],n.skips=[],n.formatters={};function e(u){let d=0;for(let f=0;f{if(k==="%%")return"%";A++;const W=n.formatters[B];if(typeof W=="function"){const S=b[A];k=W.call(v,S),b.splice(A,1),A--}return k}),n.formatArgs.call(v,b),(v.log||n.log).apply(v,b)}return y.namespace=u,y.useColors=n.useColors(),y.color=n.selectColor(u),y.extend=r,y.destroy=n.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(p!==n.namespaces&&(p=n.namespaces,m=n.enabled(u)),m),set:b=>{f=b}}),typeof n.init=="function"&&n.init(y),y}function r(u,d){const f=n(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function s(u){n.save(u),n.namespaces=u,n.names=[],n.skips=[];const d=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const f of d)f[0]==="-"?n.skips.push(f.slice(1)):n.names.push(f)}function i(u,d){let f=0,p=0,m=-1,y=0;for(;f"-"+d)].join(",");return n.enable(""),u}function a(u){for(const d of n.skips)if(i(u,d))return!1;for(const d of n.names)if(i(u,d))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}var T0t=I0t;(function(t,e){var n={};e.formatArgs=s,e.save=i,e.load=o,e.useColors=r,e.storage=a(),e.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function s(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const u="color: "+this.color;l.splice(1,0,u,"color: inherit");let d=0,f=0;l[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(d++,p==="%c"&&(f=d))}),l.splice(f,0,u)}e.log=console.debug||console.log||(()=>{});function i(l){try{l?e.storage.setItem("debug",l):e.storage.removeItem("debug")}catch{}}function o(){let l;try{l=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!l&&typeof process<"u"&&"env"in process&&(l=n.DEBUG),l}function a(){try{return localStorage}catch{}}t.exports=T0t(e);const{formatters:c}=t.exports;c.j=function(l){try{return JSON.stringify(l)}catch(u){return"[UnexpectedJSONParseError]: "+u.message}}})(KB,KB.exports);var N0t=KB.exports;const $D=Zi(N0t),Ute="waku";let rr=class s6{_info;_warn;_error;static createDebugNamespace(e,n){return n?`${Ute}:${n}:${e}`:`${Ute}:${e}`}constructor(e){this._info=$D(s6.createDebugNamespace("info",e)),this._warn=$D(s6.createDebugNamespace("warn",e)),this._error=$D(s6.createDebugNamespace("error",e))}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(e,...n){(this[e]||this.log)(...n)}};function Xk(t,e){const n=y1(t),r=y1(e.contentTopic),s=P0t(e.timestamp),i=dme([n,e.payload,r,e.meta,s].filter(eV));return Th(i)}function P0t(t){if(!t)return;let e;return typeof t=="bigint"?e=t:e=BigInt(t.valueOf())*1000000n,_0t(e)}function k0t(t,e){const n=Xk(t,e);return Yk(n)}const R0t=new rr("message:version-0"),yme=BigInt(1e6),e4=0;class O0t{pubsubTopic;proto;_hash;_hashStr;constructor(e,n){this.pubsubTopic=e,this.proto=n}get ephemeral(){return!!this.proto.ephemeral}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get hash(){return this._hash===void 0&&(this._hash=Xk(this.pubsubTopic,this.proto)),this._hash}get hashStr(){return this._hashStr===void 0&&(this._hashStr=Yk(this.hash)),this._hashStr}get timestamp(){try{if(this.proto.timestamp){const e=this.proto.timestamp/yme;return new Date(Number(e))}return}catch{return}}get meta(){return this.proto.meta}get version(){return this.proto.version??e4}get rateLimitProof(){return this.proto.rateLimitProof}}let $0t=class{contentTopic;ephemeral;routingInfo;metaSetter;constructor(e,n=!1,r,s){if(this.contentTopic=e,this.ephemeral=n,this.routingInfo=r,this.metaSetter=s,!e||e==="")throw new Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}async toWire(e){return NN.encode(await this.toProtoObj(e))}async toProtoObj(e){const n=e.timestamp??new Date,r={payload:e.payload,version:e4,contentTopic:this.contentTopic,timestamp:BigInt(n.valueOf())*yme,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const s=this.metaSetter(r);return{...r,meta:s}}return r}};function wme({contentTopic:t,routingInfo:e,ephemeral:n,metaSetter:r}){return new $0t(t,n,e,r)}let D0t=class{contentTopic;routingInfo;constructor(e,n){if(this.contentTopic=e,this.routingInfo=n,!e||e==="")throw new Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}fromWireToProtoObj(e){const n=NN.decode(e);return Promise.resolve({payload:n.payload,contentTopic:n.contentTopic,version:n.version??void 0,timestamp:n.timestamp??void 0,meta:n.meta??void 0,rateLimitProof:n.rateLimitProof??void 0,ephemeral:n.ephemeral??!1})}async fromProtoObj(e,n){return n.version??e4!==0?(R0t.error("Failed to decode due to incorrect version, expected:",e4,", actual:",n.version),Promise.resolve(void 0)):new O0t(e,n)}};function M0t(t,e){return new D0t(t,e)}var zn;(function(t){t.Relay="relay",t.Store="store",t.LightPush="lightpush",t.Filter="filter"})(zn||(zn={}));var Sn;(function(t){t.GENERIC_FAIL="Generic error",t.REMOTE_PEER_REJECTED="Remote peer rejected",t.DECODE_FAILED="Failed to decode",t.NO_PEER_AVAILABLE="No peer available",t.NO_STREAM_AVAILABLE="No stream available",t.NO_RESPONSE="No response received",t.ENCODE_FAILED="Failed to encode",t.EMPTY_PAYLOAD="Payload is empty",t.SIZE_TOO_BIG="Size is too big",t.TOPIC_NOT_CONFIGURED="Topic not configured",t.STREAM_ABORTED="Stream aborted",t.RLN_PROOF_GENERATION="Proof generation failed",t.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",t.INVALID_DECODER_TOPICS="Invalid decoder topics"})(Sn||(Sn={}));var cp;(function(t){t.Connection="waku:connection",t.Health="waku:health"})(cp||(cp={}));var xh;(function(t){t.BOOTSTRAP="bootstrap",t.PEER_EXCHANGE="peer-exchange",t.PEER_CACHE="peer-cache"})(xh||(xh={}));const GB="locked",L0t="@waku/bootstrap",bme=1,B0t=8,vme={clusterId:bme,numShardsInCluster:B0t};var Vs;(function(t){t.Unhealthy="Unhealthy",t.MinimallyHealthy="MinimallyHealthy",t.SufficientlyHealthy="SufficientlyHealthy"})(Vs||(Vs={}));function U0t(t){return t[Symbol.asyncIterator]!=null}function Gu(t){if(U0t(t))return(async()=>{const n=[];for await(const r of t)n.push(r);return n})();const e=[];for(const n of t)e.push(n);return e}function Uy(t,e){e==null&&(e=t.reduce((s,i)=>s+i.length,0));const n=qc(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}function As(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let n=0;for(const r of e)if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.push(r);else if(XA(r))n+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}prepend(...e){this.prependAll(e)}prependAll(e){let n=0;for(const r of e.reverse())if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.unshift(r);else if(XA(r))n+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}get(e){const n=Fte(this.bufs,e);return n.buf[n.index]}set(e,n){const r=Fte(this.bufs,e);r.buf[r.index]=n}write(e,n=0){if(e instanceof Uint8Array)for(let r=0;r0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,n){const{bufs:r,length:s}=this._subList(e,n);return Uy(r,s)}subarray(e,n){const{bufs:r,length:s}=this._subList(e,n);return r.length===1?r[0]:Uy(r,s)}sublist(e,n){const{bufs:r,length:s}=this._subList(e,n),i=new mn;return i.length=s,i.bufs=[...r],i}_subList(e,n){if(e=e??0,n=n??this.length,e<0&&(e=this.length+e),n<0&&(n=this.length+n),e<0||n>this.length)throw new RangeError("index is out of bounds");if(e===n)return{bufs:[],length:0};if(e===0&&n===this.length)return{bufs:this.bufs,length:this.length};const r=[];let s=0;for(let i=0;i=c)continue;const l=e>=a&&ea&&n<=c;if(l&&u){if(e===a&&n===c){r.push(o);break}const d=e-a;r.push(o.subarray(d,d+(n-e)));break}if(l){if(e===0){r.push(o);continue}r.push(o.subarray(e-a));continue}if(u){if(n===c){r.push(o);break}r.push(o.subarray(0,n-a));break}r.push(o)}return{bufs:r,length:n-e}}indexOf(e,n=0){if(!XA(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(n=Number(n??0),isNaN(n)&&(n=0),n<0&&(n=this.length+n),n<0&&(n=0),e.length===0)return n>this.length?this.length:n;const s=r.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");const i=256,o=new Int32Array(i);for(let d=0;d=0;f--){const p=this.get(d+f);if(r[f]!==p){u=Math.max(1,f-a[p]);break}}if(u===0)return d}return-1}getInt8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt8(0)}setInt8(e,n){const r=qc(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,n),this.write(r,e)}getInt16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,n)}setInt16(e,n,r){const s=Mt(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,n,r),this.write(s,e)}getInt32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,n)}setInt32(e,n,r){const s=Mt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,n,r),this.write(s,e)}getBigInt64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,n)}setBigInt64(e,n,r){const s=Mt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,n,r),this.write(s,e)}getUint8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint8(0)}setUint8(e,n){const r=qc(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,n),this.write(r,e)}getUint16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,n)}setUint16(e,n,r){const s=Mt(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,n,r),this.write(s,e)}getUint32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,n)}setUint32(e,n,r){const s=Mt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,n,r),this.write(s,e)}getBigUint64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,n)}setBigUint64(e,n,r){const s=Mt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,n,r),this.write(s,e)}getFloat32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,n)}setFloat32(e,n,r){const s=Mt(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,n,r),this.write(s,e)}getFloat64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,n)}setFloat64(e,n,r){const s=Mt(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,n,r),this.write(s,e)}equals(e){if(e==null||!(e instanceof mn)||e.bufs.length!==this.bufs.length)return!1;for(let n=0;ns+i.byteLength,0)),r.length=n,r}}function Eme(t){return t[Symbol.asyncIterator]!=null}const Qk=t=>{const e=Vi(t),n=qc(e);return rf(t,n),Qk.bytes=e,n};Qk.bytes=0;function Eh(t,e){e=e??{};const n=e.lengthEncoder??Qk;function*r(s){const i=n(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Eme(t)?async function*(){for await(const s of t)yield*r(s)}():function*(){for(const s of t)yield*r(s)}()}Eh.single=(t,e)=>{e=e??{};const n=e.lengthEncoder??Qk;return new mn(n(t.byteLength),t)};let F0t=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},j0t=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},z0t=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},jte=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};const W0t=8,V0t=1024*1024*4;var fm;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(fm||(fm={}));const rV=t=>{const e=N3(t);return rV.bytes=Vi(e),e};rV.bytes=0;function Hd(t,e){const n=new mn;let r=fm.LENGTH,s=-1;const i=e?.lengthDecoder??rV,o=e?.maxLengthLength??W0t,a=e?.maxDataLength??V0t;function*c(){for(;n.byteLength>0;){if(r===fm.LENGTH)try{if(s=i(n),s<0)throw new F0t("Invalid message length");if(s>a)throw new j0t("Message length too long");const l=i.bytes;n.consume(l),e?.onLength!=null&&e.onLength(s),r=fm.DATA}catch(l){if(l instanceof RangeError){if(n.byteLength>o)throw new z0t("Message length length too long");break}throw l}if(r===fm.DATA){if(n.byteLength0)throw new jte("Unexpected end of input")}():function*(){for(const l of t)n.append(l),yield*c();if(n.byteLength>0)throw new jte("Unexpected end of input")}()}Hd.fromReader=(t,e)=>{let n=1;const r=async function*(){for(;;)try{const{done:i,value:o}=await t.next(n);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{n=1}}();return Hd(r,{...e??{},onLength:i=>{n=i}})};function qs(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}class zte{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}}class DD{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new zte(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const n=this.head;this.head=n.next=new zte(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){const n=this.tail.next;this.tail.next=null,this.tail=n,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}let H0t=class extends Error{type;code;constructor(e,n){super(e??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}};function R3(t={}){return q0t(n=>{const r=n.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},t)}function q0t(t,e){e=e??{};let n=e.onEnd,r=new DD,s,i,o,a=qs();const c=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((b,v)=>{i=x=>{i=null,r.push(x);try{b(t(r))}catch(E){v(E)}return s}}):t(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=qs()})}},l=b=>i!=null?i(b):(r.push(b),s),u=b=>(r=new DD,i!=null?i({error:b}):(r.push({error:b}),s)),d=b=>{if(o)return s;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},f=b=>o?s:(o=!0,b!=null?u(b):l({done:!0})),p=()=>(r=new DD,f(),{done:!0}),m=b=>(f(b),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:p,throw:m,push:d,end:f,get readableLength(){return r.size},onEmpty:async b=>{const v=b?.signal;if(v?.throwIfAborted(),r.isEmpty())return;let x,E;v!=null&&(x=new Promise((A,_)=>{E=()=>{_(new H0t)},v.addEventListener("abort",E)}));try{await Promise.race([a.promise,x])}finally{E!=null&&v!=null&&v?.removeEventListener("abort",E)}}},n==null)return s;const y=s;return s={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(b){return y.throw(b),n!=null&&(n(b),n=void 0),{done:!0}},return(){return y.return(),n!=null&&(n(),n=void 0),{done:!0}},push:d,end(b){return y.end(b),n!=null&&(n(b),n=void 0),s},get readableLength(){return y.readableLength},onEmpty:b=>y.onEmpty(b)},s}let Wte=class extends Error{type;code;constructor(e,n,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=n??"ABORT_ERR"}};async function Jo(t,e,n){if(e==null)return t;if(e.aborted)return t.catch(()=>{}),Promise.reject(new Wte(n?.errorMessage,n?.errorCode,n?.errorName));let r;const s=new Wte(n?.errorMessage,n?.errorCode,n?.errorName);try{return await Promise.race([t,new Promise((i,o)=>{r=()=>{o(s)},e.addEventListener("abort",r)})])}finally{r!=null&&e.removeEventListener("abort",r)}}class K0t{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=qs(),this.haveNext=qs()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=qs(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){const e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,n){await this._push(e,n)}async end(e,n){e!=null?await this.throw(e):await this._push(void 0,n)}async _push(e,n){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=qs(),await Jo(this.readNext.promise,n?.signal,n)}}function Cme(){return new K0t}function G0t(t){return t[Symbol.asyncIterator]!=null}async function Z0t(t,e,n){try{await Promise.all(t.map(async r=>{for await(const s of r)await e.push(s,{signal:n}),n.throwIfAborted()})),await e.end(void 0,{signal:n})}catch(r){await e.end(r,{signal:n}).catch(()=>{})}}async function*Y0t(t){const e=new AbortController,n=Cme();Z0t(t,n,e.signal).catch(()=>{});try{yield*n}finally{e.abort()}}function*X0t(t){for(const e of t)yield*e}function t4(...t){const e=[];for(const n of t)G0t(n)||e.push(n);return e.length===t.length?X0t(e):Y0t(t)}function Tl(t,...e){if(t==null)throw new Error("Empty pipeline");if(MD(t)){const r=t;t=()=>r.source}else if(Sme(t)||_me(t)){const r=t;t=()=>r}const n=[t,...e];if(n.length>1&&MD(n[n.length-1])&&(n[n.length-1]=n[n.length-1].sink),n.length>2)for(let r=1;r{let e;for(;t.length>0;)e=t.shift()(e);return e},_me=t=>t?.[Symbol.asyncIterator]!=null,Sme=t=>t?.[Symbol.iterator]!=null,MD=t=>t==null?!1:t.sink!=null&&t.source!=null,J0t=t=>e=>{const n=t.sink(e);if(n?.then!=null){const r=R3({objectMode:!0});n.then(()=>{r.end()},o=>{r.end(o)});let s;const i=t.source;if(_me(i))s=async function*(){yield*i,r.end()};else if(Sme(i))s=function*(){yield*i,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return t4(r,s())}return t.source};function Vte(t){return t.filter(e=>e.status==="open").sort((e,n)=>n.timeline.open-e.timeline.open).at(0)}const Hte="consumed";class O3{multicodec;libp2p;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,n){this.multicodec=e,this.libp2p=n,this.log=new rr(`stream-manager:${e}`),this.libp2p.events.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){try{const n=e.toString(),r=this.streamPool.get(n);r&&(this.streamPool.delete(n),await r);const s=this.getOpenStreamForCodec(e)||await this.createStream(e);return s?(this.log.info(`Using stream for peerId=${n} multicodec=${this.multicodec}`),this.lockStream(n,s),s):void 0}catch(n){this.log.error("Failed to getStream:",n);return}}async createStream(e,n=0){const r=this.libp2p.connectionManager.getConnections(e),s=Vte(r);if(!s){this.log.error(`Failed to get a connection to the peer peerId=${e.toString()} multicodec=${this.multicodec}`);return}let i,o;for(let a=0;a{const{peer:n}=e.detail;!n.protocols.includes(this.multicodec)||this.getOpenStreamForCodec(n.id)||this.scheduleNewStream(n)};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const n=this.libp2p.connectionManager.getConnections(e),r=Vte(n);if(!r){this.log.info(`No open connection found for peerId=${e.toString()} multicodec=${this.multicodec}`);return}const s=r.streams.find(o=>o.protocol===this.multicodec);if(!s){this.log.info(`No open stream found for peerId=${e.toString()} multicodec=${this.multicodec}`);return}if(["done","closed","closing"].includes(s.writeStatus||"")||this.isStreamLocked(s)){this.log.info(`Stream for peerId=${e.toString()} multicodec=${this.multicodec} is unusable`);return}return this.log.info(`Found open stream for peerId=${e.toString()} multicodec=${this.multicodec}`),s}lockStream(e,n){this.log.info(`Locking stream for peerId:${e} streamId:${n.id}`),n.metadata[Hte]=!0}isStreamLocked(e){return!!e.metadata[Hte]}}let QA;const emt=new Uint8Array(16);function tmt(){if(!QA&&(QA=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!QA))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return QA(emt)}const Oi=[];for(let t=0;t<256;++t)Oi.push((t+256).toString(16).slice(1));function nmt(t,e=0){return Oi[t[e+0]]+Oi[t[e+1]]+Oi[t[e+2]]+Oi[t[e+3]]+"-"+Oi[t[e+4]]+Oi[t[e+5]]+"-"+Oi[t[e+6]]+Oi[t[e+7]]+"-"+Oi[t[e+8]]+Oi[t[e+9]]+"-"+Oi[t[e+10]]+Oi[t[e+11]]+Oi[t[e+12]]+Oi[t[e+13]]+Oi[t[e+14]]+Oi[t[e+15]]}const rmt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),qte={randomUUID:rmt};function Kb(t,e,n){if(qte.randomUUID&&!e&&!t)return qte.randomUUID();t=t||{};const r=t.random||(t.rng||tmt)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,nmt(r)}class sV{proto;constructor(e){this.proto=e}static decode(e){const n=DN.decode(e);return new sV(n)}encode(){return DN.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class Vd{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,n){return new Vd({requestId:Kb(),filterSubscribeType:gg.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:n})}static createUnsubscribeRequest(e,n){return new Vd({requestId:Kb(),filterSubscribeType:gg.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:n})}static createUnsubscribeAllRequest(e){return new Vd({requestId:Kb(),filterSubscribeType:gg.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new Vd({requestId:Kb(),filterSubscribeType:gg.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const n=gg.decode(e);return new Vd(n)}encode(){return gg.encode(this.proto)}get filterSubscribeType(){return this.proto.filterSubscribeType}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.proto.pubsubTopic}get contentTopics(){return this.proto.contentTopics}}class BE{proto;constructor(e){this.proto=e}static decode(e){const n=$N.decode(e);return new BE(n)}encode(){return $N.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const mo=new rr("filter-core"),$g={SUBSCRIBE:"/vac/waku/filter-subscribe/2.0.0-beta1",PUSH:"/vac/waku/filter-push/2.0.0-beta1"};class smt{handleIncomingMessage;streamManager;multicodec=$g.SUBSCRIBE;constructor(e,n){this.handleIncomingMessage=e,this.streamManager=new O3($g.SUBSCRIBE,n.components),n.handle($g.PUSH,this.onRequest.bind(this),{maxInboundStreams:100}).catch(r=>{mo.error("Failed to register ",$g.PUSH,r)})}async subscribe(e,n,r){const s=await this.streamManager.getStream(n);if(!s)return{success:null,failure:{error:Sn.NO_STREAM_AVAILABLE,peerId:n}};const i=Vd.createSubscribeRequest(e,r);let o;try{if(o=await Tl([i.encode()],Eh,s,Hd,async u=>await Gu(u)),!o?.length)throw Error("Received no response from subscription request.")}catch(u){return mo.error("Failed to send subscribe request",u),{success:null,failure:{error:Sn.GENERIC_FAIL,peerId:n}}}const{statusCode:a,requestId:c,statusDesc:l}=BE.decode(o[0].slice());return a<200||a>=300?(mo.error(`Filter subscribe request ${c} failed with status code ${a}: ${l}`),{failure:{error:Sn.REMOTE_PEER_REJECTED,peerId:n},success:null}):{failure:null,success:n}}async unsubscribe(e,n,r){const s=await this.streamManager.getStream(n);if(!s)return mo.error(`Failed to get a stream for remote peer:${n.toString()}`),{success:null,failure:{error:Sn.NO_STREAM_AVAILABLE,peerId:n}};const i=Vd.createUnsubscribeRequest(e,r);try{await Tl([i.encode()],Eh,s.sink)}catch(o){return mo.error("Failed to send unsubscribe request",o),{success:null,failure:{error:Sn.GENERIC_FAIL,peerId:n}}}return{success:n,failure:null}}async unsubscribeAll(e,n){const r=await this.streamManager.getStream(n);if(!r)return mo.error(`Failed to get a stream for remote peer:${n.toString()}`),{success:null,failure:{error:Sn.NO_STREAM_AVAILABLE,peerId:n}};const s=Vd.createUnsubscribeAllRequest(e),i=await Tl([s.encode()],Eh,r,Hd,async l=>await Gu(l));if(!i||!i.length)return{failure:{error:Sn.NO_RESPONSE,peerId:n},success:null};const{statusCode:o,requestId:a,statusDesc:c}=BE.decode(i[0].slice());return o<200||o>=300?(mo.error(`Filter unsubscribe all request ${a} failed with status code ${o}: ${c}`),{failure:{error:Sn.REMOTE_PEER_REJECTED,peerId:n},success:null}):{failure:null,success:n}}async ping(e){const n=await this.streamManager.getStream(e);if(!n)return mo.error(`Failed to get a stream for remote peer:${e.toString()}`),{success:null,failure:{error:Sn.NO_STREAM_AVAILABLE,peerId:e}};const r=Vd.createSubscriberPingRequest();let s;try{s=await Tl([r.encode()],Eh,n,Hd,async c=>await Gu(c))}catch(c){return mo.error("Failed to send ping request",c),{success:null,failure:{error:Sn.GENERIC_FAIL,peerId:e}}}if(!s||!s.length)return{success:null,failure:{error:Sn.NO_RESPONSE,peerId:e}};const{statusCode:i,requestId:o,statusDesc:a}=BE.decode(s[0].slice());return i<200||i>=300?(mo.error(`Filter ping request ${o} failed with status code ${i}: ${a}`),{success:null,failure:{error:Sn.REMOTE_PEER_REJECTED,peerId:e}}):{success:e,failure:null}}onRequest(e){const{connection:n,stream:r}=e,{remotePeer:s}=n;mo.info(`Received message from ${s.toString()}`);try{Tl(r,Hd,async i=>{for await(const o of i){const a=sV.decode(o.slice()),{pubsubTopic:c,wakuMessage:l}=a;if(!l){mo.error("Received empty message");return}if(!c){mo.error("Pubsub topic missing from push message");return}await this.handleIncomingMessage(c,l,n.remotePeer.toString())}}).then(()=>{mo.info("Receiving pipe closed.")},async i=>{mo.error(`Error with receiving pipe on peer:${n.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,i)})}catch(i){mo.error("Error decoding message",i)}}}class W_{proto;constructor(e){this.proto=e}static createRequest(e,n){return new W_({requestId:Kb(),request:{message:e,pubsubTopic:n},response:void 0})}static decode(e){const n=FN.decode(e);return new W_(n)}encode(){return FN.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const imt="could not generate rln proof",omt="could not get new message id to generate an rln proof",amt="RLN validation failed",cmt=t=>t?t.includes(imt)||t.includes(omt)||t.includes(amt):!1,Rd=new rr("light-push"),w1="/vac/waku/lightpush/2.0.0-beta1";class lmt{streamManager;multicodec=w1;constructor(e){this.streamManager=new O3(w1,e.components)}async preparePushMessage(e,n){try{if(!n.payload||n.payload.length===0)return Rd.error("Failed to send waku light push: payload is empty"),{query:null,error:Sn.EMPTY_PAYLOAD};if(!await x0t(e,n))return Rd.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:Sn.SIZE_TOO_BIG};const r=await e.toProtoObj(n);return r?{query:W_.createRequest(r,e.pubsubTopic),error:null}:(Rd.error("Failed to encode to protoMessage, aborting push"),{query:null,error:Sn.ENCODE_FAILED})}catch(r){return Rd.error("Failed to prepare push message",r),{query:null,error:Sn.GENERIC_FAIL}}}async send(e,n,r){const{query:s,error:i}=await this.preparePushMessage(e,n);if(i||!s)return{success:null,failure:{error:i,peerId:r}};const o=await this.streamManager.getStream(r);if(!o)return Rd.error(`Failed to get a stream for remote peer:${r.toString()}`),{success:null,failure:{error:Sn.NO_STREAM_AVAILABLE,peerId:r}};let a;try{a=await Tl([s.encode()],Eh,o,Hd,async u=>await Gu(u))}catch(u){return Rd.error("Failed to send waku light push request",u),{success:null,failure:{error:Sn.STREAM_ABORTED,peerId:r}}}const c=new mn;a.forEach(u=>{c.append(u)});let l;try{l=W_.decode(c).response}catch(u){return Rd.error("Failed to decode push reply",u),{success:null,failure:{error:Sn.DECODE_FAILED,peerId:r}}}return l?cmt(l.info)?(Rd.error("Remote peer fault: RLN generation"),{success:null,failure:{error:Sn.RLN_PROOF_GENERATION,peerId:r}}):l.isSuccess?{success:r,failure:null}:(Rd.error("Remote peer rejected the message: ",l.info),{success:null,failure:{error:Sn.REMOTE_PEER_REJECTED,peerId:r}}):(Rd.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:Sn.NO_RESPONSE,peerId:r}})}}const umt={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0};function dmt(t){return{...umt,...t}}const fmt=20,hmt=100,Kte=24*60*60*1e3,Gte=1e6;class n4{proto;constructor(e){this.proto=e}static create(e){const n=new n4({...e,contentTopics:e.contentTopics||[],requestId:Kb(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*Gte):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*Gte):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0}),r=e.messageHashes&&e.messageHashes.length>0,s=e.contentTopics&&e.contentTopics.length>0,i=e.timeStart||e.timeEnd;if(r){if(s||i)throw new Error("Message hash lookup queries cannot include content filter criteria (contentTopics, timeStart, or timeEnd)")}else if(e.pubsubTopic&&(!e.contentTopics||e.contentTopics.length===0)||!e.pubsubTopic&&e.contentTopics&&e.contentTopics.length>0)throw new Error("Both pubsubTopic and contentTopics must be set together for content-filtered queries");return n}static decode(e){const n=WN.decode(e);return new n4(n)}encode(){return WN.encode(this.proto)}}class iV{proto;constructor(e){this.proto=e}static decode(e){const n=VN.decode(e);return new iV(n)}encode(){return VN.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const C2=new rr("store"),V_="/vac/waku/store-query/3.0.0";class pmt{streamManager;multicodec=V_;constructor(e){this.streamManager=new O3(V_,e.components)}get maxTimeLimit(){return Kte}async*queryPerPage(e,n,r){if(e.timeStart&&e.timeEnd&&e.timeEnd.getTime()-e.timeStart.getTime()>Kte)throw new Error("Time range bigger than 24h");if(!(e.messageHashes&&e.messageHashes.length>0)&&e.contentTopics&&e.contentTopics.toString()!==Array.from(n.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let i=e.paginationCursor;for(;;){const o=n4.create({...e,paginationCursor:i});C2.info("Sending store query request:",{hasMessageHashes:!!e.messageHashes?.length,messageHashCount:e.messageHashes?.length,pubsubTopic:e.pubsubTopic,contentTopics:e.contentTopics});const a=await this.streamManager.getStream(r);if(!a){C2.error(`Failed to get a stream for remote peer:${r.toString()}`);break}const c=await Tl([o.encode()],Eh,a,Hd,async f=>await Gu(f)),l=new mn;c.forEach(f=>{l.append(f)});const u=iV.decode(l);if(!u.statusCode||u.statusCode>=300){const f=`Store query failed with status code: ${u.statusCode}, description: ${u.statusDesc}`;throw C2.error(f),new Error(f)}if(!u.messages||!u.messages.length){C2.warn("Stopping pagination due to empty messages in response");break}if(C2.info(`${u.messages.length} messages retrieved from store`),yield u.messages.map(f=>{if(!f.message)return Promise.resolve(void 0);const p=f.message.contentTopic;if(p){const m=n.get(p);if(m)return m.fromProtoObj(f.pubsubTopic||"",dmt(f.message))}return Promise.resolve(void 0)}),e.paginationForward?i=u.messages[u.messages.length-1].messageHash:i=u.messages[0].messageHash,u.messages.length>hmt&&u.messages.length<(e.paginationLimit||fmt))break}}}const Fs=new rr("connection-limiter"),gmt=5*1e3;class mmt{libp2p;events;networkMonitor;dialer;connectionMonitorInterval=null;options;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.networkMonitor=e.networkMonitor,this.dialer=e.dialer,this.options=e.options,this.onWakuConnectionEvent=this.onWakuConnectionEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this)}start(){this.dialPeersFromStore(),this.options.enableAutoRecovery&&this.connectionMonitorInterval===null&&(this.connectionMonitorInterval=setInterval(()=>void this.maintainConnections(),gmt)),this.events.addEventListener(cp.Connection,this.onWakuConnectionEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent)}stop(){this.events.removeEventListener(cp.Connection,this.onWakuConnectionEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent),this.connectionMonitorInterval&&(clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=null)}onWakuConnectionEvent(){if(!this.options.enableAutoRecovery){Fs.info("Auto recovery is disabled, skipping");return}this.networkMonitor.isBrowserConnected()&&this.dialPeersFromStore()}async maintainConnections(){await this.maintainConnectionsCount(),await this.maintainBootstrapConnections()}async onDisconnectedEvent(){this.libp2p.getConnections().length===0&&(Fs.info("No connections, dialing peers from store"),await this.dialPeersFromStore())}async maintainConnectionsCount(){Fs.info("Maintaining connections count");const e=this.libp2p.getConnections();if(e.length<=this.options.maxConnections){Fs.info(`Node has less than max connections ${this.options.maxConnections}, trying to dial more peers`);const n=await this.getPrioritizedPeers();if(n.length===0){Fs.info("No peers to dial, node is utilizing all known peers");return}const r=n.slice(0,this.options.maxConnections-e.length).map(s=>this.dialer.dial(s.id));await Promise.all(r);return}Fs.info(`Node has more than max connections ${this.options.maxConnections}, dropping connections`);try{const n=e.filter(s=>!s.tags.includes(GB)).slice(this.options.maxConnections);if(n.length===0){Fs.info("No connections to drop, skipping");return}const r=n.map(s=>this.libp2p.hangUp(s.remotePeer));await Promise.all(r),Fs.info(`Dropped ${n.length} connections`)}catch(n){Fs.error("Unexpected error while maintaining connections",n)}}async maintainBootstrapConnections(){Fs.info("Maintaining bootstrap connections");const e=await this.getBootstrapPeers();if(!(e.length<=this.options.maxBootstrapPeers))try{const n=e.slice(this.options.maxBootstrapPeers);Fs.info(`Dropping ${n.length} bootstrap connections because node has more than max bootstrap connections ${this.options.maxBootstrapPeers}`);const r=n.map(s=>this.libp2p.hangUp(s.id));await Promise.all(r),Fs.info(`Dropped ${n.length} bootstrap connections`)}catch(n){Fs.error("Unexpected error while maintaining bootstrap connections",n)}}async dialPeersFromStore(){Fs.info("Dialing peers from store");try{const e=await this.getPrioritizedPeers();if(e.length===0){Fs.info("No peers to dial, skipping");return}const n=e.map(r=>this.dialer.dial(r.id));Fs.info(`Dialing ${e.length} peers from store`),await Promise.all(n),Fs.info(`Dialed ${n.length} peers from store`)}catch(e){Fs.error("Unexpected error while dialing peer store peers",e)}}async getPrioritizedPeers(){const e=await this.libp2p.peerStore.all(),n=this.libp2p.getConnections();Fs.info(`Found ${e.length} peers in store, and found ${n.length} connections`);const r=e.filter(a=>!n.some(c=>c.remotePeer.equals(a.id))&&a.addresses.some(c=>c.multiaddr.toString().includes("wss")||c.multiaddr.toString().includes("ws"))),s=r.filter(a=>a.tags.has(xh.BOOTSTRAP)),i=r.filter(a=>a.tags.has(xh.PEER_EXCHANGE)),o=r.filter(a=>a.tags.has(xh.PEER_CACHE));return[...s,...i,...o]}async getBootstrapPeers(){return(await Promise.all(this.libp2p.getConnections().map(n=>n.remotePeer).map(n=>this.getPeer(n)))).filter(n=>n&&n.tags.has(xh.BOOTSTRAP))}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(n){return Fs.error(`Failed to get peer ${e}, error: ${n}`),null}}}const yo=new rr("dialer");class ymt{libp2p;shardReader;options;dialingQueue=[];dialHistory=new Map;failedDials=new Map;dialingInterval=null;isProcessing=!1;isImmediateDialing=!1;constructor(e){this.libp2p=e.libp2p,this.shardReader=e.shardReader,this.options=e.options}start(){yo.info("Starting dialer"),this.dialingInterval||(this.dialingInterval=setInterval(()=>{this.processQueue()},500)),this.dialHistory.clear(),this.failedDials.clear()}stop(){yo.info("Stopping dialer"),this.dialingInterval&&(clearInterval(this.dialingInterval),this.dialingInterval=null),this.dialHistory.clear(),this.failedDials.clear()}async dial(e){if(await this.shouldSkipPeer(e)){yo.info(`Skipping peer: ${e}`);return}const r=this.dialingQueue.length===0,s=!this.isProcessing&&!this.isImmediateDialing;r&&s?(this.isImmediateDialing=!0,yo.info("Dialed peer immediately"),await this.dialPeer(e),this.isImmediateDialing=!1,yo.info("Released immediate dial lock")):(this.dialingQueue.push(e),yo.info(`Added peer to dialing queue, queue size: ${this.dialingQueue.length}`))}async processQueue(){if(!(this.dialingQueue.length===0||this.isProcessing)){this.isProcessing=!0;try{const e=this.dialingQueue.slice(0,this.options.maxDialingPeers);this.dialingQueue=this.dialingQueue.slice(e.length),yo.info(`Processing dial queue: dialing ${e.length} peers, ${this.dialingQueue.length} remaining in queue`),await Promise.all(e.map(n=>this.dialPeer(n)))}finally{this.isProcessing=!1}}}async dialPeer(e){try{yo.info(`Dialing peer from queue: ${e}`),await this.libp2p.dial(e),this.dialHistory.set(e.toString(),Date.now()),this.failedDials.delete(e.toString()),yo.info(`Successfully dialed peer from queue: ${e}`)}catch(n){yo.error(`Error dialing peer ${e}`,n),this.failedDials.set(e.toString(),Date.now())}}async shouldSkipPeer(e){if(this.libp2p.getPeers().some(r=>r.equals(e)))return yo.info(`Skipping peer ${e} - already connected`),!0;if(this.isRecentlyDialed(e))return yo.info(`Skipping peer ${e} - already dialed in the last 10 seconds`),!0;if(this.isRecentlyFailed(e))return yo.info(`Skipping peer ${e} - recently failed to dial`),!0;try{return await this.shardReader.hasShardInfo(e)?await this.shardReader.isPeerOnCluster(e)?!1:(yo.info(`Skipping peer ${e} - not on same cluster`),!0):(yo.info(`Skipping peer ${e} - no shard info`),!1)}catch(r){return yo.error(`Error checking shard info for peer ${e}`,r),!0}}isRecentlyDialed(e){const n=this.dialHistory.get(e.toString());return!!(n&&Date.now()-nr.addresses.some(o=>o.multiaddr.equals(i)))){ng.info(`Peer ${e} has same addresses in peer store, skipping`);return}ng.info(`Merging peer ${e} addresses in peer store`),await this.libp2p.peerStore.merge(e,{multiaddrs:n})}catch(r){ng.error(`Error updating peer store for ${e}`,r)}}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(n){ng.error(`Error getting peer info for ${e}`,n);return}}}const Zte="/relay-ping/1/ping/null",vc=new rr("keep-alive");class bmt{relay;networkConfig;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:e,relay:n,networkConfig:r,libp2p:s}){this.options=e,this.relay=n,this.networkConfig=r,this.libp2p=s,this.onPeerConnect=this.onPeerConnect.bind(this),this.onPeerDisconnect=this.onPeerDisconnect.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onPeerConnect),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnect)}stop(){this.libp2p.removeEventListener("peer:connect",this.onPeerConnect),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnect);for(const e of this.pingKeepAliveTimers.values())clearInterval(e);for(const e of this.relayKeepAliveTimers.values())for(const n of e)clearInterval(n);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}onPeerConnect(e){const n=e.detail;this.startPingForPeer(n)}onPeerDisconnect(e){const n=e.detail;this.stopPingForPeer(n)}startPingForPeer(e){this.stopPingForPeer(e),this.startLibp2pPing(e),this.startRelayPing(e)}stopPingForPeer(e){this.stopLibp2pPing(e),this.stopRelayPing(e)}startLibp2pPing(e){if(this.options.pingKeepAlive===0){vc.warn(`Ping keep alive is disabled pingKeepAlive:${this.options.pingKeepAlive}, skipping start for libp2p ping`);return}const n=e.toString();if(this.pingKeepAliveTimers.has(n)){vc.warn(`Ping already started for peer: ${n}, skipping start for libp2p ping`);return}const r=setInterval(()=>{this.pingLibp2p(e)},this.options.pingKeepAlive*1e3);this.pingKeepAliveTimers.set(n,r)}stopLibp2pPing(e){const n=e.toString();if(!this.pingKeepAliveTimers.has(n)){vc.warn(`Ping not started for peer: ${n}, skipping stop for ping`);return}clearInterval(this.pingKeepAliveTimers.get(n)),this.pingKeepAliveTimers.delete(n)}startRelayPing(e){if(!this.relay)return;if(this.options.relayKeepAlive===0){vc.warn(`Relay keep alive is disabled relayKeepAlive:${this.options.relayKeepAlive}, skipping start for relay ping`);return}if(this.relayKeepAliveTimers.has(e.toString())){vc.warn(`Relay ping already started for peer: ${e.toString()}, skipping start for relay ping`);return}const n=[];for(const r of this.relay.pubsubTopics){if(!this.relay.getMeshPeers(r).includes(e.toString())){vc.warn(`Peer: ${e.toString()} is not in the mesh for topic: ${r}, skipping start for relay ping`);continue}const i=mme(this.networkConfig,{contentTopic:Zte,pubsubTopic:r}),o=wme({routingInfo:i,contentTopic:Zte,ephemeral:!0}),a=setInterval(()=>{this.pingRelay(o)},this.options.relayKeepAlive*1e3);n.push(a)}this.relayKeepAliveTimers.set(e.toString(),n)}stopRelayPing(e){if(!this.relay)return;const n=e.toString();if(!this.relayKeepAliveTimers.has(n)){vc.warn(`Relay ping not started for peer: ${n}, skipping stop for relay ping`);return}this.relayKeepAliveTimers.get(n)?.map(clearInterval),this.relayKeepAliveTimers.delete(n)}async pingRelay(e){try{vc.info("Sending Waku Relay ping message"),await this.relay.send(e,{payload:new Uint8Array([1])})}catch(n){vc.error("Failed to send relay ping",n)}}async pingLibp2p(e){try{vc.info(`Pinging libp2p peer (${e.toString()})`);const n=await this.libp2p.services.ping.ping(e);vc.info(`Ping succeeded (${e.toString()})`,n),await this.libp2p.peerStore.merge(e,{metadata:{ping:y1(n.toString())}}),vc.info(`Ping updated for peer (${e.toString()})`)}catch(n){vc.error(`Ping failed for peer (${e.toString()})`,n)}}}class vmt{libp2p;events;isNetworkConnected=!1;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onConnectedEvent=this.onConnectedEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this),this.dispatchNetworkEvent=this.dispatchNetworkEvent.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onConnectedEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.addEventListener("online",this.dispatchNetworkEvent),globalThis.addEventListener("offline",this.dispatchNetworkEvent)}catch{}}stop(){this.libp2p.removeEventListener("peer:connect",this.onConnectedEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.removeEventListener("online",this.dispatchNetworkEvent),globalThis.removeEventListener("offline",this.dispatchNetworkEvent)}catch{}}isConnected(){return this.isBrowserConnected()?this.isP2PConnected():!1}isP2PConnected(){return this.isNetworkConnected}isBrowserConnected(){try{if(globalThis?.navigator&&!globalThis?.navigator?.onLine)return!1}catch{}return!0}onConnectedEvent(){this.isNetworkConnected||(this.isNetworkConnected=!0,this.dispatchNetworkEvent())}onDisconnectedEvent(){this.isNetworkConnected&&this.libp2p.getConnections().length===0&&(this.isNetworkConnected=!1,this.dispatchNetworkEvent())}dispatchNetworkEvent(){this.events.dispatchEvent(new CustomEvent(cp.Connection,{detail:this.isConnected()}))}}const LD=new rr("shard-reader");class xmt{libp2p;clusterId;constructor(e){this.libp2p=e.libp2p,this.clusterId=e.networkConfig.clusterId}async isPeerOnCluster(e){const n=await this.getRelayShards(e);return n?n.clusterId===this.clusterId:!1}async hasShardInfo(e){return!!await this.getRelayShards(e)}async isPeerOnTopic(e,n){try{const{clusterId:r,shard:s}=hme(n);return r!==this.clusterId?!1:await this.isPeerOnShard(e,s)}catch(r){return LD.error(`Error comparing pubsub topic ${n} with shard info for ${e}`,r),!1}}async isPeerOnShard(e,n){const r=await this.getRelayShards(e);return LD.info(`Checking if peer on same shard: this { clusterId: ${this.clusterId}, shardId: ${n} },${e} { clusterId: ${r?.clusterId}, shards: ${r?.shards} }`),r?r.clusterId===this.clusterId&&r.shards.includes(n):!1}async getRelayShards(e){try{const r=(await this.libp2p.peerStore.get(e)).metadata.get("shardInfo");return r?qB(r):void 0}catch(n){LD.error(`Error getting shard info for ${e}`,n);return}}}const Emt=Symbol.for("@libp2p/connection"),Yte=Symbol.for("@libp2p/content-routing"),H_=Symbol.for("@libp2p/peer-discovery"),Jk=Symbol.for("@libp2p/peer-id");function Zm(t){return!!t?.[Jk]}const Xte=Symbol.for("@libp2p/peer-routing"),Ame="keep-alive",Cmt=Symbol.for("@libp2p/transport");var q_;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(q_||(q_={}));let b1=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};class _mt extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let Smt=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},cr=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class oV extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Amt extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}}class Ime extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class Imt extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class Tmt extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class Nmt extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Pmt extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}let ZB=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};class Tme extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}let aV=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}};class kmt extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class Rmt extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class cV extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class qd extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}class Omt extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}}let Nme=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}};class r4 extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}class BD extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}class Pme extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class $mt extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class kme extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class e8 extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}class Oo extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const n=this.#e.get(e);return n==null?0:n.length}addEventListener(e,n,r){super.addEventListener(e,n,r);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:n,once:(r!==!0&&r!==!1&&r?.once)??!1})}removeEventListener(e,n,r){super.removeEventListener(e.toString(),n??null,r);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:i})=>i!==n),this.#e.set(e,s))}dispatchEvent(e){const n=super.dispatchEvent(e);let r=this.#e.get(e.type);return r==null||(r=r.filter(({once:s})=>!s),this.#e.set(e.type,r)),n}safeDispatchEvent(e,n={}){return this.dispatchEvent(new CustomEvent(e,n))}}function lV(t){return t!=null&&typeof t.start=="function"&&typeof t.stop=="function"}async function Dmt(...t){const e=[];for(const n of t)lV(n)&&e.push(n);await Promise.all(e.map(async n=>{n.beforeStart!=null&&await n.beforeStart()})),await Promise.all(e.map(async n=>{await n.start()})),await Promise.all(e.map(async n=>{n.afterStart!=null&&await n.afterStart()}))}async function Mmt(...t){const e=[];for(const n of t)lV(n)&&e.push(n);await Promise.all(e.map(async n=>{n.beforeStop!=null&&await n.beforeStop()})),await Promise.all(e.map(async n=>{await n.stop()})),await Promise.all(e.map(async n=>{n.afterStop!=null&&await n.afterStop()}))}const lp=Symbol.for("@libp2p/service-capabilities"),Qte=Symbol.for("@libp2p/service-dependencies"),Lmt=parseInt("11111",2),YB=parseInt("10000000",2),Bmt=parseInt("01111111",2),Jte={0:_2,1:_2,2:Umt,3:zmt,4:Wmt,5:jmt,6:Fmt,16:_2,22:_2,48:_2};function t8(t,e={offset:0}){const n=t[e.offset]&Lmt;if(e.offset++,Jte[n]!=null)return Jte[n](t,e);throw new Error("No decoder for tag "+n)}function $3(t,e){let n=0;if((t[e.offset]&YB)===YB){const r=t[e.offset]&Bmt;let s="0x";e.offset++;for(let i=0;i=t.byteLength);){const r=t8(t,e);if(r===null)break;n.push(r)}return n}function Umt(t,e){const n=$3(t,e),r=e.offset,s=e.offset+n,i=[];for(let o=r;otypeof t=="bigint"&&dV<=t;function tyt(t,e,n){return WD(t)&&WD(e)&&WD(n)&&e<=t&&tdV;t>>=QB,e+=1);return e}const hV=t=>(QB<new Uint8Array(p),s=p=>Uint8Array.of(p);let i=r(t),o=r(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...p)=>n(o,i,...p),u=(p=r(0))=>{o=l(s(0),p),i=l(),p.length!==0&&(o=l(s(1),p),i=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const m=[];for(;p{c(),u(p);let y;for(;!(y=m(d()));)u();return c(),y}}function n8(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(s,i,o){const a=t[s];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([s,i])=>r(s,i,!1)),Object.entries(n).forEach(([s,i])=>r(s,i,!0))}function ene(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const i=t(n,...r);return e.set(n,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wa=BigInt(0),Hi=BigInt(1),Nm=BigInt(2),ryt=BigInt(3),Mme=BigInt(4),Lme=BigInt(5),Bme=BigInt(8);function Rs(t,e){const n=t%e;return n>=Wa?n:e+n}function _u(t,e,n){let r=t;for(;e-- >Wa;)r*=r,r%=n;return r}function tne(t,e){if(t===Wa)throw new Error("invert: expected non-zero number");if(e<=Wa)throw new Error("invert: expected positive modulus, got "+e);let n=Rs(t,e),r=e,s=Wa,i=Hi;for(;n!==Wa;){const a=r/n,c=r%n,l=s-i*a;r=n,n=c,s=i,i=l}if(r!==Hi)throw new Error("invert: does not exist");return Rs(s,e)}function Ume(t,e){const n=(t.ORDER+Hi)/Mme,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function syt(t,e){const n=(t.ORDER-Lme)/Bme,r=t.mul(e,Nm),s=t.pow(r,n),i=t.mul(e,s),o=t.mul(t.mul(i,Nm),s),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function iyt(t){if(t1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ume;let i=s.pow(r,e);const o=(e+Hi)/Nm;return function(c,l){if(c.is0(l))return l;if(nne(c,l)!==1)throw new Error("Cannot find square root");let u=n,d=c.mul(c.ONE,i),f=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let m=1,y=c.sqr(f);for(;!c.eql(y,c.ONE);)if(m++,y=c.sqr(y),m===u)throw new Error("Cannot find square root");const b=Hi<(Rs(t,e)&Hi)===Hi,cyt=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function lyt(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=cyt.reduce((r,s)=>(r[s]="function",r),e);return n8(t,n),t}function uyt(t,e,n){if(nWa;)n&Hi&&(r=t.mul(r,s)),s=t.sqr(s),n>>=Hi;return r}function Fme(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),i),r}function nne(t,e){const n=(t.ORDER-Hi)/Nm,r=t.pow(e,n),s=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function dyt(t,e){e!==void 0&&u0(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function r8(t,e,n=!1,r={}){if(t<=Wa)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,i;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const u=e;u.BITS&&(s=u.BITS),u.sqrt&&(i=u.sqrt),typeof u.isLE=="boolean"&&(n=u.isLE)}else typeof e=="number"&&(s=e),r.sqrt&&(i=r.sqrt);const{nBitLength:o,nByteLength:a}=dyt(t,s);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const l=Object.freeze({ORDER:t,isLE:n,BITS:o,BYTES:a,MASK:hV(o),ZERO:Wa,ONE:Hi,create:u=>Rs(u,t),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return Wa<=u&&uu===Wa,isValidNot0:u=>!l.is0(u)&&l.isValid(u),isOdd:u=>(u&Hi)===Hi,neg:u=>Rs(-u,t),eql:(u,d)=>u===d,sqr:u=>Rs(u*u,t),add:(u,d)=>Rs(u+d,t),sub:(u,d)=>Rs(u-d,t),mul:(u,d)=>Rs(u*d,t),pow:(u,d)=>uyt(l,u,d),div:(u,d)=>Rs(u*tne(d,t),t),sqrN:u=>u*u,addN:(u,d)=>u+d,subN:(u,d)=>u-d,mulN:(u,d)=>u*d,inv:u=>tne(u,t),sqrt:i||(u=>(c||(c=oyt(t)),c(l,u))),toBytes:u=>n?D3(u,a):fV(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return n?Fy(u):Dme(u)},invertBatch:u=>Fme(l,u),cmov:(u,d,f)=>f?d:u});return Object.freeze(l)}function jme(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function fyt(t){const e=jme(t);return e+Math.ceil(e/2)}function CDt(t,e,n=!1){const r=t.length,s=jme(e),i=fyt(e);if(r<16||r1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const o=n?Fy(t):Dme(t),a=Rs(o,e-Hi)+Hi;return n?D3(a,s):fV(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const v1=BigInt(0),Pm=BigInt(1);function VD(t,e){const n=e.negate();return t?n:e}function hyt(t,e,n){const r=e==="pz"?o=>o.pz:o=>o.ez,s=Fme(t.Fp,n.map(r));return n.map((o,a)=>o.toAffine(s[a])).map(t.fromAffine)}function zme(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function HD(t,e){zme(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,i=hV(t),o=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function rne(t,e,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=n;let a=Number(t&s),c=t>>o;a>r&&(a-=i,c+=Pm);const l=e*r,u=l+Math.abs(a)-1,d=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function pyt(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function gyt(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const qD=new WeakMap,Wme=new WeakMap;function KD(t){return Wme.get(t)||1}function sne(t){if(t!==v1)throw new Error("invalid wNAF")}function myt(t,e){return{constTimeNegate:VD,hasPrecomputes(n){return KD(n)!==1},unsafeLadder(n,r,s=t.ZERO){let i=n;for(;r>v1;)r&Pm&&(s=s.add(i)),i=i.double(),r>>=Pm;return s},precomputeWindow(n,r){const{windows:s,windowSize:i}=HD(r,e),o=[];let a=n,c=a;for(let l=0;lv1||r>v1;)n&Pm&&(i=i.add(s)),r&Pm&&(o=o.add(s)),s=s.double(),n>>=Pm,r>>=Pm;return{p1:i,p2:o}}function yyt(t,e,n,r){pyt(n,t),gyt(r,e);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=nyt(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=hV(c),u=new Array(Number(l)+1).fill(o),d=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=d;p>=0;p-=c){u.fill(o);for(let y=0;y>BigInt(p)&l);u[v]=u[v].add(n[y])}let m=o;for(let y=u.length-1,b=o;y>0;y--)b=b.add(u[y]),m=m.add(b);if(f=f.add(m),p!==0)for(let y=0;yv1))throw new Error(`CURVE.${a} must be positive bigint`)}const r=ine(e.p,n.Fp),s=ine(e.n,n.Fn),o=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const a of o)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $d=BigInt(0),Wo=BigInt(1),GD=BigInt(2),byt=BigInt(8),vyt={zip215:!0};function xyt(t,e,n,r){const s=t.sqr(n),i=t.sqr(r),o=t.add(t.mul(e.a,s),i),a=t.add(t.ONE,t.mul(e.d,t.mul(s,i)));return t.eql(o,a)}function Eyt(t,e={}){const{Fp:n,Fn:r}=wyt("edwards",t,e),{h:s,n:i}=t;n8(e,{},{uvRatio:"function"});const o=GD<n.create(y),c=e.uvRatio||((y,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,b))}}catch{return{isValid:!1,value:$d}}});if(!xyt(n,t,t.Gx,t.Gy))throw new Error("bad curve params: generator point");function l(y,b,v=!1){const x=v?Wo:$d;return Tm("coordinate "+y,b,x,o),b}function u(y){if(!(y instanceof p))throw new Error("ExtendedPoint expected")}const d=ene((y,b)=>{const{ex:v,ey:x,ez:E}=y,A=y.is0();b==null&&(b=A?byt:n.inv(E));const _=a(v*b),k=a(x*b),B=a(E*b);if(A)return{x:$d,y:Wo};if(B!==Wo)throw new Error("invZ was invalid");return{x:_,y:k}}),f=ene(y=>{const{a:b,d:v}=t;if(y.is0())throw new Error("bad point: ZERO");const{ex:x,ey:E,ez:A,et:_}=y,k=a(x*x),B=a(E*E),W=a(A*A),S=a(W*W),$=a(k*b),R=a(W*a($+B)),M=a(S+a(v*a(k*B)));if(R!==M)throw new Error("bad point: equation left != right (1)");const j=a(x*E),z=a(A*_);if(j!==z)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(b,v,x,E){this.ex=l("x",b),this.ey=l("y",v),this.ez=l("z",x,!0),this.et=l("t",E),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof p)throw new Error("extended point not allowed");const{x:v,y:x}=b||{};return l("x",v),l("y",x),new p(v,x,Wo,a(v*x))}static normalizeZ(b){return hyt(p,"ez",b)}static msm(b,v){return yyt(p,r,b,v)}_setWindowSize(b){this.precompute(b)}precompute(b=8,v=!0){return m.setWindowSize(this,b),v||this.multiply(GD),this}assertValidity(){f(this)}equals(b){u(b);const{ex:v,ey:x,ez:E}=this,{ex:A,ey:_,ez:k}=b,B=a(v*k),W=a(A*E),S=a(x*k),$=a(_*E);return B===W&&S===$}is0(){return this.equals(p.ZERO)}negate(){return new p(a(-this.ex),this.ey,this.ez,a(-this.et))}double(){const{a:b}=t,{ex:v,ey:x,ez:E}=this,A=a(v*v),_=a(x*x),k=a(GD*a(E*E)),B=a(b*A),W=v+x,S=a(a(W*W)-A-_),$=B+_,R=$-k,M=B-_,j=a(S*R),z=a($*M),N=a(S*M),T=a(R*$);return new p(j,z,T,N)}add(b){u(b);const{a:v,d:x}=t,{ex:E,ey:A,ez:_,et:k}=this,{ex:B,ey:W,ez:S,et:$}=b,R=a(E*B),M=a(A*W),j=a(k*x*$),z=a(_*S),N=a((E+A)*(B+W)-R-M),T=z-j,U=z+j,L=a(M-v*R),P=a(N*T),H=a(U*L),Y=a(N*L),re=a(T*U);return new p(P,H,re,Y)}subtract(b){return this.add(b.negate())}multiply(b){const v=b;Tm("scalar",v,Wo,i);const{p:x,f:E}=m.wNAFCached(this,v,p.normalizeZ);return p.normalizeZ([x,E])[0]}multiplyUnsafe(b,v=p.ZERO){const x=b;return Tm("scalar",x,$d,i),x===$d?p.ZERO:this.is0()||x===Wo?this:m.wNAFCachedUnsafe(this,x,p.normalizeZ,v)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return m.wNAFCachedUnsafe(this,i).is0()}toAffine(b){return d(this,b)}clearCofactor(){return s===Wo?this:this.multiplyUnsafe(s)}static fromBytes(b,v=!1){return jl(b),this.fromHex(b,v)}static fromHex(b,v=!1){const{d:x,a:E}=t,A=n.BYTES;b=Nu("pointHex",b,A),JB("zip215",v);const _=b.slice(),k=b[A-1];_[A-1]=k&-129;const B=Fy(_),W=v?o:n.ORDER;Tm("pointHex.y",B,$d,W);const S=a(B*B),$=a(S-Wo),R=a(x*S-E);let{isValid:M,value:j}=c($,R);if(!M)throw new Error("Point.fromHex: invalid y coordinate");const z=(j&Wo)===Wo,N=(k&128)!==0;if(!v&&j===$d&&N)throw new Error("Point.fromHex: x=0 and x_0=1");return N!==z&&(j=a(-j)),p.fromAffine({x:j,y:B})}static fromPrivateScalar(b){return p.BASE.multiply(b)}toBytes(){const{x:b,y:v}=this.toAffine(),x=D3(v,n.BYTES);return x[x.length-1]|=b&Wo?128:0,x}toRawBytes(){return this.toBytes()}toHex(){return Dv(this.toBytes())}toString(){return``}}p.BASE=new p(t.Gx,t.Gy,Wo,a(t.Gx*t.Gy)),p.ZERO=new p($d,Wo,Wo,$d),p.Fp=n,p.Fn=r;const m=myt(p,r.BYTES*8);return p}function Cyt(t,e){n8(e,{hash:"function"},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n,hash:r}=e,{BASE:s,Fp:i,Fn:o}=t,a=o.ORDER,c=e.randomBytes||LS,l=e.adjustScalarBytes||(_=>_),u=e.domain||((_,k,B)=>{if(JB("phflag",B),k.length||B)throw new Error("Contexts/pre-hash are not supported");return _});function d(_){return o.create(_)}function f(_){return d(Fy(_))}function p(_){const k=i.BYTES;_=Nu("private key",_,k);const B=Nu("hashed private key",r(_),2*k),W=l(B.slice(0,k)),S=B.slice(k,2*k),$=f(W);return{head:W,prefix:S,scalar:$}}function m(_){const{head:k,prefix:B,scalar:W}=p(_),S=s.multiply(W),$=S.toBytes();return{head:k,prefix:B,scalar:W,point:S,pointBytes:$}}function y(_){return m(_).pointBytes}function b(_=Uint8Array.of(),...k){const B=mC(...k);return f(r(u(B,Nu("context",_),!!n)))}function v(_,k,B={}){_=Nu("message",_),n&&(_=n(_));const{prefix:W,scalar:S,pointBytes:$}=m(k),R=b(B.context,W,_),M=s.multiply(R).toBytes(),j=b(B.context,M,$,_),z=d(R+j*S);Tm("signature.s",z,$d,a);const N=i.BYTES,T=mC(M,D3(z,N));return Nu("result",T,N*2)}const x=vyt;function E(_,k,B,W=x){const{context:S,zip215:$}=W,R=i.BYTES;_=Nu("signature",_,2*R),k=Nu("message",k),B=Nu("publicKey",B,R),$!==void 0&&JB("zip215",$),n&&(k=n(k));const M=Fy(_.slice(R,2*R));let j,z,N;try{j=t.fromHex(B,$),z=t.fromHex(_.slice(0,R),$),N=s.multiplyUnsafe(M)}catch{return!1}if(!$&&j.isSmallOrder())return!1;const T=b(S,z.toBytes(),j.toBytes(),k);return z.add(j.multiplyUnsafe(T)).subtract(N).clearCofactor().is0()}return s.precompute(8),{getPublicKey:y,sign:v,verify:E,utils:{getExtendedPublicKey:m,randomPrivateKey:()=>c(i.BYTES),precompute(_=8,k=t.BASE){return k.precompute(_,!1)}},Point:t}}function _yt(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=r8(e.n,t.nBitLength,!0),s={Fp:n,Fn:r,uvRatio:t.uvRatio},i={hash:t.hash,randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:s,eddsaOpts:i}}function Syt(t,e){return Object.assign({},e,{ExtendedPoint:e.Point,CURVE:t})}function Ayt(t){const{CURVE:e,curveOpts:n,eddsaOpts:r}=_yt(t),s=Eyt(e,n),i=Cyt(s,r);return Syt(t,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const S2=BigInt(0),db=BigInt(1),JA=BigInt(2);function Iyt(t){return n8(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function Tyt(t){const e=Iyt(t),{P:n,type:r,adjustScalarBytes:s,powPminus2:i,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||LS,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),f=BigInt(a?121665:39081),p=a?JA**BigInt(254):JA**BigInt(447),m=a?BigInt(8)*JA**BigInt(251)-db:BigInt(4)*JA**BigInt(445)-db,y=p+m+db,b=S=>Rs(S,n),v=x(d);function x(S){return D3(b(S),u)}function E(S){const $=Nu("u coordinate",S,u);return a&&($[31]&=127),b(Fy($))}function A(S){return Fy(s(Nu("scalar",S,u)))}function _(S,$){const R=W(E($),A(S));if(R===S2)throw new Error("invalid private or public key received");return x(R)}function k(S){return _(S,v)}function B(S,$,R){const M=b(S*($-R));return $=b($-M),R=b(R+M),{x_2:$,x_3:R}}function W(S,$){Tm("u",S,S2,n),Tm("scalar",$,p,y);const R=$,M=S;let j=db,z=S2,N=S,T=db,U=S2;for(let P=BigInt(l-1);P>=S2;P--){const H=R>>P&db;U^=H,{x_2:j,x_3:N}=B(U,j,N),{x_2:z,x_3:T}=B(U,z,T),U=H;const Y=j+z,re=b(Y*Y),de=j-z,fe=b(de*de),ve=re-fe,Ee=N+T,oe=N-T,Oe=b(oe*Y),je=b(Ee*de),V=Oe+je,we=Oe-je;N=b(V*V),T=b(M*b(we*we)),j=b(re*fe),z=b(ve*(re+b(f*ve)))}({x_2:j,x_3:N}=B(U,j,N)),{x_2:z,x_3:T}=B(U,z,T);const L=i(z);return b(j*L)}return{scalarMult:_,scalarMultBase:k,getSharedSecret:(S,$)=>_(S,$),getPublicKey:S=>k(S),utils:{randomPrivateKey:()=>c(u)},GuBytes:v.slice()}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BigInt(0);const Nyt=BigInt(1),one=BigInt(2),Pyt=BigInt(3),kyt=BigInt(5),Ryt=BigInt(8),M3={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ryt,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Vme(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=M3.p,a=t*t%i*t%i,c=_u(a,one,i)*a%i,l=_u(c,Nyt,i)*t%i,u=_u(l,kyt,i)*l%i,d=_u(u,e,i)*u%i,f=_u(d,n,i)*d%i,p=_u(f,r,i)*f%i,m=_u(p,s,i)*p%i,y=_u(m,s,i)*p%i,b=_u(y,e,i)*u%i;return{pow_p_5_8:_u(b,one,i)*t%i,b2:a}}function Hme(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const ane=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Oyt(t,e){const n=M3.p,r=Rs(e*e*e,n),s=Rs(r*r*e,n),i=Vme(t*s).pow_p_5_8;let o=Rs(t*r*i,n);const a=Rs(e*o*o,n),c=o,l=Rs(o*ane,n),u=a===t,d=a===Rs(-t,n),f=a===Rs(-t*ane,n);return u&&(o=c),(d||f)&&(o=l),ayt(o,n)&&(o=Rs(-o,n)),{isValid:u||d,value:o}}const $yt=r8(M3.p,void 0,!0),Dyt={...M3,Fp:$yt,hash:zj,adjustScalarBytes:Hme,uvRatio:Oyt},K_=Ayt(Dyt),eI=(()=>{const t=M3.p;return Tyt({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=Vme(e);return Rs(_u(n,Pyt,t)*r,t)},adjustScalarBytes:Hme})})();let cne=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Myt=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};const jy={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new Myt("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}},qme=32,pV=64,eU=32;let pv;const Kme=(async()=>{try{return await jy.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Lyt(){const t=K_.utils.randomPrivateKey(),e=K_.getPublicKey(t);return{privateKey:Vyt(t,e),publicKey:e}}async function Byt(t,e){let n;t.length===pV?n=t.subarray(0,32):n=t;const r={crv:"Ed25519",kty:"OKP",x:hn(t.subarray(32),"base64url"),d:hn(n,"base64url"),ext:!0,key_ops:["sign"]},s=await jy.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),i=await jy.get().subtle.sign({name:"Ed25519"},s,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(i,0,i.byteLength)}function Uyt(t,e){const n=t.subarray(0,eU);return K_.sign(e instanceof Uint8Array?e:e.subarray(),n)}async function Fyt(t,e){return pv==null&&(pv=await Kme),pv?Byt(t,e):Uyt(t,e)}async function jyt(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await jy.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await jy.get().subtle.verify({name:"Ed25519"},r,e,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function zyt(t,e,n){return K_.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}async function Wyt(t,e,n){return pv==null&&(pv=await Kme),pv?jyt(t,e,n):zyt(t,e,n)}function Vyt(t,e){const n=new Uint8Array(pV);for(let r=0;r(r?.signal?.throwIfAborted(),i)):s}};class Hyt{type="Ed25519";raw;publicKey;constructor(e,n){this.raw=mV(e,pV),this.publicKey=new Gme(n)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:As(this.raw,e.raw)}sign(e,n){n?.signal?.throwIfAborted();const r=Fyt(this.raw,e);return gV(r)?r.then(s=>(n?.signal?.throwIfAborted(),s)):(n?.signal?.throwIfAborted(),r)}}function Zme(t){return t=mV(t,qme),new Gme(t)}async function qyt(){const{privateKey:t,publicKey:e}=Lyt();return new Hyt(t,e)}function mV(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new cr(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var ji;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(ji||(ji={}));var tU;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(tU||(tU={}));(function(t){t.codec=()=>JW(tU)})(ji||(ji={}));var x1;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),ji.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.Type=ji.codec().decode(n);break}case 2:{i.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(x1||(x1={}));var lne;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),ji.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.Type=ji.codec().decode(n);break}case 2:{i.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(lne||(lne={}));function yV(t){if(isNaN(t)||t<=0)throw new cr("random bytes length must be a Number bigger than 0");return LS(t)}let Kyt=class{type="RSA";jwk;_raw;_multihash;constructor(e,n){this.jwk=e,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Qyt(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Cr.createV1(114,this._multihash)}toString(){return ps.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:As(this.raw,e.raw)}verify(e,n,r){return twt(this.jwk,n,e,r)}};const Gyt=18,Zyt=1062,Yyt=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Xyt(t){const e=t8(t[1],{offset:0});return{kty:"RSA",n:hn(e[0],"base64url"),e:hn(e[1],"base64url")}}function Qyt(t){if(t.n==null||t.e==null)throw new cr("JWK was missing components");return UE([Yyt,Rme(UE([XB(Jt(t.n,"base64url")),XB(Jt(t.e,"base64url"))]))]).subarray()}function Jyt(t,e){if(t.byteLength>=Zyt)throw new oV("Key size is too large");const n=t8(t,{offset:0});return ewt(n,t,e)}function ewt(t,e,n){const r=Xyt(t);if(n==null){const s=Th(x1.encode({Type:ji.RSA,Data:e}));n=k3(Gyt,s)}return new Kyt(r,n)}async function twt(t,e,n,r){const s=await jy.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const i=await jy.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),i}var up={};const nwt=Zy(e9e);var s8={},wV={},Yme={},Xme={},i8={};Object.defineProperty(i8,"__esModule",{value:!0});i8.crypto=void 0;i8.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(t){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(t,"__esModule",{value:!0}),t.wrapXOFConstructorWithOpts=t.wrapConstructorWithOpts=t.wrapConstructor=t.Hash=t.nextTick=t.swap32IfBE=t.byteSwapIfBE=t.swap8IfBE=t.isLE=void 0,t.isBytes=n,t.anumber=r,t.abytes=s,t.ahash=i,t.aexists=o,t.aoutput=a,t.u8=c,t.u32=l,t.clean=u,t.createView=d,t.rotr=f,t.rotl=p,t.byteSwap=m,t.byteSwap32=y,t.bytesToHex=x,t.hexToBytes=_,t.asyncLoop=B,t.utf8ToBytes=W,t.bytesToUtf8=S,t.toBytes=$,t.kdfInputToBytes=R,t.concatBytes=M,t.checkOpts=j,t.createHasher=N,t.createOptHasher=T,t.createXOFer=U,t.randomBytes=L;const e=i8;function n(P){return P instanceof Uint8Array||ArrayBuffer.isView(P)&&P.constructor.name==="Uint8Array"}function r(P){if(!Number.isSafeInteger(P)||P<0)throw new Error("positive integer expected, got "+P)}function s(P,...H){if(!n(P))throw new Error("Uint8Array expected");if(H.length>0&&!H.includes(P.length))throw new Error("Uint8Array expected of length "+H+", got length="+P.length)}function i(P){if(typeof P!="function"||typeof P.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");r(P.outputLen),r(P.blockLen)}function o(P,H=!0){if(P.destroyed)throw new Error("Hash instance has been destroyed");if(H&&P.finished)throw new Error("Hash#digest() has already been called")}function a(P,H){s(P);const Y=H.outputLen;if(P.length>>H}function p(P,H){return P<>>32-H>>>0}t.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function m(P){return P<<24&4278190080|P<<8&16711680|P>>>8&65280|P>>>24&255}t.swap8IfBE=t.isLE?P=>P:P=>m(P),t.byteSwapIfBE=t.swap8IfBE;function y(P){for(let H=0;HP:y;const b=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",v=Array.from({length:256},(P,H)=>H.toString(16).padStart(2,"0"));function x(P){if(s(P),b)return P.toHex();let H="";for(let Y=0;Y=E._0&&P<=E._9)return P-E._0;if(P>=E.A&&P<=E.F)return P-(E.A-10);if(P>=E.a&&P<=E.f)return P-(E.a-10)}function _(P){if(typeof P!="string")throw new Error("hex string expected, got "+typeof P);if(b)return Uint8Array.fromHex(P);const H=P.length,Y=H/2;if(H%2)throw new Error("hex string expected, got unpadded hex of length "+H);const re=new Uint8Array(Y);for(let de=0,fe=0;de{};t.nextTick=k;async function B(P,H,Y){let re=Date.now();for(let de=0;de=0&&feP().update($(re)).digest(),Y=P();return H.outputLen=Y.outputLen,H.blockLen=Y.blockLen,H.create=()=>P(),H}function T(P){const H=(re,de)=>P(de).update($(re)).digest(),Y=P({});return H.outputLen=Y.outputLen,H.blockLen=Y.blockLen,H.create=re=>P(re),H}function U(P){const H=(re,de)=>P(de).update($(re)).digest(),Y=P({});return H.outputLen=Y.outputLen,H.blockLen=Y.blockLen,H.create=re=>P(re),H}t.wrapConstructor=N,t.wrapConstructorWithOpts=T,t.wrapXOFConstructorWithOpts=U;function L(P=32){if(e.crypto&&typeof e.crypto.getRandomValues=="function")return e.crypto.getRandomValues(new Uint8Array(P));if(e.crypto&&typeof e.crypto.randomBytes=="function")return Uint8Array.from(e.crypto.randomBytes(P));throw new Error("crypto.getRandomValues must be defined")}})(Xme);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.hmac=t.HMAC=void 0;const e=Xme;class n extends e.Hash{constructor(i,o){super(),this.finished=!1,this.destroyed=!1,(0,e.ahash)(i);const a=(0,e.toBytes)(o);if(this.iHash=i.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 c=this.blockLen,l=new Uint8Array(c);l.set(a.length>c?i.create().update(a).digest():a);for(let u=0;unew n(s,i).update(o).digest();t.hmac=r,t.hmac.create=(s,i)=>new n(s,i)})(Yme);var Pf={},Gr={};Object.defineProperty(Gr,"__esModule",{value:!0});Gr.isNegativeLE=void 0;Gr.mod=Nc;Gr.pow=swt;Gr.pow2=iwt;Gr.invert=s4;Gr.tonelliShanks=nye;Gr.FpSqrt=rye;Gr.validateField=lwt;Gr.FpPow=bV;Gr.FpInvertBatch=sye;Gr.FpDiv=uwt;Gr.FpLegendre=i4;Gr.FpIsSquare=dwt;Gr.nLength=vV;Gr.Field=xV;Gr.FpSqrtOdd=fwt;Gr.FpSqrtEven=hwt;Gr.hashToPrivateScalar=pwt;Gr.getFieldBytesLength=EV;Gr.getMinHashLength=iye;Gr.mapHashToField=gwt;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ba=lx,Va=BigInt(0),ii=BigInt(1),km=BigInt(2),rwt=BigInt(3),Qme=BigInt(4),Jme=BigInt(5),eye=BigInt(8);function Nc(t,e){const n=t%e;return n>=Va?n:e+n}function swt(t,e,n){return bV(xV(n),t,e)}function iwt(t,e,n){let r=t;for(;e-- >Va;)r*=r,r%=n;return r}function s4(t,e){if(t===Va)throw new Error("invert: expected non-zero number");if(e<=Va)throw new Error("invert: expected positive modulus, got "+e);let n=Nc(t,e),r=e,s=Va,i=ii;for(;n!==Va;){const a=r/n,c=r%n,l=s-i*a;r=n,n=c,s=i,i=l}if(r!==ii)throw new Error("invert: does not exist");return Nc(s,e)}function tye(t,e){const n=(t.ORDER+ii)/Qme,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function owt(t,e){const n=(t.ORDER-Jme)/eye,r=t.mul(e,km),s=t.pow(r,n),i=t.mul(e,s),o=t.mul(t.mul(i,km),s),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function nye(t){if(t1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return tye;let i=s.pow(r,e);const o=(e+ii)/km;return function(c,l){if(c.is0(l))return l;if(i4(c,l)!==1)throw new Error("Cannot find square root");let u=n,d=c.mul(c.ONE,i),f=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let m=1,y=c.sqr(f);for(;!c.eql(y,c.ONE);)if(m++,y=c.sqr(y),m===u)throw new Error("Cannot find square root");const b=ii<(Nc(t,e)&ii)===ii;Gr.isNegativeLE=awt;const cwt=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function lwt(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=cwt.reduce((r,s)=>(r[s]="function",r),e);return(0,Ba._validateObject)(t,n),t}function bV(t,e,n){if(nVa;)n&ii&&(r=t.mul(r,s)),s=t.sqr(s),n>>=ii;return r}function sye(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),i),r}function uwt(t,e,n){return t.mul(e,typeof n=="bigint"?s4(n,t.ORDER):t.inv(n))}function i4(t,e){const n=(t.ORDER-ii)/km,r=t.pow(e,n),s=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function dwt(t,e){return i4(t,e)===1}function vV(t,e){e!==void 0&&(0,Ba.anumber)(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function xV(t,e,n=!1,r={}){if(t<=Va)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,i;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const u=e;u.BITS&&(s=u.BITS),u.sqrt&&(i=u.sqrt),typeof u.isLE=="boolean"&&(n=u.isLE)}else typeof e=="number"&&(s=e),r.sqrt&&(i=r.sqrt);const{nBitLength:o,nByteLength:a}=vV(t,s);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const l=Object.freeze({ORDER:t,isLE:n,BITS:o,BYTES:a,MASK:(0,Ba.bitMask)(o),ZERO:Va,ONE:ii,create:u=>Nc(u,t),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return Va<=u&&uu===Va,isValidNot0:u=>!l.is0(u)&&l.isValid(u),isOdd:u=>(u&ii)===ii,neg:u=>Nc(-u,t),eql:(u,d)=>u===d,sqr:u=>Nc(u*u,t),add:(u,d)=>Nc(u+d,t),sub:(u,d)=>Nc(u-d,t),mul:(u,d)=>Nc(u*d,t),pow:(u,d)=>bV(l,u,d),div:(u,d)=>Nc(u*s4(d,t),t),sqrN:u=>u*u,addN:(u,d)=>u+d,subN:(u,d)=>u-d,mulN:(u,d)=>u*d,inv:u=>s4(u,t),sqrt:i||(u=>(c||(c=rye(t)),c(l,u))),toBytes:u=>n?(0,Ba.numberToBytesLE)(u,a):(0,Ba.numberToBytesBE)(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return n?(0,Ba.bytesToNumberLE)(u):(0,Ba.bytesToNumberBE)(u)},invertBatch:u=>sye(l,u),cmov:(u,d,f)=>f?d:u});return Object.freeze(l)}function fwt(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");const n=t.sqrt(e);return t.isOdd(n)?n:t.neg(n)}function hwt(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");const n=t.sqrt(e);return t.isOdd(n)?t.neg(n):n}function pwt(t,e,n=!1){t=(0,Ba.ensureBytes)("privateHash",t);const r=t.length,s=vV(e).nByteLength+8;if(s<24||r1024)throw new Error("hashToPrivateScalar: expected "+s+"-1024 bytes of input, got "+r);const i=n?(0,Ba.bytesToNumberLE)(t):(0,Ba.bytesToNumberBE)(t);return Nc(i,e-ii)+ii}function EV(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function iye(t){const e=EV(t);return e+Math.ceil(e/2)}function gwt(t,e,n=!1){const r=t.length,s=EV(e),i=iye(e);if(r<16||r1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const o=n?(0,Ba.bytesToNumberLE)(t):(0,Ba.bytesToNumberBE)(t),a=Nc(o,e-ii)+ii;return n?(0,Ba.numberToBytesLE)(a,s):(0,Ba.numberToBytesBE)(a,s)}Object.defineProperty(Pf,"__esModule",{value:!0});Pf.negateCt=i6;Pf.normalizeZ=mwt;Pf.wNAF=ywt;Pf.mulEndoUnsafe=wwt;Pf.pippenger=bwt;Pf.precomputeMSMUnsafe=vwt;Pf.validateBasic=xwt;Pf._createCurveFields=Ewt;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const G_=lx,Z_=Gr,E1=BigInt(0),Rm=BigInt(1);function i6(t,e){const n=e.negate();return t?n:e}function mwt(t,e,n){const r=e==="pz"?o=>o.pz:o=>o.ez,s=(0,Z_.FpInvertBatch)(t.Fp,n.map(r));return n.map((o,a)=>o.toAffine(s[a])).map(t.fromAffine)}function CV(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ZD(t,e){CV(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,i=(0,G_.bitMask)(t),o=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function une(t,e,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=n;let a=Number(t&s),c=t>>o;a>r&&(a-=i,c+=Rm);const l=e*r,u=l+Math.abs(a)-1,d=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function oye(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function aye(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const YD=new WeakMap,cye=new WeakMap;function XD(t){return cye.get(t)||1}function dne(t){if(t!==E1)throw new Error("invalid wNAF")}function ywt(t,e){return{constTimeNegate:i6,hasPrecomputes(n){return XD(n)!==1},unsafeLadder(n,r,s=t.ZERO){let i=n;for(;r>E1;)r&Rm&&(s=s.add(i)),i=i.double(),r>>=Rm;return s},precomputeWindow(n,r){const{windows:s,windowSize:i}=ZD(r,e),o=[];let a=n,c=a;for(let l=0;lE1||r>E1;)n&Rm&&(i=i.add(s)),r&Rm&&(o=o.add(s)),s=s.double(),n>>=Rm,r>>=Rm;return{p1:i,p2:o}}function bwt(t,e,n,r){oye(n,t),aye(r,e);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=(0,G_.bitLen)(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=(0,G_.bitMask)(c),u=new Array(Number(l)+1).fill(o),d=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=d;p>=0;p-=c){u.fill(o);for(let y=0;y>BigInt(p)&l);u[v]=u[v].add(n[y])}let m=o;for(let y=u.length-1,b=o;y>0;y--)b=b.add(u[y]),m=m.add(b);if(f=f.add(m),p!==0)for(let y=0;y{const u=[];for(let d=0,f=l;d{if(aye(l,e),l.length>n.length)throw new Error("array of scalars must be smaller than array of points");let u=s;for(let d=0;d>f&a);y&&(u=u.add(c[p][y-1]))}}return u}}function xwt(t){return(0,Z_.validateField)(t.Fp),(0,G_.validateObject)(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...(0,Z_.nLength)(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function fne(t,e){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return(0,Z_.validateField)(e),e}else return(0,Z_.Field)(t)}function Ewt(t,e,n={}){if(!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>E1))throw new Error(`CURVE.${a} must be positive bigint`)}const r=fne(e.p,n.Fp),s=fne(e.n,n.Fn),o=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const a of o)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:s}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.DER=t.DERErr=void 0,t._legacyHelperEquat=f,t._legacyHelperNormPriv=p,t.weierstrassN=m,t.weierstrassPoints=y,t.ecdsa=v,t.weierstrass=k,t.SWUFpSqrtRatio=B,t.mapToCurveSimpleSWU=W;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const e=Yme,n=lx,r=Pf,s=Gr;function i(S){S.lowS!==void 0&&(0,n.abool)("lowS",S.lowS),S.prehash!==void 0&&(0,n.abool)("prehash",S.prehash)}class o extends Error{constructor($=""){super($)}}t.DERErr=o,t.DER={Err:o,_tlv:{encode:(S,$)=>{const{Err:R}=t.DER;if(S<0||S>256)throw new R("tlv.encode: wrong tag");if($.length&1)throw new R("tlv.encode: unpadded data");const M=$.length/2,j=(0,n.numberToHexUnpadded)(M);if(j.length/2&128)throw new R("tlv.encode: long form length too big");const z=M>127?(0,n.numberToHexUnpadded)(j.length/2|128):"";return(0,n.numberToHexUnpadded)(S)+z+j+$},decode(S,$){const{Err:R}=t.DER;let M=0;if(S<0||S>256)throw new R("tlv.encode: wrong tag");if($.length<2||$[M++]!==S)throw new R("tlv.decode: wrong tlv");const j=$[M++],z=!!(j&128);let N=0;if(!z)N=j;else{const U=j&127;if(!U)throw new R("tlv.decode(long): indefinite length not supported");if(U>4)throw new R("tlv.decode(long): byte length is too big");const L=$.subarray(M,M+U);if(L.length!==U)throw new R("tlv.decode: length bytes not complete");if(L[0]===0)throw new R("tlv.decode(long): zero leftmost byte");for(const P of L)N=N<<8|P;if(M+=U,N<128)throw new R("tlv.decode(long): not minimal encoding")}const T=$.subarray(M,M+N);if(T.length!==N)throw new R("tlv.decode: wrong value length");return{v:T,l:$.subarray(M+N)}}},_int:{encode(S){const{Err:$}=t.DER;if(S{const{px:Me,py:be,pz:pe}=Ie;if(R.eql(pe,R.ONE))return{x:Me,y:be};const J=Ie.is0();ge==null&&(ge=J?R.ONE:R.inv(pe));const ie=R.mul(Me,ge),ae=R.mul(be,ge),Pe=R.mul(pe,ge);if(J)return{x:R.ZERO,y:R.ZERO};if(!R.eql(Pe,R.ONE))throw new Error("invZ was invalid");return{x:ie,y:ae}}),Oe=(0,n.memoized)(Ie=>{if(Ie.is0()){if($.allowInfinityPoint&&!R.is0(Ie.py))return;throw new Error("bad point: ZERO")}const{x:ge,y:Me}=Ie.toAffine();if(!R.isValid(ge)||!R.isValid(Me))throw new Error("bad point: x or y not field elements");if(!re(ge,Me))throw new Error("bad point: equation left != right");if(!Ie.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function je(Ie,ge,Me,be,pe){return Me=new V(R.mul(Me.px,Ie),Me.py,Me.pz),ge=(0,r.negateCt)(be,ge),Me=(0,r.negateCt)(pe,Me),ge.add(Me)}class V{constructor(ge,Me,be){this.px=ve("x",ge),this.py=ve("y",Me,!0),this.pz=ve("z",be),Object.freeze(this)}static fromAffine(ge){const{x:Me,y:be}=ge||{};if(!ge||!R.isValid(Me)||!R.isValid(be))throw new Error("invalid affine point");if(ge instanceof V)throw new Error("projective point not allowed");return R.is0(Me)&&R.is0(be)?V.ZERO:new V(Me,be,R.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(ge){return(0,r.normalizeZ)(V,"pz",ge)}static fromBytes(ge){return(0,n.abytes)(ge),V.fromHex(ge)}static fromHex(ge){const Me=V.fromAffine(H((0,n.ensureBytes)("pointHex",ge)));return Me.assertValidity(),Me}static fromPrivateKey(ge){const Me=p(M,$.allowedPrivateKeyLengths,$.wrapPrivateKey);return V.BASE.multiply(Me(ge))}static msm(ge,Me){return(0,r.pippenger)(V,M,ge,Me)}precompute(ge=8,Me=!0){return Ae.setWindowSize(this,ge),Me||this.multiply(u),this}_setWindowSize(ge){this.precompute(ge)}assertValidity(){Oe(this)}hasEvenY(){const{y:ge}=this.toAffine();if(!R.isOdd)throw new Error("Field doesn't support isOdd");return!R.isOdd(ge)}equals(ge){Ee(ge);const{px:Me,py:be,pz:pe}=this,{px:J,py:ie,pz:ae}=ge,Pe=R.eql(R.mul(Me,ae),R.mul(J,pe)),$e=R.eql(R.mul(be,ae),R.mul(ie,pe));return Pe&&$e}negate(){return new V(this.px,R.neg(this.py),this.pz)}double(){const{a:ge,b:Me}=S,be=R.mul(Me,u),{px:pe,py:J,pz:ie}=this;let ae=R.ZERO,Pe=R.ZERO,$e=R.ZERO,Re=R.mul(pe,pe),ut=R.mul(J,J),Je=R.mul(ie,ie),ft=R.mul(pe,J);return ft=R.add(ft,ft),$e=R.mul(pe,ie),$e=R.add($e,$e),ae=R.mul(ge,$e),Pe=R.mul(be,Je),Pe=R.add(ae,Pe),ae=R.sub(ut,Pe),Pe=R.add(ut,Pe),Pe=R.mul(ae,Pe),ae=R.mul(ft,ae),$e=R.mul(be,$e),Je=R.mul(ge,Je),ft=R.sub(Re,Je),ft=R.mul(ge,ft),ft=R.add(ft,$e),$e=R.add(Re,Re),Re=R.add($e,Re),Re=R.add(Re,Je),Re=R.mul(Re,ft),Pe=R.add(Pe,Re),Je=R.mul(J,ie),Je=R.add(Je,Je),Re=R.mul(Je,ft),ae=R.sub(ae,Re),$e=R.mul(Je,ut),$e=R.add($e,$e),$e=R.add($e,$e),new V(ae,Pe,$e)}add(ge){Ee(ge);const{px:Me,py:be,pz:pe}=this,{px:J,py:ie,pz:ae}=ge;let Pe=R.ZERO,$e=R.ZERO,Re=R.ZERO;const ut=S.a,Je=R.mul(S.b,u);let ft=R.mul(Me,J),Z=R.mul(be,ie),O=R.mul(pe,ae),F=R.add(Me,be),ne=R.add(J,ie);F=R.mul(F,ne),ne=R.add(ft,Z),F=R.sub(F,ne),ne=R.add(Me,pe);let he=R.add(J,ae);return ne=R.mul(ne,he),he=R.add(ft,O),ne=R.sub(ne,he),he=R.add(be,pe),Pe=R.add(ie,ae),he=R.mul(he,Pe),Pe=R.add(Z,O),he=R.sub(he,Pe),Re=R.mul(ut,ne),Pe=R.mul(Je,O),Re=R.add(Pe,Re),Pe=R.sub(Z,Re),Re=R.add(Z,Re),$e=R.mul(Pe,Re),Z=R.add(ft,ft),Z=R.add(Z,ft),O=R.mul(ut,O),ne=R.mul(Je,ne),Z=R.add(Z,O),O=R.sub(ft,O),O=R.mul(ut,O),ne=R.add(ne,O),ft=R.mul(Z,ne),$e=R.add($e,ft),ft=R.mul(he,ne),Pe=R.mul(F,Pe),Pe=R.sub(Pe,ft),ft=R.mul(F,Z),Re=R.mul(he,Re),Re=R.add(Re,ft),new V(Pe,$e,Re)}subtract(ge){return this.add(ge.negate())}is0(){return this.equals(V.ZERO)}multiply(ge){const{endo:Me}=$;if(!M.isValidNot0(ge))throw new Error("invalid scalar: out of range");let be,pe;const J=ie=>Ae.wNAFCached(this,ie,V.normalizeZ);if(Me){const{k1neg:ie,k1:ae,k2neg:Pe,k2:$e}=Me.splitScalar(ge),{p:Re,f:ut}=J(ae),{p:Je,f:ft}=J($e);pe=ut.add(ft),be=je(Me.beta,Re,Je,ie,Pe)}else{const{p:ie,f:ae}=J(ge);be=ie,pe=ae}return V.normalizeZ([be,pe])[0]}multiplyUnsafe(ge){const{endo:Me}=$,be=this;if(!M.isValid(ge))throw new Error("invalid scalar: out of range");if(ge===a||be.is0())return V.ZERO;if(ge===c)return be;if(Ae.hasPrecomputes(this))return this.multiply(ge);if(Me){const{k1neg:pe,k1:J,k2neg:ie,k2:ae}=Me.splitScalar(ge),{p1:Pe,p2:$e}=(0,r.mulEndoUnsafe)(V,be,J,ae);return je(Me.beta,Pe,$e,pe,ie)}else return Ae.wNAFCachedUnsafe(be,ge)}multiplyAndAddUnsafe(ge,Me,be){const pe=this.multiplyUnsafe(Me).add(ge.multiplyUnsafe(be));return pe.is0()?void 0:pe}toAffine(ge){return oe(this,ge)}isTorsionFree(){const{isTorsionFree:ge}=$;return j===c?!0:ge?ge(V,this):Ae.wNAFCachedUnsafe(this,z).is0()}clearCofactor(){const{clearCofactor:ge}=$;return j===c?this:ge?ge(V,this):this.multiplyUnsafe(j)}toBytes(ge=!0){return(0,n.abool)("isCompressed",ge),this.assertValidity(),P(V,this,ge)}toRawBytes(ge=!0){return this.toBytes(ge)}toHex(ge=!0){return(0,n.bytesToHex)(this.toBytes(ge))}toString(){return``}}V.BASE=new V(S.Gx,S.Gy,R.ONE),V.ZERO=new V(R.ZERO,R.ONE,R.ZERO),V.Fp=R,V.Fn=M;const we=M.BITS,Ae=(0,r.wNAF)(V,$.endo?Math.ceil(we/2):we);return V}function y(S){const{CURVE:$,curveOpts:R}=x(S),M=m($,R);return A(S,M)}function b(S){return Uint8Array.of(S?2:3)}function v(S,$,R={}){(0,n._validateObject)($,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const M=$.randomBytes||n.randomBytes,j=$.hmac||((be,...pe)=>(0,e.hmac)($.hash,be,(0,n.concatBytes)(...pe))),{Fp:z,Fn:N}=S,{ORDER:T,BITS:U}=N;function L(be){const pe=T>>c;return be>pe}function P(be){return L(be)?N.neg(be):be}function H(be,pe){if(!N.isValidNot0(pe))throw new Error(`invalid signature ${be}: out of range 1..CURVE.n`)}class Y{constructor(pe,J,ie){H("r",pe),H("s",J),this.r=pe,this.s=J,ie!=null&&(this.recovery=ie),Object.freeze(this)}static fromCompact(pe){const J=N.BYTES,ie=(0,n.ensureBytes)("compactSignature",pe,J*2);return new Y(N.fromBytes(ie.subarray(0,J)),N.fromBytes(ie.subarray(J,J*2)))}static fromDER(pe){const{r:J,s:ie}=t.DER.toSig((0,n.ensureBytes)("DER",pe));return new Y(J,ie)}assertValidity(){}addRecoveryBit(pe){return new Y(this.r,this.s,pe)}recoverPublicKey(pe){const J=z.ORDER,{r:ie,s:ae,recovery:Pe}=this;if(Pe==null||![0,1,2,3].includes(Pe))throw new Error("recovery id invalid");if(T*l1)throw new Error("recovery id is ambiguous for h>1 curve");const Re=Pe===2||Pe===3?ie+T:ie;if(!z.isValid(Re))throw new Error("recovery id 2 or 3 invalid");const ut=z.toBytes(Re),Je=S.fromHex((0,n.concatBytes)(b((Pe&1)===0),ut)),ft=N.inv(Re),Z=Oe((0,n.ensureBytes)("msgHash",pe)),O=N.create(-Z*ft),F=N.create(ae*ft),ne=S.BASE.multiplyUnsafe(O).add(Je.multiplyUnsafe(F));if(ne.is0())throw new Error("point at infinify");return ne.assertValidity(),ne}hasHighS(){return L(this.s)}normalizeS(){return this.hasHighS()?new Y(this.r,N.neg(this.s),this.recovery):this}toBytes(pe){if(pe==="compact")return(0,n.concatBytes)(N.toBytes(this.r),N.toBytes(this.s));if(pe==="der")return(0,n.hexToBytes)(t.DER.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return(0,n.bytesToHex)(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return(0,n.bytesToHex)(this.toBytes("compact"))}}const re=p(N,R.allowedPrivateKeyLengths,R.wrapPrivateKey),de={isValidPrivateKey(be){try{return re(be),!0}catch{return!1}},normPrivateKeyToScalar:re,randomPrivateKey:()=>{const be=T;return(0,s.mapHashToField)(M((0,s.getMinHashLength)(be)),be)},precompute(be=8,pe=S.BASE){return pe.precompute(be,!1)}};function fe(be,pe=!0){return S.fromPrivateKey(be).toBytes(pe)}function ve(be){if(typeof be=="bigint")return!1;if(be instanceof S)return!0;const J=(0,n.ensureBytes)("key",be).length,ie=z.BYTES,ae=ie+1,Pe=2*ie+1;if(!(R.allowedPrivateKeyLengths||N.BYTES===ae))return J===ae||J===Pe}function Ee(be,pe,J=!0){if(ve(be)===!0)throw new Error("first arg must be private key");if(ve(pe)===!1)throw new Error("second arg must be public key");return S.fromHex(pe).multiply(re(be)).toBytes(J)}const oe=$.bits2int||function(be){if(be.length>8192)throw new Error("input is too large");const pe=(0,n.bytesToNumberBE)(be),J=be.length*8-U;return J>0?pe>>BigInt(J):pe},Oe=$.bits2int_modN||function(be){return N.create(oe(be))},je=(0,n.bitMask)(U);function V(be){return(0,n.aInRange)("num < 2^"+U,be,a,je),N.toBytes(be)}function we(be,pe,J=Ae){if(["recovered","canonical"].some(F=>F in J))throw new Error("sign() legacy options not supported");const{hash:ie}=$;let{lowS:ae,prehash:Pe,extraEntropy:$e}=J;ae==null&&(ae=!0),be=(0,n.ensureBytes)("msgHash",be),i(J),Pe&&(be=(0,n.ensureBytes)("prehashed msgHash",ie(be)));const Re=Oe(be),ut=re(pe),Je=[V(ut),V(Re)];if($e!=null&&$e!==!1){const F=$e===!0?M(z.BYTES):$e;Je.push((0,n.ensureBytes)("extraEntropy",F))}const ft=(0,n.concatBytes)(...Je),Z=Re;function O(F){const ne=oe(F);if(!N.isValidNot0(ne))return;const he=N.inv(ne),Te=S.BASE.multiply(ne).toAffine(),Fe=N.create(Te.x);if(Fe===a)return;const Bt=N.create(he*N.create(Z+Fe*ut));if(Bt===a)return;let vn=(Te.x===Fe?0:2)|Number(Te.y&c),Kt=Bt;return ae&&L(Bt)&&(Kt=P(Bt),vn^=1),new Y(Fe,Kt,vn)}return{seed:ft,k2sig:O}}const Ae={lowS:$.lowS,prehash:!1},Ie={lowS:$.lowS,prehash:!1};function ge(be,pe,J=Ae){const{seed:ie,k2sig:ae}=we(be,pe,J);return(0,n.createHmacDrbg)($.hash.outputLen,N.BYTES,j)(ie,ae)}S.BASE.precompute(8);function Me(be,pe,J,ie=Ie){const ae=be;pe=(0,n.ensureBytes)("msgHash",pe),J=(0,n.ensureBytes)("publicKey",J),i(ie);const{lowS:Pe,prehash:$e,format:Re}=ie;if("strict"in ie)throw new Error("options.strict was renamed to lowS");if(Re!==void 0&&!["compact","der","js"].includes(Re))throw new Error('format must be "compact", "der" or "js"');const ut=typeof ae=="string"||(0,n.isBytes)(ae),Je=!ut&&!Re&&typeof ae=="object"&&ae!==null&&typeof ae.r=="bigint"&&typeof ae.s=="bigint";if(!ut&&!Je)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let ft,Z;try{if(Je)if(Re===void 0||Re==="js")ft=new Y(ae.r,ae.s);else throw new Error("invalid format");if(ut){try{Re!=="compact"&&(ft=Y.fromDER(ae))}catch(Kt){if(!(Kt instanceof t.DER.Err))throw Kt}!ft&&Re!=="der"&&(ft=Y.fromCompact(ae))}Z=S.fromHex(J)}catch{return!1}if(!ft||Pe&&ft.hasHighS())return!1;$e&&(pe=$.hash(pe));const{r:O,s:F}=ft,ne=Oe(pe),he=N.inv(F),Te=N.create(ne*he),Fe=N.create(O*he),Bt=S.BASE.multiplyUnsafe(Te).add(Z.multiplyUnsafe(Fe));return Bt.is0()?!1:N.create(Bt.x)===O}return Object.freeze({getPublicKey:fe,getSharedSecret:Ee,sign:ge,verify:Me,utils:de,Point:S,Signature:Y})}function x(S){const $={a:S.a,b:S.b,p:S.Fp.ORDER,n:S.n,h:S.h,Gx:S.Gx,Gy:S.Gy},R=S.Fp,M=(0,s.Field)($.n,S.nBitLength),j={Fp:R,Fn:M,allowedPrivateKeyLengths:S.allowedPrivateKeyLengths,allowInfinityPoint:S.allowInfinityPoint,endo:S.endo,wrapPrivateKey:S.wrapPrivateKey,isTorsionFree:S.isTorsionFree,clearCofactor:S.clearCofactor,fromBytes:S.fromBytes,toBytes:S.toBytes};return{CURVE:$,curveOpts:j}}function E(S){const{CURVE:$,curveOpts:R}=x(S),M={hash:S.hash,hmac:S.hmac,randomBytes:S.randomBytes,lowS:S.lowS,bits2int:S.bits2int,bits2int_modN:S.bits2int_modN};return{CURVE:$,curveOpts:R,ecdsaOpts:M}}function A(S,$){const{Fp:R,Fn:M}=$;function j(T){return(0,n.inRange)(T,c,M.ORDER)}const z=f(R,S.a,S.b),N=p(M,S.allowedPrivateKeyLengths,S.wrapPrivateKey);return Object.assign({},{CURVE:S,Point:$,ProjectivePoint:$,normPrivateKeyToScalar:N,weierstrassEquation:z,isWithinCurveOrder:j})}function _(S,$){return Object.assign({},$,{ProjectivePoint:$.Point,CURVE:S})}function k(S){const{CURVE:$,curveOpts:R,ecdsaOpts:M}=E(S),j=m($,R),z=v(j,M,R);return _(S,z)}function B(S,$){const R=S.ORDER;let M=a;for(let de=R-c;de%l===a;de/=l)M+=c;const j=M,z=l<{let ve=H,Ee=S.pow(fe,L),oe=S.sqr(Ee);oe=S.mul(oe,fe);let Oe=S.mul(de,oe);Oe=S.pow(Oe,U),Oe=S.mul(Oe,Ee),Ee=S.mul(Oe,fe),oe=S.mul(Oe,de);let je=S.mul(oe,Ee);Oe=S.pow(je,P);let V=S.eql(Oe,S.ONE);Ee=S.mul(oe,Y),Oe=S.mul(je,ve),oe=S.cmov(Ee,oe,V),je=S.cmov(Oe,je,V);for(let we=j;we>c;we--){let Ae=we-l;Ae=l<{let oe=S.sqr(Ee);const Oe=S.mul(ve,Ee);oe=S.mul(oe,Oe);let je=S.pow(oe,de);je=S.mul(je,Oe);const V=S.mul(je,fe),we=S.mul(S.sqr(je),Ee),Ae=S.eql(we,ve);let Ie=S.cmov(V,je,Ae);return{isValid:Ae,value:Ie}}}return re}function W(S,$){(0,s.validateField)(S);const{A:R,B:M,Z:j}=$;if(!S.isValid(R)||!S.isValid(M)||!S.isValid(j))throw new Error("mapToCurveSimpleSWU: invalid opts");const z=B(S,j);if(!S.isOdd)throw new Error("Field does not have .isOdd()");return N=>{let T,U,L,P,H,Y,re,de;T=S.sqr(N),T=S.mul(T,j),U=S.sqr(T),U=S.add(U,T),L=S.add(U,S.ONE),L=S.mul(L,M),P=S.cmov(j,S.neg(U),!S.eql(U,S.ZERO)),P=S.mul(P,R),U=S.sqr(L),Y=S.sqr(P),H=S.mul(Y,R),U=S.add(U,H),U=S.mul(U,L),Y=S.mul(Y,P),H=S.mul(Y,M),U=S.add(U,H),re=S.mul(T,L);const{isValid:fe,value:ve}=z(U,Y);de=S.mul(T,N),de=S.mul(de,ve),re=S.cmov(re,L,fe),de=S.cmov(de,ve,fe);const Ee=S.isOdd(N)===S.isOdd(de);de=S.cmov(S.neg(de),de,Ee);const oe=(0,s.FpInvertBatch)(S,[P],!0)[0];return re=S.mul(re,oe),{x:re,y:de}}}})(wV);Object.defineProperty(s8,"__esModule",{value:!0});s8.getHash=_wt;s8.createCurve=Swt;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Cwt=wV;function _wt(t){return{hash:t}}function Swt(t,e){const n=r=>(0,Cwt.weierstrass)({...t,hash:r});return{...n(e),create:n}}var bw={};Object.defineProperty(bw,"__esModule",{value:!0});bw.expand_message_xmd=uye;bw.expand_message_xof=dye;bw.hash_to_field=nU;bw.isogenyMap=Twt;bw.createHasher=Nwt;const pi=lx,lye=Gr,Awt=pi.bytesToNumberBE;function mg(t,e){if(Y_(t),Y_(e),t<0||t>=1<<8*e)throw new Error("invalid I2OSP input: "+t);const n=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)n[r]=t&255,t>>>=8;return new Uint8Array(n)}function Iwt(t,e){const n=new Uint8Array(t.length);for(let r=0;r255&&(e=r((0,pi.concatBytes)((0,pi.utf8ToBytes)("H2C-OVERSIZE-DST-"),e)));const{outputLen:s,blockLen:i}=r,o=Math.ceil(n/s);if(n>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const a=(0,pi.concatBytes)(e,mg(e.length,1)),c=mg(0,i),l=mg(n,2),u=new Array(o),d=r((0,pi.concatBytes)(c,t,l,mg(0,1),a));u[0]=r((0,pi.concatBytes)(d,mg(1,1),a));for(let p=1;p<=o;p++){const m=[Iwt(d,u[p-1]),mg(p+1,1),a];u[p]=r((0,pi.concatBytes)(...m))}return(0,pi.concatBytes)(...u).slice(0,n)}function dye(t,e,n,r,s){if((0,pi.abytes)(t),(0,pi.abytes)(e),Y_(n),e.length>255){const i=Math.ceil(2*r/8);e=s.create({dkLen:i}).update((0,pi.utf8ToBytes)("H2C-OVERSIZE-DST-")).update(e).digest()}if(n>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return s.create({dkLen:n}).update(t).update(mg(n,2)).update(e).update(mg(e.length,1)).digest()}function nU(t,e,n){(0,pi._validateObject)(n,{p:"bigint",m:"number",k:"number",hash:"function"});const{p:r,k:s,m:i,hash:o,expand:a,DST:c}=n;if(!(0,pi.isBytes)(c)&&typeof c!="string")throw new Error("DST must be string or uint8array");if(!(0,pi.isHash)(n.hash))throw new Error("expected valid hash");(0,pi.abytes)(t),Y_(e);const l=typeof c=="string"?(0,pi.utf8ToBytes)(c):c,u=r.toString(2).length,d=Math.ceil((u+s)/8),f=e*i*d;let p;if(a==="xmd")p=uye(t,l,f,o);else if(a==="xof")p=dye(t,l,f,s,o);else if(a==="_internal_pass")p=t;else throw new Error('expand must be "xmd" or "xof"');const m=new Array(e);for(let y=0;yArray.from(r).reverse());return(r,s)=>{const[i,o,a,c]=n.map(d=>d.reduce((f,p)=>t.add(t.mul(f,r),p))),[l,u]=(0,lye.FpInvertBatch)(t,[o,c],!0);return r=t.mul(i,l),s=t.mul(s,t.mul(a,u)),{x:r,y:s}}}function Nwt(t,e,n){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function r(i){return t.fromAffine(e(i))}function s(i){const o=i.clearCofactor();return o.equals(t.ZERO)?t.ZERO:(o.assertValidity(),o)}return{defaults:n,hashToCurve(i,o){const a=n.DST?n.DST:{},c=Object.assign({},n,a,o),l=nU(i,2,c),u=r(l[0]),d=r(l[1]);return s(u.add(d))},encodeToCurve(i,o){const a=n.encodeDST?n.encodeDST:{},c=Object.assign({},n,a,o),l=nU(i,1,c);return s(r(l[0]))},mapToCurve(i){if(!Array.isArray(i))throw new Error("expected array of bigints");for(const o of i)if(typeof o!="bigint")throw new Error("expected array of bigints");return s(r(i))}}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.encodeToCurve=t.hashToCurve=t.secp256k1_hasher=t.schnorr=t.secp256k1=void 0;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const e=nwt,n=xT,r=s8,s=bw,i=Gr,o=wV,a=lx,c={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},l=BigInt(0),u=BigInt(1),d=BigInt(2),f=(T,U)=>(T+U/d)/U;function p(T){const U=c.p,L=BigInt(3),P=BigInt(6),H=BigInt(11),Y=BigInt(22),re=BigInt(23),de=BigInt(44),fe=BigInt(88),ve=T*T*T%U,Ee=ve*ve*T%U,oe=(0,i.pow2)(Ee,L,U)*Ee%U,Oe=(0,i.pow2)(oe,L,U)*Ee%U,je=(0,i.pow2)(Oe,d,U)*ve%U,V=(0,i.pow2)(je,H,U)*je%U,we=(0,i.pow2)(V,Y,U)*V%U,Ae=(0,i.pow2)(we,de,U)*we%U,Ie=(0,i.pow2)(Ae,fe,U)*Ae%U,ge=(0,i.pow2)(Ie,de,U)*we%U,Me=(0,i.pow2)(ge,L,U)*Ee%U,be=(0,i.pow2)(Me,re,U)*V%U,pe=(0,i.pow2)(be,P,U)*ve%U,J=(0,i.pow2)(pe,d,U);if(!m.eql(m.sqr(J),T))throw new Error("Cannot find square root");return J}const m=(0,i.Field)(c.p,void 0,void 0,{sqrt:p});t.secp256k1=(0,r.createCurve)({...c,Fp:m,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:T=>{const U=c.n,L=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),P=-u*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),H=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),Y=L,re=BigInt("0x100000000000000000000000000000000"),de=f(Y*T,U),fe=f(-P*T,U);let ve=(0,i.mod)(T-de*L-fe*H,U),Ee=(0,i.mod)(-de*P-fe*Y,U);const oe=ve>re,Oe=Ee>re;if(oe&&(ve=U-ve),Oe&&(Ee=U-Ee),ve>re||Ee>re)throw new Error("splitScalar: Endomorphism failed, k="+T);return{k1neg:oe,k1:ve,k2neg:Oe,k2:Ee}}}},e.sha256);const y={};function b(T,...U){let L=y[T];if(L===void 0){const P=(0,e.sha256)(Uint8Array.from(T,H=>H.charCodeAt(0)));L=(0,a.concatBytes)(P,P),y[T]=L}return(0,e.sha256)((0,a.concatBytes)(L,...U))}const v=T=>T.toBytes(!0).slice(1),x=T=>(0,a.numberToBytesBE)(T,32),E=T=>(0,i.mod)(T,c.p),A=T=>(0,i.mod)(T,c.n),_=t.secp256k1.Point,k=T=>T%d===l;function B(T){let U=t.secp256k1.utils.normPrivateKeyToScalar(T),L=_.fromPrivateKey(U);return{scalar:k(L.y)?U:A(-U),bytes:v(L)}}function W(T){(0,a.aInRange)("x",T,u,c.p);const U=E(T*T),L=E(U*T+BigInt(7));let P=p(L);k(P)||(P=E(-P));const H=_.fromAffine({x:T,y:P});return H.assertValidity(),H}const S=a.bytesToNumberBE;function $(...T){return A(S(b("BIP0340/challenge",...T)))}function R(T){return B(T).bytes}function M(T,U,L=(0,n.randomBytes)(32)){const P=(0,a.ensureBytes)("message",T),{bytes:H,scalar:Y}=B(U),re=(0,a.ensureBytes)("auxRand",L,32),de=x(Y^S(b("BIP0340/aux",re))),fe=b("BIP0340/nonce",de,H,P),ve=A(S(fe));if(ve===l)throw new Error("sign failed: k is zero");const{bytes:Ee,scalar:oe}=B(ve),Oe=$(Ee,H,P),je=new Uint8Array(64);if(je.set(Ee,0),je.set(x(A(oe+Oe*Y)),32),!j(je,P,H))throw new Error("sign: Invalid signature produced");return je}function j(T,U,L){const P=(0,a.ensureBytes)("signature",T,64),H=(0,a.ensureBytes)("message",U),Y=(0,a.ensureBytes)("publicKey",L,32);try{const re=W(S(Y)),de=S(P.subarray(0,32));if(!(0,a.inRange)(de,u,c.p))return!1;const fe=S(P.subarray(32,64));if(!(0,a.inRange)(fe,u,c.n))return!1;const ve=$(x(de),v(re),H),Ee=_.BASE.multiplyUnsafe(fe).add(re.multiplyUnsafe(A(-ve))),{x:oe,y:Oe}=Ee.toAffine();return!(Ee.is0()||!k(Oe)||oe!==de)}catch{return!1}}t.schnorr={getPublicKey:R,sign:M,verify:j,utils:{randomPrivateKey:t.secp256k1.utils.randomPrivateKey,lift_x:W,pointToBytes:v,numberToBytesBE:a.numberToBytesBE,bytesToNumberBE:a.bytesToNumberBE,taggedHash:b,mod:i.mod}};const z=(0,s.isogenyMap)(m,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(T=>T.map(U=>BigInt(U)))),N=(0,o.mapToCurveSimpleSWU)(m,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:m.create(BigInt("-11"))});t.secp256k1_hasher=(0,s.createHasher)(t.secp256k1.Point,T=>{const{x:U,y:L}=N(m.create(T[0]));return z(U,L)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:m.ORDER,m:1,k:128,expand:"xmd",hash:e.sha256}),t.hashToCurve=t.secp256k1_hasher.hashToCurve,t.encodeToCurve=t.secp256k1_hasher.encodeToCurve})(up);function Pwt(t,e,n,r){const s=QW.digest(n instanceof Uint8Array?n:n.subarray());if(gV(s))return s.then(({digest:i})=>(r?.signal?.throwIfAborted(),up.secp256k1.verify(e,i,t))).catch(i=>{throw i.name==="AbortError"?i:new cne(String(i))});try{return r?.signal?.throwIfAborted(),up.secp256k1.verify(e,s.digest,t)}catch(i){throw new cne(String(i))}}let kwt=class{type="secp256k1";raw;_key;constructor(e){this._key=Owt(e),this.raw=Rwt(this._key)}toMultihash(){return L0.digest(Rh(this))}toCID(){return Cr.createV1(114,this.toMultihash())}toString(){return ps.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:As(this.raw,e.raw)}verify(e,n,r){return Pwt(this._key,n,e,r)}};function fye(t){return new kwt(t)}function Rwt(t){return up.secp256k1.ProjectivePoint.fromHex(t).toRawBytes(!0)}function Owt(t){try{return up.secp256k1.ProjectivePoint.fromHex(t),t}catch(e){throw new oV(String(e))}}async function $wt(t,e){return qyt()}function x0(t,e){const{Type:n,Data:r}=x1.decode(t),s=r??new Uint8Array;switch(n){case ji.RSA:return Jyt(s,e);case ji.Ed25519:return Zme(s);case ji.secp256k1:return fye(s);case ji.ECDSA:return Ome(s);default:throw new e8}}function Dwt(t){const{Type:e,Data:n}=x1.decode(t.digest),r=n??new Uint8Array;switch(e){case ji.Ed25519:return Zme(r);case ji.secp256k1:return fye(r);case ji.ECDSA:return Ome(r);default:throw new e8}}function Rh(t){return x1.encode({Type:ji[t.type],Data:t.raw})}const hye=Symbol.for("nodejs.util.inspect.custom"),Mwt=114;let _V=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Jk]=!0;toString(){return this.string==null&&(this.string=ps.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Cr.createV1(Mwt,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return As(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return As(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[hye](){return`PeerId(${this.toString()})`}},pye=class extends _V{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},gye=class extends _V{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},mye=class extends _V{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}};const Lwt=2336;class yye{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=L0.digest(Jt(this.url))}[hye](){return`PeerId(${this.url})`}[Jk]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Cr.createV1(Lwt,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=hn(e)),e.toString()===this.toString())}}const Bwt=114,hne=2336;function yf(t,e){let n;if(t.charAt(0)==="1"||t.charAt(0)==="Q")n=Zk(ps.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return L3(Cr.parse(t));throw new cr('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return o8(n)}function X_(t){if(t.type==="Ed25519")return new gye({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new mye({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new pye({multihash:t.toCID().multihash,publicKey:t});throw new e8}function Uwt(t){return X_(t.publicKey)}function o8(t){if(jwt(t))return new pye({multihash:t});if(Fwt(t))try{const e=Dwt(t);if(e.type==="Ed25519")return new gye({multihash:t,publicKey:e});if(e.type==="secp256k1")return new mye({multihash:t,publicKey:e})}catch{const n=hn(t.digest);return new yye(new URL(n))}throw new Rmt("Supplied PeerID Multihash is invalid")}function L3(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Bwt&&t.code!==hne)throw new kmt("Supplied PeerID CID is invalid");if(t.code===hne){const e=hn(t.multihash.digest);return new yye(new URL(e))}return o8(t.multihash)}function Fwt(t){return t.code===L0.code}function jwt(t){return t.code===QW.code}class Rl extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class Q_ extends Error{static name="ValidationError";name="ValidationError"}class zwt extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class Wwt extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}class Vwt{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const n=this.index,r=e();return r===void 0&&(this.index=n),r}parseWith(e){const n=e();if(this.index===this.input.length)return n}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{const n=this.readChar();if(n===e)return n})}readSeparator(e,n,r){return this.readAtomically(()=>{if(!(n>0&&this.readGivenChar(e)===void 0))return r()})}readNumber(e,n,r,s){return this.readAtomically(()=>{let i=0,o=0;const a=this.peekChar();if(a===void 0)return;const c=a==="0",l=2**(8*s)-1;for(;;){const u=this.readAtomically(()=>{const d=this.readChar();if(d===void 0)return;const f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(i*=e,i+=u,i>l||(o+=1,n!==void 0&&o>n))return}if(o!==0)return!r&&c&&o>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{const e=new Uint8Array(4);for(let n=0;nthis.readNumber(10,3,!1,1));if(r===void 0)return;e[n]=r}return e})}readIPv6Addr(){const e=n=>{for(let r=0;rthis.readIPv4Addr());if(o!==void 0)return n[s]=o[0],n[s+1]=o[1],n[s+2]=o[2],n[s+3]=o[3],[s+4,!0]}const i=this.readSeparator(":",r,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[s,!1];n[s]=i>>8,n[s+1]=i&255}return[n.length,!1]};return this.readAtomically(()=>{const n=new Uint8Array(16),[r,s]=e(n);if(r===16)return n;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;const i=new Uint8Array(14),o=16-(r+2),[a]=e(i.subarray(0,o));return n.set(i.subarray(0,a),16-a),n})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}}const wye=45,Hwt=15,C1=new Vwt;function bye(t){if(!(t.length>Hwt))return C1.new(t).parseWith(()=>C1.readIPv4Addr())}function vye(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>wye))return C1.new(t).parseWith(()=>C1.readIPv6Addr())}function rU(t,e=!1){if(t.includes("%")&&(t=t.split("%")[0]),t.length>wye)return;const n=C1.new(t).parseWith(()=>C1.readIPAddr());if(n)return e&&n.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,n[0],n[1],n[2],n[3]]):n}function zy(t){return!!bye(t)}function SV(t){return!!vye(t)}const _1=4,o4=6,sU=273,qwt=33,Zu=41,xx=42,Kwt=43,a8=53,c8=54,B3=55,l8=56,Gwt=132,Zwt=301,Ywt=302,Xwt=400,xye=421,Qwt=444,Jwt=445,ebt=446,tbt=447,Eye=448,nbt=449,rbt=454,sbt=460,ibt=461,obt=465,abt=466,cbt=480,lbt=481,ubt=443,dbt=477,fbt=478,hbt=479,pbt=277,gbt=275,mbt=276,ybt=280,wbt=281,Cye=290,bbt=777;function pne(t){return e=>hn(e,t)}function gne(t){return e=>Jt(e,t)}function Y2(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function Gb(t){const e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function vbt(t){const e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);const n=Jt(e[0],"base32"),r=parseInt(e[1],10);if(r<1||r>65536)throw new Error("Port number is not in range(1, 65536)");const s=Gb(r);return Uy([n,s],n.length+s.length)}function xbt(t){const e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);const n=e0.decode(`b${e[0]}`),r=parseInt(e[1],10);if(r<1||r>65536)throw new Error("Port number is not in range(1, 65536)");const s=Gb(r);return Uy([n,s],n.length+s.length)}function mne(t){const e=t.subarray(0,t.length-2),n=t.subarray(t.length-2),r=hn(e,"base32"),s=Y2(n);return`${r}:${s}`}const _ye=function(t){t=t.toString().trim();const e=new Uint8Array(4);return t.split(/\./g).forEach((n,r)=>{const s=parseInt(n,10);if(isNaN(s)||s<0||s>255)throw new Rl("Invalid byte value in IP address");e[r]=s}),e},Ebt=function(t){let e=0;t=t.toString().trim();const n=t.split(":",8);let r;for(r=0;r0;r--)i.push("0");n.splice.apply(n,i)}const s=new Uint8Array(e+16);for(r=0;r65535)throw new Rl("Invalid byte value in IP address");s[e++]=i>>8&255,s[e++]=i&255}return s},Cbt=function(t){if(t.byteLength!==4)throw new Rl("IPv4 address was incorrect length");const e=[];for(let n=0;nt.decoder),Abt=function(){let t=QD[0].or(QD[1]);return QD.slice(2).forEach(e=>t=t.or(e)),t}();function Ibt(t){return Abt.decode(t)}function Tbt(t){return e=>t.encoder.encode(e)}function Nbt(t){if(parseInt(t).toString()!==t)throw new Q_("Value must be an integer")}function Pbt(t){if(t<0)throw new Q_("Value must be a positive integer, or zero")}function kbt(t){return e=>{if(e>t)throw new Q_(`Value must be smaller than or equal to ${t}`)}}function Rbt(...t){return e=>{for(const n of t)n(e)}}const tI=Rbt(Nbt,Pbt,kbt(65535)),wo=-1;class Obt{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let n;if(typeof e=="string"?n=this.protocolsByName.get(e):n=this.protocolsByCode.get(e),n==null)throw new Wwt(`Protocol ${e} was unknown`);return n}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(n=>{this.protocolsByName.set(n,e)})}removeProtocol(e){const n=this.protocolsByCode.get(e);n!=null&&(this.protocolsByCode.delete(n.code),this.protocolsByName.delete(n.name),n.aliases?.forEach(r=>{this.protocolsByName.delete(r)}))}}const Ll=new Obt,$bt=[{code:_1,name:"ip4",size:32,valueToBytes:_ye,bytesToValue:Cbt,validate:t=>{if(!zy(t))throw new Q_(`Invalid IPv4 address "${t}"`)}},{code:o4,name:"tcp",size:16,valueToBytes:Gb,bytesToValue:Y2,validate:tI},{code:sU,name:"udp",size:16,valueToBytes:Gb,bytesToValue:Y2,validate:tI},{code:qwt,name:"dccp",size:16,valueToBytes:Gb,bytesToValue:Y2,validate:tI},{code:Zu,name:"ip6",size:128,valueToBytes:Ebt,bytesToValue:_bt,stringToValue:Sbt,validate:t=>{if(!SV(t))throw new Q_(`Invalid IPv6 address "${t}"`)}},{code:xx,name:"ip6zone",size:wo},{code:Kwt,name:"ipcidr",size:8,bytesToValue:pne("base10"),valueToBytes:gne("base10")},{code:a8,name:"dns",size:wo,resolvable:!0},{code:c8,name:"dns4",size:wo,resolvable:!0},{code:B3,name:"dns6",size:wo,resolvable:!0},{code:l8,name:"dnsaddr",size:wo,resolvable:!0},{code:Gwt,name:"sctp",size:16,valueToBytes:Gb,bytesToValue:Y2,validate:tI},{code:Zwt,name:"udt"},{code:Ywt,name:"utp"},{code:Xwt,name:"unix",size:wo,path:!0,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:xye,name:"p2p",aliases:["ipfs"],size:wo,bytesToValue:pne("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?gne("base58btc")(t):Cr.parse(t).multihash.bytes},{code:Qwt,name:"onion",size:96,bytesToValue:mne,valueToBytes:vbt},{code:Jwt,name:"onion3",size:296,bytesToValue:mne,valueToBytes:xbt},{code:ebt,name:"garlic64",size:wo},{code:tbt,name:"garlic32",size:wo},{code:Eye,name:"tls"},{code:nbt,name:"sni",size:wo},{code:rbt,name:"noise"},{code:sbt,name:"quic"},{code:ibt,name:"quic-v1"},{code:obt,name:"webtransport"},{code:abt,name:"certhash",size:wo,bytesToValue:Tbt(YW),valueToBytes:Ibt},{code:cbt,name:"http"},{code:lbt,name:"http-path",size:wo,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.substring(1))},{code:ubt,name:"https"},{code:dbt,name:"ws"},{code:fbt,name:"wss"},{code:hbt,name:"p2p-websocket-star"},{code:pbt,name:"p2p-stardust"},{code:gbt,name:"p2p-webrtc-star"},{code:mbt,name:"p2p-webrtc-direct"},{code:ybt,name:"webrtc-direct"},{code:wbt,name:"webrtc"},{code:Cye,name:"p2p-circuit"},{code:bbt,name:"memory",size:wo}];$bt.forEach(t=>{Ll.addProtocol(t)});function Dbt(t){const e=[];let n=0;for(;n0&&s.size===wo&&(a=Vi(o));const c=i+a+o,l={code:r,name:s.name,bytes:t.subarray(n,n+c)};if(o>0){const u=n+i+a,d=t.subarray(u,u+o);l.value=s.bytesToValue?.(d)??hn(d)}e.push(l),n+=c}return e}function Mbt(t){let e=0;const n=[];for(const r of t){if(r.bytes==null){const s=Ll.getProtocol(r.code),i=Vi(r.code);let o,a=0,c=0;r.value!=null&&(o=s.valueToBytes?.(r.value)??Jt(r.value),a=o.byteLength,s.size===wo&&(c=Vi(a)));const l=new Uint8Array(i+c+a);let u=0;CN(r.code,l,u),u+=i,o!=null&&(s.size===wo&&(CN(a,l,u),u+=c),l.set(o,u)),r.bytes=l}n.push(r.bytes),e+=r.bytes.byteLength}return Uy(n,e)}function Lbt(t){if(t.charAt(0)!=="/")throw new Rl('String multiaddr must start with "/"');const e=[];let n="protocol",r="",s="";for(let i=1;i{if(e.value==null)return e.name;const n=Ll.getProtocol(e.code);if(n==null)throw new Rl(`Unknown protocol code ${e.code}`);return[e.name,n.valueToString?.(e.value)??e.value]}).join("/")}`}function Ubt(t,e,n){return t.size==null||t.size===0?0:t.size>0?t.size/8:N3(e,n)}const Fbt=Symbol.for("nodejs.util.inspect.custom"),Sye=Symbol.for("@multiformats/multiaddr"),jbt=[a8,c8,B3,l8];class zbt extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}function Wbt(t){if(t==null&&(t="/"),u8(t))return t.getComponents();if(t instanceof Uint8Array)return Dbt(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),Lbt(t);if(Array.isArray(t))return t;throw new Rl("Must be a string, Uint8Array, Component[], or another Multiaddr")}class Zb{[Sye]=!0;#e;#t;#n;constructor(e="/",n={}){this.#e=Wbt(e),n.validate!==!1&&Vbt(this)}get bytes(){return this.#n==null&&(this.#n=Mbt(this.#e)),this.#n}toString(){return this.#t==null&&(this.#t=Bbt(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,n,r,s,i="";for(const{code:a,name:c,value:l}of this.#e)a===xx&&(i=`%${l??""}`),jbt.includes(a)&&(n="tcp",s=443,r=`${l??""}${i}`,e=a===B3?6:4),(a===o4||a===sU)&&(n=c==="tcp"?"tcp":"udp",s=parseInt(l??"")),(a===_1||a===Zu)&&(n="tcp",r=`${l??""}${i}`,e=a===Zu?6:4);if(e==null||n==null||r==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:n,port:s}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:n})=>{const r=Ll.getProtocol(e);return{code:e,size:r.size??0,name:r.name,resolvable:!!r.resolvable,path:!!r.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:n})=>{if(n==null)return[e];const r=Ll.getProtocol(e),s=[e];return n!=null&&s.push(r.valueToBytes?.(n)??Jt(n)),s})}stringTuples(){return this.#e.map(({code:e,value:n})=>n==null?[e]:[e,n])}encapsulate(e){const n=new Zb(e);return new Zb([...this.#e,...n.getComponents()],{validate:!1})}decapsulate(e){const n=e.toString(),r=this.toString(),s=r.lastIndexOf(n);if(s<0)throw new zwt(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new Zb(r.slice(0,s),{validate:!1})}decapsulateCode(e){let n;for(let r=this.#e.length-1;r>-1;r--)if(this.#e[r].code===e){n=r;break}return new Zb(this.#e.slice(0,n),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:r,value:s})=>{r===xye&&e.push([r,s]),r===Cye&&(e=[])});const n=e.pop();if(n?.[1]!=null){const r=n[1];return r[0]==="Q"||r[0]==="1"?hn(ps.decode(`z${r}`),"base58btc"):hn(Cr.parse(r).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(const e of this.#e)if(Ll.getProtocol(e.code).path)return e.value??null;return null}equals(e){return As(this.bytes,e.bytes)}async resolve(e){const n=this.protos().find(i=>i.resolvable);if(n==null)return[this];const r=AV.get(n.name);if(r==null)throw new zbt(`no available resolver for ${n.name}`);return(await r(this,e)).map(i=>er(i))}nodeAddress(){const e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(this.#e.length!==2||this.#e[0].code!==_1&&this.#e[0].code!==Zu||this.#e[1].code!==o4&&this.#e[1].code!==sU)}[Fbt](){return`Multiaddr(${this.toString()})`}}function Vbt(t){t.getComponents().forEach(e=>{const n=Ll.getProtocol(e.code);e.value!=null&&n.validate?.(e.value)})}function Hbt(t,e,n){let r=0;for(const s of t)if(!(rn)break;if(s!==255)return!1;r++}return!0}function qbt(t,e,n,r){let s=0;for(const i of t)if(!(sr)break;if(i!==e[s])return!1;s++}return!0}function Kbt(t){switch(t.length){case J_:return t.join(".");case eS:{const e=[];for(let n=0;n>4).toString(16)+(n&15).toString(16);return e}const J_=4,eS=16,Ybt=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Aye(t,e){e.length===eS&&t.length===J_&&Hbt(e,0,11)&&(e=e.slice(12)),e.length===J_&&t.length===eS&&qbt(t,Ybt,0,11)&&(t=t.slice(12));const n=t.length;if(n!=e.length)throw new Error("Failed to mask ip");const r=new Uint8Array(n);for(let s=0;sr*8)throw new Error("Failed to parse given CIDR: "+t);const o=Iye(i,8*r);return{network:Aye(s,o),mask:o}}function Iye(t,e){if(e!==8*J_&&e!==8*eS)throw new Error("Invalid CIDR mask");if(t<0||t>e)throw new Error("Invalid CIDR mask");const n=e/8,r=new Uint8Array(n);for(let s=0;s=8){r[s]=255,t-=8;continue}r[s]=255-(255>>t),t=0}return r}class Tye{constructor(e,n){if(n==null)({network:this.network,mask:this.mask}=Qbt(e));else{const r=rU(e);if(r==null)throw new Error("Failed to parse network");n=String(n);const s=parseInt(n,10);if(Number.isNaN(s)||String(s).length!==n.length||s<0||s>r.length*8){const i=rU(n);if(i==null)throw new Error("Failed to parse mask");this.mask=i}else this.mask=Iye(s,8*r.length);this.network=Aye(r,this.mask)}}contains(e){return Xbt({network:this.network,mask:this.mask},e)}toString(){const e=Gbt(this.mask),n=e!==-1?String(e):Zbt(this.mask);return Kbt(this.network)+"/"+n}}function Jbt(t,e){return new Tye(t).contains(e)}function evt(t){let e,n;if(t.getComponents().forEach(r=>{(r.name==="ip4"||r.name==="ip6")&&(n=r.value),r.name==="ipcidr"&&(e=r.value)}),e==null||n==null)throw new Error("Invalid multiaddr");return new Tye(n,e)}function a4(t,e){return Ll.getProtocol(t).bytesToValue?.(e)??hn(e,"base16")}function tvt(t,e){return Ll.getProtocol(t).valueToBytes?.(e)??Jt(e,"base16")}const AV=new Map;function u8(t){return!!t?.[Sye]}function er(t){return new Zb(t)}function IV(t){const e=Ll.getProtocol(t);return{code:e.code,size:e.size??0,name:e.name,resolvable:!!e.resolvable,path:!!e.path}}const yne=t=>{if(!t)return-1;try{const e=t.metadata.get("ping");return e?Number(j_(e)):-1}catch{return-1}},nvt=t=>Zm(t)?t:er(t),rvt=t=>Zm(t)?t:yf(er(t).getPeerId()),rg=new rr("connection-manager"),svt=3,ivt=5*60,ovt=5*60,avt=!0,cvt=10,lvt=3,uvt=60,dvt=10;class fvt{keepAliveManager;discoveryDialer;dialer;shardReader;networkMonitor;connectionLimiter;options;libp2p;constructor(e){this.libp2p=e.libp2p,this.options={maxBootstrapPeers:svt,maxConnections:cvt,pingKeepAlive:ivt,relayKeepAlive:ovt,enableAutoRecovery:avt,maxDialingPeers:lvt,failedDialCooldown:uvt,dialCooldown:dvt,...e.config},this.keepAliveManager=new bmt({relay:e.relay,libp2p:e.libp2p,networkConfig:e.networkConfig,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.shardReader=new xmt({libp2p:e.libp2p,networkConfig:e.networkConfig}),this.dialer=new ymt({libp2p:e.libp2p,shardReader:this.shardReader,options:this.options}),this.discoveryDialer=new wmt({libp2p:e.libp2p,dialer:this.dialer}),this.networkMonitor=new vmt({libp2p:e.libp2p,events:e.events}),this.connectionLimiter=new mmt({libp2p:e.libp2p,events:e.events,networkMonitor:this.networkMonitor,dialer:this.dialer,options:this.options})}start(){this.dialer.start(),this.networkMonitor.start(),this.discoveryDialer.start(),this.keepAliveManager.start(),this.connectionLimiter.start()}stop(){this.dialer.stop(),this.networkMonitor.stop(),this.discoveryDialer.stop(),this.keepAliveManager.stop(),this.connectionLimiter.stop()}isConnected(){return this.networkMonitor.isConnected()}async dial(e,n){const r=nvt(e);rg.info(`Dialing peer ${r.toString()} with protocols ${n}`);const s=await this.libp2p.dialProtocol(r,n);return rg.info(`Dialed peer ${r.toString()} with protocols ${n}`),s}async hangUp(e){const n=rvt(e);try{return rg.info(`Dropping connection with peer ${n.toString()}`),await this.libp2p.hangUp(n),rg.info(`Dropped connection with peer ${n.toString()}`),!0}catch(r){return rg.error(`Error dropping connection with peer ${n.toString()} - ${r}`),!1}}async getConnectedPeers(e){const n=this.libp2p.getPeers();if(rg.info(`Getting connected peers for codec ${e}`),n.length===0)return rg.info("No connected peers"),[];const s=(await Promise.all(n.map(async i=>{try{return await this.libp2p.peerStore.get(i)}catch{return null}}))).filter(i=>!!i).filter(i=>e?i.protocols.includes(e):!0).sort((i,o)=>yne(i)-yne(o));return rg.info(`Found ${s.length} connected peers for codec ${e}`),s}async hasShardInfo(e){return this.shardReader.hasShardInfo(e)}async isPeerOnTopic(e,n){return this.shardReader.isPeerOnTopic(e,n)}async isPeerOnShard(e,n){return this.shardReader.isPeerOnShard(e,n)}}const JD=new rr("metadata"),e9="/vac/waku/metadata/1.0.0";class hvt{clusterId;streamManager;libp2pComponents;handshakesConfirmed=new Map;multicodec=e9;constructor(e,n){this.clusterId=e,this.streamManager=new O3(e9,n),this.libp2pComponents=n,n.registrar.handle(e9,r=>{this.onRequest(r)})}async query(e){const n=HB.encode({clusterId:this.clusterId,shards:[]});if(!await this.libp2pComponents.peerStore.get(e))return{shardInfo:null,error:Sn.NO_PEER_AVAILABLE};const s=await this.streamManager.getStream(e);if(!s)return JD.error(`Failed to get a stream for remote peer:${e.toString()}`),{shardInfo:null,error:Sn.NO_STREAM_AVAILABLE};const i=await Tl([n],Eh,s,Hd,async c=>await Gu(c)),{error:o,shardInfo:a}=this.decodeMetadataResponse(i);return o?{shardInfo:null,error:o}:(await this.savePeerShardInfo(e,a),{shardInfo:a,error:null})}async confirmOrAttemptHandshake(e){const n=this.handshakesConfirmed.get(e.toString());return n?{shardInfo:n,error:null}:await this.query(e)}async onRequest(e){try{const{stream:n,connection:r}=e,s=XN.encode({clusterId:this.clusterId,shards:[]}),i=await Tl([s],Eh,n,Hd,async c=>await Gu(c)),{error:o,shardInfo:a}=this.decodeMetadataResponse(i);if(o)return;await this.savePeerShardInfo(r.remotePeer,a)}catch(n){JD.error("Error handling metadata request",n)}}decodeMetadataResponse(e){const n=new mn;e.forEach(s=>{n.append(s)});const r=XN.decode(n);return r?{shardInfo:r,error:null}:(JD.error("Error decoding metadata response"),{shardInfo:null,error:Sn.DECODE_FAILED})}async savePeerShardInfo(e,n){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:nV(n)}}),this.handshakesConfirmed.set(e.toString(),n)}}function pvt(t){return e=>new hvt(t,e)}const xc=new rr("peer-manager"),gvt=2;var Uu;(function(t){t.FilterConnect="filter:connect",t.FilterDisconnect="filter:disconnect",t.StoreConnect="store:connect"})(Uu||(Uu={}));class mvt{events=new Oo;numPeersToUse;libp2p;connectionManager;lockedPeers=new Set;unlockedPeers=new Map;constructor(e){this.onConnected=this.onConnected.bind(this),this.onDisconnected=this.onDisconnected.bind(this),this.numPeersToUse=e?.config?.numPeersToUse||gvt,this.libp2p=e.libp2p,this.connectionManager=e.connectionManager}start(){this.libp2p.addEventListener("peer:identify",this.onConnected),this.libp2p.addEventListener("peer:disconnect",this.onDisconnected)}stop(){this.libp2p.removeEventListener("peer:identify",this.onConnected),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnected)}async getPeers(e){xc.info(`Getting peers for protocol: ${e.protocol}, pubsubTopic: ${e.pubsubTopic}`);const n=await this.connectionManager.getConnectedPeers();xc.info(`Found ${n.length} connected peers`);let r=[];for(const a of n){const c=this.hasPeerProtocol(a,e.protocol),l=await this.connectionManager.isPeerOnTopic(a.id,e.pubsubTopic),u=this.isPeerAvailableForUse(a.id);c&&l&&u&&(r.push(a),xc.info(`Peer ${a.id} qualifies for protocol ${e.protocol}`))}const s=r.filter(a=>this.isPeerLocked(a.id));if(xc.info(`Found ${s.length} locked peers out of ${r.length} qualifying peers`),s.length>=this.numPeersToUse){const a=s.slice(0,this.numPeersToUse).map(c=>c.id);return xc.info(`Using ${a.length} locked peers: ${a.map(c=>c.toString())}`),a}const i=r.filter(a=>!this.isPeerLocked(a.id));xc.info(`Found ${i.length} unlocked peers, need ${this.numPeersToUse-s.length} more`),r=[...s,...i].slice(0,this.numPeersToUse).map(a=>(this.lockPeer(a.id),a));const o=r.map(a=>a.id);return xc.info(`Selected ${o.length} peers: ${o.map(a=>a.toString())}`),o}async renewPeer(e,n){xc.info(`Renewing peer ${e} for protocol: ${n.protocol}, pubsubTopic: ${n.pubsubTopic}`);const s=(await this.connectionManager.getConnectedPeers()).find(i=>i.id.equals(e));if(!s){xc.warn(`Cannot renew peer:${e}, no connection to the peer.`);return}xc.info(`Found peer ${e} in connected peers, unlocking and getting new peers`),this.unlockPeer(s.id),await this.getPeers(n)}async isPeerOnPubsub(e,n){return await this.connectionManager.hasShardInfo(e)?this.connectionManager.isPeerOnTopic(e,n):!0}async onConnected(e){const n=e.detail;n.protocols.includes(this.matchProtocolToCodec(zn.Filter))&&this.dispatchFilterPeerConnect(n.peerId),n.protocols.includes(this.matchProtocolToCodec(zn.Store))&&this.dispatchStorePeerConnect(n.peerId)}async onDisconnected(e){const n=e.detail;try{const r=await this.libp2p.peerStore.get(n);this.hasPeerProtocol(r,zn.Filter)&&this.dispatchFilterPeerDisconnect(r.id)}catch(r){xc.error(`Failed to dispatch Filter disconnect event:${r}`)}}hasPeerProtocol(e,n){return e.protocols.includes(this.matchProtocolToCodec(n))}lockPeer(e){xc.info(`Locking peer ${e}`),this.lockedPeers.add(e.toString()),this.libp2p.getConnections().filter(n=>n.remotePeer.equals(e)).forEach(n=>n.tags.push(GB)),this.unlockedPeers.delete(e.toString())}isPeerLocked(e){return this.lockedPeers.has(e.toString())}unlockPeer(e){xc.info(`Unlocking peer ${e}`),this.lockedPeers.delete(e.toString()),this.libp2p.getConnections().filter(n=>n.remotePeer.equals(e)).forEach(n=>{n.tags=n.tags.filter(r=>r!==GB)}),this.unlockedPeers.set(e.toString(),Date.now())}isPeerAvailableForUse(e){const n=this.unlockedPeers.get(e.toString());if(!n)return!0;const r=new Date(n).getTime();return Date.now()-r>=1e4}dispatchFilterPeerConnect(e){this.events.dispatchEvent(new CustomEvent(Uu.FilterConnect,{detail:e}))}dispatchStorePeerConnect(e){this.events.dispatchEvent(new CustomEvent(Uu.StoreConnect,{detail:e}))}dispatchFilterPeerDisconnect(e){this.events.dispatchEvent(new CustomEvent(Uu.FilterDisconnect,{detail:e}))}matchProtocolToCodec(e){return{[zn.Filter]:$g.SUBSCRIBE,[zn.LightPush]:w1,[zn.Store]:V_,[zn.Relay]:""}[e]}}class yvt{ttlMs;cleanupIntervalId=null;entryTimestamps=new Map;constructor(e,n=5e3){this.ttlMs=e,this.startCleanupInterval(n)}dispose(){this.cleanupIntervalId!==null&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.entryTimestamps.clear()}add(e){return this.entryTimestamps.set(e,Date.now()),this}has(e){return this.entryTimestamps.has(e)}startCleanupInterval(e){this.cleanupIntervalId=setInterval(()=>{this.removeExpiredEntries()},e)}removeExpiredEntries(){const e=Date.now();for(const[n,r]of this.entryTimestamps.entries())e-r>this.ttlMs&&this.entryTimestamps.delete(n)}}const yn=new rr("sdk:filter-subscription");class wvt{pubsubTopic;protocol;peerManager;config;isStarted=!1;inProgress=!1;peers=new Map;peerFailures=new Map;receivedMessages=new yvt(6e4);callbacks=new Map;messageEmitter=new Oo;toSubscribeContentTopics=new Set;toUnsubscribeContentTopics=new Set;subscribeIntervalId=null;keepAliveIntervalId=null;get contentTopics(){const e=Array.from(this.callbacks.keys()).map(r=>r.contentTopic),n=new Set(e).values();return Array.from(n)}constructor(e){this.config=e.config,this.pubsubTopic=e.pubsubTopic,this.protocol=e.protocol,this.peerManager=e.peerManager,this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}start(){if(yn.info(`Starting subscription for pubsubTopic: ${this.pubsubTopic}`),this.isStarted||this.inProgress){yn.info("Subscription already started or in progress, skipping start");return}this.inProgress=!0,this.attemptSubscribe({useNewContentTopics:!1}),this.setupSubscriptionInterval(),this.setupKeepAliveInterval(),this.setupEventListeners(),this.isStarted=!0,this.inProgress=!1,yn.info(`Subscription started for pubsubTopic: ${this.pubsubTopic}`)}stop(){if(yn.info(`Stopping subscription for pubsubTopic: ${this.pubsubTopic}`),!this.isStarted||this.inProgress){yn.info("Subscription not started or stop in progress, skipping stop");return}this.inProgress=!0,this.disposeEventListeners(),this.disposeIntervals(),this.disposePeers(),this.disposeHandlers(),this.receivedMessages.dispose(),this.inProgress=!1,this.isStarted=!1,yn.info(`Subscription stopped for pubsubTopic: ${this.pubsubTopic}`)}isEmpty(){return this.callbacks.size===0}async add(e,n){const r=Array.isArray(e)?e:[e];for(const s of r)this.addSingle(s,n);return this.toSubscribeContentTopics.size>0?await this.attemptSubscribe({useNewContentTopics:!0}):!0}async remove(e){const n=Array.isArray(e)?e:[e];for(const r of n)this.removeSingle(r);return this.toUnsubscribeContentTopics.size>0?await this.attemptUnsubscribe({useNewContentTopics:!0}):!0}invoke(e,n){if(this.isMessageReceived(e)){yn.info(`Skipping invoking callbacks for already received message: pubsubTopic:${this.pubsubTopic}, peerId:${n.toString()}, contentTopic:${e.contentTopic}`);return}yn.info(`Invoking message for contentTopic: ${e.contentTopic}`),this.messageEmitter.dispatchEvent(new CustomEvent(e.contentTopic,{detail:e}))}addSingle(e,n){yn.info(`Adding subscription for contentTopic: ${e.contentTopic}`);const r=!this.contentTopics.includes(e.contentTopic);if(r&&this.toSubscribeContentTopics.add(e.contentTopic),this.callbacks.has(e)){yn.warn(`Replacing callback associated associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`);const i=this.callbacks.get(e);this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,i)}const s=i=>{(async()=>{try{const o=await e.fromProtoObj(e.pubsubTopic,i.detail);n(o)}catch(o){yn.error("Error decoding message",o)}})()};this.callbacks.set(e,s),this.messageEmitter.addEventListener(e.contentTopic,s),yn.info(`Subscription added for contentTopic: ${e.contentTopic}, isNewContentTopic: ${r}`)}removeSingle(e){yn.info(`Removing subscription for contentTopic: ${e.contentTopic}`);const n=this.callbacks.get(e);n||yn.warn(`No callback associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`),this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,n);const r=!this.contentTopics.includes(e.contentTopic);r&&this.toUnsubscribeContentTopics.add(e.contentTopic),yn.info(`Subscription removed for contentTopic: ${e.contentTopic}, isCompletelyRemoved: ${r}`)}isMessageReceived(e){try{const n=k0t(this.pubsubTopic,e);if(this.receivedMessages.has(n))return!0;this.receivedMessages.add(n)}catch{}return!1}setupSubscriptionInterval(){yn.info("Setting up subscription interval with period 1000ms"),this.subscribeIntervalId=setInterval(()=>{(async()=>{this.toSubscribeContentTopics.size>0&&(yn.info(`Subscription interval: ${this.toSubscribeContentTopics.size} topics to subscribe`),await this.attemptSubscribe({useNewContentTopics:!0})),this.toUnsubscribeContentTopics.size>0&&(yn.info(`Subscription interval: ${this.toUnsubscribeContentTopics.size} topics to unsubscribe`),await this.attemptUnsubscribe({useNewContentTopics:!0}))})()},1e3)}setupKeepAliveInterval(){yn.info(`Setting up keep-alive interval with period ${this.config.keepAliveIntervalMs}ms`),this.keepAliveIntervalId=setInterval(()=>{(async()=>{yn.info(`Keep-alive interval running for ${this.peers.size} peers`);let n=await Promise.all(Array.from(this.peers.values()).map(async r=>{if((await this.protocol.ping(r)).success){yn.info(`Ping successful for peer: ${r.toString()}`),this.peerFailures.set(r.toString(),0);return}let i=this.peerFailures.get(r.toString())||0;if(i+=1,this.peerFailures.set(r.toString(),i),yn.warn(`Ping failed for peer: ${r.toString()}, failures: ${i}/${this.config.pingsBeforePeerRenewed}`),!(i!!r),await Promise.all(n.map(r=>(this.peers.delete(r?.toString()),this.peerFailures.delete(r?.toString()),this.requestUnsubscribe(r,this.contentTopics)))),n.length>0&&(yn.info(`Replacing ${n.length} failed peers`),await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}))})()},this.config.keepAliveIntervalMs)}setupEventListeners(){this.peerManager.events.addEventListener(Uu.FilterConnect,this.onPeerConnected),this.peerManager.events.addEventListener(Uu.FilterDisconnect,this.onPeerDisconnected)}disposeIntervals(){this.subscribeIntervalId&&clearInterval(this.subscribeIntervalId),this.keepAliveIntervalId&&clearInterval(this.keepAliveIntervalId)}disposeHandlers(){for(const[e,n]of this.callbacks.entries())this.messageEmitter.removeEventListener(e.contentTopic,n);this.callbacks.clear()}async disposePeers(){await this.attemptUnsubscribe({useNewContentTopics:!1}),this.peers.clear(),this.peerFailures=new Map}disposeEventListeners(){this.peerManager.events.removeEventListener(Uu.FilterConnect,this.onPeerConnected),this.peerManager.events.removeEventListener(Uu.FilterDisconnect,this.onPeerDisconnected)}async onPeerConnected(e){const n=e.detail?.toString();if(yn.info(`Peer connected: ${n}`),!await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)){yn.info(`Peer ${n} doesn't support pubsubTopic:${this.pubsubTopic}`);return}if(this.peers.has(n)){yn.info(`Peer ${n} already subscribed, skipping`);return}await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})}async onPeerDisconnected(e){const n=e.detail?.toString();if(yn.info(`Peer disconnected: ${n}`),!await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)){yn.info(`Peer ${n} doesn't support pubsubTopic:${this.pubsubTopic}`);return}if(!this.peers.has(n)){yn.info(`Disconnected peer ${n} not in use, ignoring`);return}yn.info(`Active peer ${n} disconnected, removing from peers list`),this.peers.delete(n),this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})}async attemptSubscribe(e){const{useNewContentTopics:n,useOnlyNewPeers:r=!1}=e,s=n?Array.from(this.toSubscribeContentTopics):this.contentTopics;if(yn.info(`Attempting to subscribe: useNewContentTopics=${n}, useOnlyNewPeers=${r}, contentTopics=${s.length}`),!s.length)return yn.warn("Requested content topics is an empty array, skipping"),!1;const i=new Set(this.peers.keys()),o=await this.peerManager.getPeers({protocol:zn.Filter,pubsubTopic:this.pubsubTopic});for(const u of o){if(this.peers.size>=this.config.numPeersToUse)break;this.peers.set(u.toString(),u)}const a=r?Array.from(this.peers.values()).filter(u=>!i.has(u.toString())):Array.from(this.peers.values());if(yn.info(`Subscribing with ${a.length} peers for ${s.length} content topics`),r&&a.length===0)return yn.warn("Requested to use only new peers, but no peers found, skipping"),!1;const c=await Promise.all(a.map(u=>this.requestSubscribe(u,s))),l=c.filter(u=>u).length;return yn.info(`Subscribe attempts completed: ${l}/${c.length} successful`),n&&(this.toSubscribeContentTopics=new Set),c.some(u=>u)}async requestSubscribe(e,n){if(yn.info(`requestSubscribe: pubsubTopic:${this.pubsubTopic} contentTopics:${n.join(",")}`),!n.length||!this.pubsubTopic)return yn.warn("requestSubscribe: no contentTopics or pubsubTopic provided, not sending subscribe request"),!1;const r=await this.protocol.subscribe(this.pubsubTopic,e,n);return r.failure?(yn.warn(`requestSubscribe: Failed to subscribe ${this.pubsubTopic} to ${e.toString()} with error:${r.failure.error} for contentTopics:${n}`),!1):(yn.info(`requestSubscribe: Subscribed ${this.pubsubTopic} to ${e.toString()} for contentTopics:${n}`),!0)}async attemptUnsubscribe(e){const{useNewContentTopics:n}=e,r=n?Array.from(this.toUnsubscribeContentTopics):this.contentTopics;if(yn.info(`Attempting to unsubscribe: useNewContentTopics=${n}, contentTopics=${r.length}`),!r.length)return yn.warn("Requested content topics is an empty array, skipping"),!1;const s=Array.from(this.peers.values()),i=await Promise.all(s.map(a=>this.requestUnsubscribe(a,n?r:void 0))),o=i.filter(a=>a).length;return yn.info(`Unsubscribe attempts completed: ${o}/${i.length} successful`),n&&(this.toUnsubscribeContentTopics=new Set),i.some(a=>a)}async requestUnsubscribe(e,n){const r=n?await this.protocol.unsubscribe(this.pubsubTopic,e,n):await this.protocol.unsubscribeAll(this.pubsubTopic,e);return r.failure?(yn.warn(`requestUnsubscribe: Failed to unsubscribe for pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} with error:${r.failure?.error} for contentTopics:${n}`),!1):(yn.info(`requestUnsubscribe: Unsubscribed pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} for contentTopics:${n}`),!0)}}const sg=new rr("sdk:filter");class bvt{protocol;peerManager;config;subscriptions=new Map;constructor(e){this.config={numPeersToUse:2,pingsBeforePeerRenewed:3,keepAliveIntervalMs:6e4,...e.options},this.peerManager=e.peerManager,this.protocol=new smt(this.onIncomingMessage.bind(this),e.libp2p)}get multicodec(){return this.protocol.multicodec}unsubscribeAll(){for(const e of this.subscriptions.values())e.stop();this.subscriptions.clear()}async subscribe(e,n){const r=Array.isArray(e)?e:[e];if(r.length===0)throw Error("Cannot subscribe with 0 decoders.");const s=r.map(l=>l.pubsubTopic),i=s[0],o=r.map(l=>l.contentTopic);sg.info(`Subscribing to contentTopics: ${o}, pubsubTopic: ${i}`),this.throwIfTopicNotSame(s);let a=this.subscriptions.get(i);a||(a=new wvt({pubsubTopic:i,protocol:this.protocol,config:this.config,peerManager:this.peerManager}),a.start());const c=await a.add(r,n);return this.subscriptions.set(i,a),sg.info(`Subscription ${c?"successful":"failed"} for content topic: ${o}`),c}async unsubscribe(e){const n=Array.isArray(e)?e:[e];if(n.length===0)throw Error("Cannot unsubscribe with 0 decoders.");const r=n.map(c=>c.pubsubTopic),s=r[0],i=n.map(c=>c.contentTopic);sg.info(`Unsubscribing from contentTopics: ${i}, pubsubTopic: ${s}`),this.throwIfTopicNotSame(r);const o=this.subscriptions.get(s);if(!o)return sg.warn("No subscriptions associated with the decoder."),!1;const a=await o.remove(n);return o.isEmpty()&&(sg.warn("Subscription has no decoders anymore, terminating it."),o.stop(),this.subscriptions.delete(s)),sg.info(`Unsubscribing ${a?"successful":"failed"} for content topic: ${i}`),a}async onIncomingMessage(e,n,r){sg.info(`Received message for pubsubTopic:${e}, contentTopic:${n.contentTopic}, peerId:${r.toString()}`);const s=this.subscriptions.get(e);if(!s){sg.error(`No subscription locally registered for topic ${e}`);return}s.invoke(n,r)}throwIfTopicNotSame(e){const n=e[0];if(!e.every(s=>s===n))throw Error(`Cannot subscribe to more than one pubsub topic at the same time, got pubsubTopics:${e}`)}}const ig=new rr("health-indicator");class vvt{libp2p;events;value=Vs.Unhealthy;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onPeerIdentify=this.onPeerIdentify.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}start(){ig.info("start: adding listeners to libp2p"),this.libp2p.addEventListener("peer:identify",this.onPeerIdentify),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnected),this.assessHealth()}stop(){ig.info("stop: removing listeners to libp2p"),this.libp2p.removeEventListener("peer:identify",this.onPeerIdentify),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnected)}toValue(){return this.value}async onPeerDisconnected(e){ig.info("onPeerDisconnected: received libp2p event"),await this.assessHealth()}async onPeerIdentify(e){ig.info("onPeerIdentify: received libp2p event"),await this.assessHealth()}async assessHealth(){const e=this.libp2p.getConnections();if(e.length===0){ig.info("assessHealth: no connections, setting to Unhealthy"),this.updateAndDispatchHealthEvent(Vs.Unhealthy);return}const n=await Promise.all(e.map(async o=>{try{return await this.libp2p.peerStore.get(o.remotePeer)}catch{return ig.warn(`assessHealth: failed to get peer ${o.remotePeer}, skipping`),null}})),r=n.filter(o=>o?.protocols.includes($g.SUBSCRIBE)).length,s=n.filter(o=>o?.protocols.includes(w1)).length;let i;r===0||s===0?i=Vs.Unhealthy:r>=2&&s>=2?i=Vs.SufficientlyHealthy:r===1&&s===1?i=Vs.MinimallyHealthy:(ig.error(`assessHealth: unexpected state, cannot identify health status of the node: Filter:${r}; LightPush:${s}`),i=this.value),ig.info(`assessHealth: node identified as ${i} Filter:${r}; LightPush:${s}`),this.updateAndDispatchHealthEvent(i)}updateAndDispatchHealthEvent(e){this.value!==e&&(this.value=e,this.events.dispatchEvent(new CustomEvent(cp.Health,{detail:this.value})))}}const xvt=t=>t===Sn.REMOTE_PEER_REJECTED||t===Sn.NO_RESPONSE||t===Sn.RLN_PROOF_GENERATION||t===Sn.NO_PEER_AVAILABLE,Evt=t=>new Promise((e,n)=>setTimeout(()=>n(new Error("Task timeout")),t)),Cvt=5,_vt=1e4,fb=new rr("sdk:retry-manager");let Svt=class{intervalID=null;retryIntervalMs;inProgress=0;queue=[];peerManager;constructor(e){this.peerManager=e.peerManager,this.retryIntervalMs=e.retryIntervalMs||1e3}start(){this.intervalID=setInterval(()=>{this.processQueue()},this.retryIntervalMs)}stop(){this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}push(e,n,r){this.queue.push({maxAttempts:n,callback:e,routingInfo:r})}processQueue(){if(this.queue.length!==0)for(;this.queue.length&&this.inProgressthis.taskExecutor(e),100)}async taskExecutor(e){if(e.maxAttempts<=0){fb.warn("scheduleTask: max attempts has reached, removing from queue");return}const n=(await this.peerManager.getPeers({protocol:zn.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}))[0];if(!n){fb.warn("scheduleTask: no peers, putting back to queue"),this.queue.push({...e,maxAttempts:e.maxAttempts-1});return}try{this.inProgress+=1;const r=await Promise.race([Evt(_vt),e.callback(n)]);if(r?.failure)throw Error(r.failure.error);if(fb.info("scheduleTask: executed successfully"),e.maxAttempts===0){fb.warn("scheduleTask: discarded a task due to limit of max attempts");return}this.queue.push({...e,maxAttempts:e.maxAttempts-1})}catch(r){const s=r;if(fb.error("scheduleTask: task execution failed with error:",s),xvt(s.message)&&await this.peerManager.renewPeer(n,{protocol:zn.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}),e.maxAttempts===0){fb.warn("scheduleTask: discarded a task due to limit of max attempts");return}this.queue.push({...e,maxAttempts:e.maxAttempts-1})}finally{this.inProgress-=1}}};const Avt=new rr("sdk:light-push"),Nye=3,Ivt={autoRetry:!0,retryIntervalMs:1e3,maxAttempts:Nye,numPeersToUse:1};class Tvt{config;retryManager;peerManager;protocol;constructor(e){this.config={...Ivt,...e.options||{}},this.peerManager=e.peerManager,this.protocol=new lmt(e.libp2p),this.retryManager=new Svt({peerManager:e.peerManager,retryIntervalMs:this.config.retryIntervalMs})}get multicodec(){return this.protocol.multicodec}start(){this.retryManager.start()}stop(){this.retryManager.stop()}async send(e,n,r={}){r={...this.config,...r};const{pubsubTopic:s}=e;Avt.info("send: attempting to send a message to pubsubTopic:",s);const i=await this.peerManager.getPeers({protocol:zn.LightPush,pubsubTopic:e.pubsubTopic}),o=i?.length>0?await Promise.all(i.map(c=>this.protocol.send(e,n,c).catch(l=>({success:null,failure:{error:Sn.GENERIC_FAIL}})))):[],a=o.length?{successes:o.filter(c=>c.success).map(c=>c.success),failures:o.filter(c=>c.failure).map(c=>c.failure)}:{successes:[],failures:[{error:Sn.NO_PEER_AVAILABLE}]};if(r.autoRetry&&a.successes.length===0){const c=l=>this.protocol.send(e,n,l);this.retryManager.push(c.bind(this),r.maxAttempts||Nye,e.routingInfo)}return a}}const Ec=new rr("store-sdk");class Nvt{options;libp2p;peerManager;protocol;constructor(e){this.options=e.options||{},this.peerManager=e.peerManager,this.libp2p=e.libp2p,this.protocol=new pmt(e.libp2p)}get multicodec(){return this.protocol.multicodec}async*queryGenerator(e,n){const{decodersAsMap:r,queryOptions:s}=this.buildQueryParams(e,n);for(const i of s){const o=n?.peerId??await this.getPeerToUse(i.pubsubTopic);if(!o)throw Ec.error("No peers available to query"),new Error("No peers available to query");Ec.info(`Querying store with options: ${JSON.stringify(i)}`);const a=this.protocol.queryPerPage(i,r,o);for await(const c of a)yield c}}async queryWithOrderedCallback(e,n,r){Ec.info("Querying store with ordered callback");for await(const s of this.queryGenerator(e,r))if(await this.processMessages(s,n))break}async queryWithPromiseCallback(e,n,r){Ec.info("Querying store with promise callback");let s=!1;for await(const i of this.queryGenerator(e,r)){const o=i.map(async a=>{s||(s=!!await n(a))});if(await Promise.all(o),s)break}}async processMessages(e,n){let r=!1;const i=(await Promise.all(e)).filter(eV);return await Promise.all(i.map(async o=>{o&&!r&&(r=!!await n(o))})),r}createCursor(e){return Xk(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(e.length===0)throw Ec.error("No decoders provided"),new Error("No decoders provided");const n=Array.from(new Set(e.map(o=>o.pubsubTopic)));if(n.length>1)throw Ec.error("API does not support querying multiple pubsub topics at once"),new Error("API does not support querying multiple pubsub topics at once");const r=n[0],s=new Map;e.forEach(o=>{if(s.has(o.contentTopic))throw Ec.error("API does not support different decoder per content topic"),new Error("API does not support different decoder per content topic");s.set(o.contentTopic,o)});const i=e.filter(o=>o.pubsubTopic===r).map(o=>o.contentTopic);if(i.length===0)throw Ec.error(`No decoders found for topic ${r}`),new Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:i,decodersAsMap:s}}async getPeerToUse(e){const n=await this.peerManager.getPeers({protocol:zn.Store,pubsubTopic:e});return this.options.peers?await this.getPeerFromConfigurationOrFirst(n,this.options.peers):n[0]}async getPeerFromConfigurationOrFirst(e,n){const r=n.map(er),s=[];for(const i of r){const o=e.find(a=>a.toString()===i.getPeerId()?.toString());if(o)return o;s.push(i)}for(;s.length;){const i=s.pop();if(!i)return;try{if(await this.libp2p.dial(i))return yf(i.getPeerId())}catch(o){Ec.warn(`Failed to dial peer from options.peers list for Store protocol. Peer:${i.getPeerId()}, error:${o}`)}}return Ec.warn(`Passed node to use for Store not found: ${n.toString()}. Attempting to use first available peers.`),e[0]}buildQueryParams(e,n){const r=n?.messageHashes&&n.messageHashes.length>0;let s,i,o;if(r)s=n.pubsubTopic||e[0]?.pubsubTopic||"",i=[],o=new Map,e.forEach(c=>{o.set(c.contentTopic,c)});else{const c=this.validateDecodersAndPubsubTopic(e);s=c.pubsubTopic,i=c.contentTopics,o=c.decodersAsMap}const a=[];if(n?.timeStart&&n?.timeEnd){let c=n.timeStart;const l=n.timeEnd;for(;l.getTime()-c.getTime()>this.protocol.maxTimeLimit;){const u=new Date(c.getTime()+this.protocol.maxTimeLimit);a.push([c,u]),c=u}a.length===0&&(Ec.info("Using single time range"),a.push([c,l]))}return a.length===0?(Ec.info("No sub time ranges"),{decodersAsMap:o,queryOptions:[{pubsubTopic:s,contentTopics:i,includeData:!0,paginationForward:!0,...n}]}):(Ec.info(`Building ${a.length} sub time ranges`),{decodersAsMap:o,queryOptions:a.map(([c,l])=>({pubsubTopic:s,contentTopics:i,includeData:!0,paginationForward:!0,...n,timeStart:c,timeEnd:l}))})}}const gv=new rr("wait-for-remote-peer");async function Pvt(t,e,n){e=e?.length?e:Dvt(t);const r=t.libp2p.getConnections();if(!t.isStarted())throw Error("Waku node is not started");for(const i of e)switch(i){case zn.Relay:if(!t.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");break;case zn.LightPush:if(!t.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");break;case zn.Store:if(!t.store)throw Error("Cannot wait for Store peer: protocol not mounted");break;case zn.Filter:if(!t.filter)throw Error("Cannot wait for Filter peer: protocol not mounted");break}const s=[kvt(t,e)];r.length>0&&!e.includes(zn.Relay)&&s.push(Rvt(t,e)),n?await $vt(Promise.any(s),n,"Timed out waiting for a remote peer."):await Promise.any(s)}async function kvt(t,e){const n=[];return t.relay&&e.includes(zn.Relay)&&n.push(t.relay.waitForPeers()),t.store&&e.includes(zn.Store)&&n.push(t9(V_,t.libp2p)),t.lightPush&&e.includes(zn.LightPush)&&n.push(t9(w1,t.libp2p)),t.filter&&e.includes(zn.Filter)&&n.push(t9($g.SUBSCRIBE,t.libp2p)),Promise.all(n)}async function t9(t,e){gv.info(`Waiting for ${t} peer.`),await new Promise(n=>{const r=async s=>{if(s.detail?.protocols?.includes(t)){const i=e.services.metadata;if(!i){e.removeEventListener("peer:identify",r),n();return}try{await i.confirmOrAttemptHandshake(s.detail.peerId),e.removeEventListener("peer:identify",r),n()}catch(o){o.code==="ERR_CONNECTION_BEING_CLOSED"&&gv.error("Connection closed. Some peers can be on different shard."),gv.error(`Error waiting for metadata: ${o}`)}}};e.addEventListener("peer:identify",r)})}async function Rvt(t,e){const n=t.libp2p.getPeers(),r=t.libp2p.services.metadata,s=Mvt(e);if(!n.length||!r){gv.info(`Skipping waitForMetadata due to missing connections:${n.length} or metadataService:${!!r}`);return}for(const i of n)try{const o=await t.libp2p.peerStore.get(i);if(o.protocols.some(c=>s.has(c))&&!(await r.confirmOrAttemptHandshake(i)).error&&(o.protocols.forEach(u=>{s.has(u)&&s.set(u,!0)}),Array.from(s.values()).every(u=>u)))return}catch(o){o.code==="ERR_CONNECTION_BEING_CLOSED"&&gv.error("Connection closed. Some peers can be on different shard."),gv.error(`Error while iterating through peers: ${o}`);continue}}const Ovt=(t,e)=>new Promise((n,r)=>setTimeout(()=>r(Error(e)),t));async function $vt(t,e,n){await Promise.race([t,Ovt(e,n)])}function Dvt(t){const e=[];return t.relay&&e.push(zn.Relay),t.filter&&e.push(zn.Filter),t.store&&e.push(zn.Store),t.lightPush&&e.push(zn.LightPush),e}function Mvt(t){const e=new Map,n={[zn.Filter]:$g.SUBSCRIBE,[zn.LightPush]:w1,[zn.Store]:V_};for(const r of t)n[r]&&e.set(n[r],!1);return e}const nm=new rr("waku");class Lvt{libp2p;relay;store;filter;lightPush;events=new Oo;networkConfig;_nodeStateLock=!1;_nodeStarted=!1;connectionManager;peerManager;healthIndicator;constructor(e,n,r,s){this.relay=s,this.libp2p=n,this.networkConfig=e.networkConfig||vme,r={filter:!1,lightpush:!1,store:!1,...r};const i=this.libp2p.peerId.toString();this.connectionManager=new fvt({libp2p:n,relay:this.relay,events:this.events,networkConfig:this.networkConfig,config:e?.connectionManager}),this.peerManager=new mvt({libp2p:n,config:{numPeersToUse:e.numPeersToUse},connectionManager:this.connectionManager}),this.healthIndicator=new vvt({libp2p:n,events:this.events}),r.store&&(this.store=new Nvt({libp2p:n,peerManager:this.peerManager,options:e?.store})),r.lightpush&&(this.lightPush=new Tvt({libp2p:n,peerManager:this.peerManager,options:e?.lightPush})),r.filter&&(this.filter=new bvt({libp2p:n,peerManager:this.peerManager,options:e.filter})),nm.info("Waku node created",i,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}get health(){return this.healthIndicator.toValue()}async dial(e,n){const r=n??[];typeof n>"u"&&(this.relay&&r.push(zn.Relay),this.store&&r.push(zn.Store),this.filter&&r.push(zn.Filter),this.lightPush&&r.push(zn.LightPush));const s=[];return r.includes(zn.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach(i=>s.push(i)):nm.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(zn.Store)&&(this.store?s.push(this.store.multicodec):nm.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(zn.LightPush)&&(this.lightPush?s.push(this.lightPush.multicodec):nm.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(zn.Filter)&&(this.filter?s.push(this.filter.multicodec):nm.error("Filter codec not included in dial codec: protocol not mounted locally")),nm.info(`Dialing to ${e?.toString()} with protocols ${r}`),await this.connectionManager.dial(e,s)}async hangUp(e){return nm.info(`Hanging up peer:${e?.toString()}.`),this.connectionManager.hangUp(e)}async start(){this._nodeStateLock||this.isStarted()||(this._nodeStateLock=!0,await this.libp2p.start(),this.connectionManager.start(),this.peerManager.start(),this.healthIndicator.start(),this.lightPush?.start(),this._nodeStateLock=!1,this._nodeStarted=!0)}async stop(){this._nodeStateLock||!this.isStarted()||(this._nodeStateLock=!0,this.lightPush?.stop(),this.healthIndicator.stop(),this.peerManager.stop(),this.connectionManager.stop(),await this.libp2p.stop(),this._nodeStateLock=!1,this._nodeStarted=!1)}async getConnectedPeers(){return this.connectionManager.getConnectedPeers()}async waitForPeers(e,n){return Pvt(this,e,n)}isStarted(){return this._nodeStarted&&this.libp2p.status==="started"}isConnected(){return this.connectionManager.isConnected()}createDecoder(e){const n=this.createRoutingInfo(e.contentTopic,e.shardId);return M0t(e.contentTopic,n)}createEncoder(e){const n=this.createRoutingInfo(e.contentTopic,e.shardId);return wme({contentTopic:e.contentTopic,ephemeral:e.ephemeral,routingInfo:n})}createRoutingInfo(e,n){return mme(this.networkConfig,{contentTopic:e,shardId:n})}}const Bvt=8,TV=1024*1024*4;let Uvt=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Pye=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Fvt=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},wne=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function kye(t){return t[Symbol.asyncIterator]!=null}function Rye(t,e){if(t.byteLength>e)throw new Pye("Message length too long")}const d8=t=>{const e=Vi(t),n=qc(e);return rf(t,n),d8.bytes=e,n};d8.bytes=0;function NV(t,e){e=e??{};const n=e.lengthEncoder??d8,r=e?.maxDataLength??TV;function*s(i){Rye(i,r);const o=n(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return kye(t)?async function*(){for await(const i of t)yield*s(i)}():function*(){for(const i of t)yield*s(i)}()}NV.single=(t,e)=>{e=e??{};const n=e.lengthEncoder??d8,r=e?.maxDataLength??TV;return Rye(t,r),new mn(n(t.byteLength),t)};var hm;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(hm||(hm={}));const PV=t=>{const e=N3(t);return PV.bytes=Vi(e),e};PV.bytes=0;function c4(t,e){const n=new mn;let r=hm.LENGTH,s=-1;const i=e?.lengthDecoder??PV,o=e?.maxLengthLength??Bvt,a=e?.maxDataLength??TV;function*c(){for(;n.byteLength>0;){if(r===hm.LENGTH)try{if(s=i(n),s<0)throw new Uvt("Invalid message length");if(s>a)throw new Pye("Message length too long");const l=i.bytes;n.consume(l),e?.onLength!=null&&e.onLength(s),r=hm.DATA}catch(l){if(l instanceof RangeError){if(n.byteLength>o)throw new Fvt("Message length length too long");break}throw l}if(r===hm.DATA){if(n.byteLength0)throw new wne("Unexpected end of input")}():function*(){for(const l of t)n.append(l),yield*c();if(n.byteLength>0)throw new wne("Unexpected end of input")}()}c4.fromReader=(t,e)=>{let n=1;const r=async function*(){for(;;)try{const{done:i,value:o}=await t.next(n);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{n=1}}();return c4(r,{...e??{},onLength:i=>{n=i}})};class jvt extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}function l4(t,e){const n=Cme();t.sink(n).catch(async o=>{await n.end(o)}),t.sink=async o=>{for await(const a of o)await n.push(a);await n.end()};let r=t.source;t.source[Symbol.iterator]!=null?r=t.source[Symbol.iterator]():t.source[Symbol.asyncIterator]!=null&&(r=t.source[Symbol.asyncIterator]());const s=new mn;return{read:async o=>{if(o?.signal?.throwIfAborted(),o?.bytes==null){const{done:c,value:l}=await Jo(r.next(),o?.signal);return c===!0?null:l}for(;s.byteLength{a?.signal?.throwIfAborted(),o instanceof Uint8Array?await n.push(o,a):await n.push(o.subarray(),a)},unwrap:()=>{if(s.byteLength>0){const o=t.source;t.source=async function*(){e?.yieldBytes===!1?yield s:yield*s,yield*o}()}return t}}}class zvt extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Wvt extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Vvt extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function S1(t,e={}){const n=l4(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Vi(e.maxDataLength));const r=e?.lengthDecoder??N3,s=e?.lengthEncoder??rf;return{read:async o=>{let a=-1;const c=new mn;for(;;){c.append(await n.read({...o,bytes:1}));try{a=r(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new zvt("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Vvt("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Wvt("message length too long");return n.read({...o,bytes:a})},write:async(o,a)=>{await n.write(new mn(s(o.byteLength),o),a)},writeV:async(o,a)=>{const c=new mn(...o.flatMap(l=>[s(l.byteLength),l]));await n.write(c,a)},unwrap:()=>n.unwrap()}}function bne(){const t=qs();let e=!1;return{sink:async n=>{if(e)throw new Error("already piped");e=!0,t.resolve(n)},source:async function*(){yield*await t.promise}()}}function Hvt(){const t=bne(),e=bne();return[{source:t.source,sink:e.sink},{source:e.source,sink:t.sink}]}const tS=65535,vne=tS-16,U3=!!globalThis.process?.env?.DUMP_SESSION_KEYS;/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Oye(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function iU(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function n9(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ra(t,...e){if(!Oye(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function xne(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function qvt(t,e){Ra(t);const n=e.outputLen;if(t.length{function n(r,...s){if(Ra(r),!Gvt)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=s[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?Ra(u):Ra(u,t.nonceLength)}const i=t.tagLength;i&&s[1]!==void 0&&Ra(s[1]);const o=e(r,...s),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Ra(d)}};let c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ra(u),a(o.encrypt.length,d),o.encrypt(u,d)},decrypt(u,d){if(Ra(u),i&&u.length>s&i),a=Number(n&i),c=4,l=0;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function Jvt(t,e,n){iU(n);const r=new Uint8Array(16),s=Kvt(r);return Cne(s,0,BigInt(e),n),Cne(s,8,BigInt(t),n),r}function e1t(t){return t.byteOffset%4===0}function aU(t){return Uint8Array.from(t)}const $ye=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),t1t=$ye("expand 16-byte k"),n1t=$ye("expand 32-byte k"),r1t=t0(t1t),s1t=t0(n1t);function pr(t,e){return t<>>32-e}function cU(t){return t.byteOffset%4===0}const nI=64,i1t=16,Dye=2**32-1,_ne=new Uint32Array;function o1t(t,e,n,r,s,i,o,a){const c=s.length,l=new Uint8Array(nI),u=t0(l),d=cU(s)&&cU(i),f=d?t0(s):_ne,p=d?t0(i):_ne;for(let m=0;m=Dye)throw new Error("arx: counter overflow");const y=Math.min(nI,c-m);if(d&&y===nI){const b=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let v=0,x;v{Ra(a),Ra(c),Ra(l);const f=l.length;if(u===void 0&&(u=new Uint8Array(f)),Ra(u),n9(d),d<0||d>=Dye)throw new Error("arx: counter overflow");if(u.lengtht[e++]&255|(t[e++]&255)<<8;class c1t{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=oU(e),Ra(e,32);const n=ki(e,0),r=ki(e,2),s=ki(e,4),i=ki(e,6),o=ki(e,8),a=ki(e,10),c=ki(e,12),l=ki(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|s<<6)&7939,this.r[3]=(s>>>7|i<<9)&8191,this.r[4]=(i>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=ki(e,16+2*u)}process(e,n,r=!1){const s=r?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],f=o[5],p=o[6],m=o[7],y=o[8],b=o[9],v=ki(e,n+0),x=ki(e,n+2),E=ki(e,n+4),A=ki(e,n+6),_=ki(e,n+8),k=ki(e,n+10),B=ki(e,n+12),W=ki(e,n+14);let S=i[0]+(v&8191),$=i[1]+((v>>>13|x<<3)&8191),R=i[2]+((x>>>10|E<<6)&8191),M=i[3]+((E>>>7|A<<9)&8191),j=i[4]+((A>>>4|_<<12)&8191),z=i[5]+(_>>>1&8191),N=i[6]+((_>>>14|k<<2)&8191),T=i[7]+((k>>>11|B<<5)&8191),U=i[8]+((B>>>8|W<<8)&8191),L=i[9]+(W>>>5|s),P=0,H=P+S*a+$*(5*b)+R*(5*y)+M*(5*m)+j*(5*p);P=H>>>13,H&=8191,H+=z*(5*f)+N*(5*d)+T*(5*u)+U*(5*l)+L*(5*c),P+=H>>>13,H&=8191;let Y=P+S*c+$*a+R*(5*b)+M*(5*y)+j*(5*m);P=Y>>>13,Y&=8191,Y+=z*(5*p)+N*(5*f)+T*(5*d)+U*(5*u)+L*(5*l),P+=Y>>>13,Y&=8191;let re=P+S*l+$*c+R*a+M*(5*b)+j*(5*y);P=re>>>13,re&=8191,re+=z*(5*m)+N*(5*p)+T*(5*f)+U*(5*d)+L*(5*u),P+=re>>>13,re&=8191;let de=P+S*u+$*l+R*c+M*a+j*(5*b);P=de>>>13,de&=8191,de+=z*(5*y)+N*(5*m)+T*(5*p)+U*(5*f)+L*(5*d),P+=de>>>13,de&=8191;let fe=P+S*d+$*u+R*l+M*c+j*a;P=fe>>>13,fe&=8191,fe+=z*(5*b)+N*(5*y)+T*(5*m)+U*(5*p)+L*(5*f),P+=fe>>>13,fe&=8191;let ve=P+S*f+$*d+R*u+M*l+j*c;P=ve>>>13,ve&=8191,ve+=z*a+N*(5*b)+T*(5*y)+U*(5*m)+L*(5*p),P+=ve>>>13,ve&=8191;let Ee=P+S*p+$*f+R*d+M*u+j*l;P=Ee>>>13,Ee&=8191,Ee+=z*c+N*a+T*(5*b)+U*(5*y)+L*(5*m),P+=Ee>>>13,Ee&=8191;let oe=P+S*m+$*p+R*f+M*d+j*u;P=oe>>>13,oe&=8191,oe+=z*l+N*c+T*a+U*(5*b)+L*(5*y),P+=oe>>>13,oe&=8191;let Oe=P+S*y+$*m+R*p+M*f+j*d;P=Oe>>>13,Oe&=8191,Oe+=z*u+N*l+T*c+U*a+L*(5*b),P+=Oe>>>13,Oe&=8191;let je=P+S*b+$*y+R*m+M*p+j*f;P=je>>>13,je&=8191,je+=z*d+N*u+T*l+U*c+L*a,P+=je>>>13,je&=8191,P=(P<<2)+P|0,P=P+H|0,H=P&8191,P=P>>>13,Y+=P,i[0]=H,i[1]=Y,i[2]=re,i[3]=de,i[4]=fe,i[5]=ve,i[6]=Ee,i[7]=oe,i[8]=Oe,i[9]=je}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(s^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+n[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+n[a]|0)+(o>>>16)|0,e[a]=o&65535;A1(r)}update(e){xne(this),e=oU(e),Ra(e);const{buffer:n,blockLen:r}=this,s=e.length;for(let i=0;i>>0,e[i++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}function l1t(t){const e=(r,s)=>t(s).update(oU(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const u1t=l1t(t=>new c1t(t));function d1t(t,e,n,r,s,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],f=e[2],p=e[3],m=e[4],y=e[5],b=e[6],v=e[7],x=s,E=n[0],A=n[1],_=n[2],k=o,B=a,W=c,S=l,$=u,R=d,M=f,j=p,z=m,N=y,T=b,U=v,L=x,P=E,H=A,Y=_;for(let de=0;de{t.update(e);const n=e.length%16;n&&t.update(h1t.subarray(n))},p1t=new Uint8Array(32);function Ane(t,e,n,r,s){const i=t(e,n,p1t),o=u1t.create(i);s&&Sne(o,s),Sne(o,r);const a=Jvt(r.length,s?s.length:0,!0);o.update(a);const c=o.digest();return A1(i,a),c}const g1t=t=>(e,n,r)=>({encrypt(i,o){const a=i.length;o=Ene(a+16,o,!1),o.set(i);const c=o.subarray(0,-16);t(e,n,c,c,1);const l=Ane(t,e,n,c,r);return o.set(l,a),A1(l),o},decrypt(i,o){o=Ene(i.length-16,o,!1);const a=i.subarray(0,-16),c=i.subarray(-16),l=Ane(t,e,n,a,r);if(!Xvt(c,l))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),t(e,n,o,o,1),A1(l),o}}),Ine=Qvt({blockSize:64,nonceLength:12,tagLength:16},g1t(f1t));function m1t(t,e,n){return OP(t),n===void 0&&(n=new Uint8Array(t.outputLen)),KS(t,qh(n),qh(e))}const r9=Uint8Array.from([0]),Tne=Uint8Array.of();function y1t(t,e,n,r=32){OP(t),u0(r);const s=t.outputLen;if(r>255*s)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/s);n===void 0&&(n=Tne);const o=new Uint8Array(i*s),a=KS.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;ut.generateX25519SharedKey(e.privateKey,n).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const u4=t=>{const e=qc(2);return e[0]=t>>8,e[1]=t,e};u4.bytes=2;const o6=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};o6.bytes=2;function x1t(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Mye(t,e){!e.enabled||!U3||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${hn(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${hn(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Lye(t,e){!e.enabled||!U3||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${hn(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${hn(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function E1t(t,e){!e.enabled||!U3||e(t?`REMOTE_STATIC_PUBLIC_KEY ${hn(t.subarray(),"hex")}`:"Missing remote static public key.")}function Bye(t,e){!e.enabled||!U3||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${hn(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Uye(t,e,n){!n.enabled||!U3||(n(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&hn(t.k,"hex")}`),n(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&hn(e.k,"hex")}`))}class FE extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=FE.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const C1t=0,_1t=4294967295,S1t="Cipherstate has reached maximum n, a new handshake must be performed";class A1t{n;bytes;view;constructor(e=C1t){this.n=e,this.bytes=Mt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>_1t)throw new Error(S1t)}}const mv=Mt(0);class rI{k;n;crypto;constructor(e,n=void 0,r=0){this.crypto=e,this.k=n,this.n=new A1t(r)}hasKey(){return!!this.k}encryptWithAd(e,n){if(!this.hasKey())return n;this.n.assertValue();const r=this.crypto.encrypt(n,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,n,r){if(!this.hasKey())return n;this.n.assertValue();const s=this.crypto.decrypt(n,this.n.getBytes(),e,this.k,r);return this.n.increment(),s}}class I1t{cs;ck;h;crypto;constructor(e,n){this.crypto=e;const r=Jt(n,"utf-8");this.h=N1t(e,r),this.ck=this.h,this.cs=new rI(e)}mixKey(e){const[n,r]=this.crypto.hkdf(this.ck,e);this.ck=n,this.cs=new rI(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new mn(this.h,e))}encryptAndHash(e){const n=this.cs.encryptWithAd(this.h,e);return this.mixHash(n),n}decryptAndHash(e){const n=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),n}split(){const[e,n]=this.crypto.hkdf(this.ck,mv);return[new rI(this.crypto,e),new rI(this.crypto,n)]}}class T1t{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:n,protocolName:r,prologue:s,initiator:i,s:o,e:a,rs:c,re:l}=e;this.crypto=n,this.ss=new I1t(n,r),this.ss.mixHash(s),this.initiator=i,this.s=o,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,n=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.webtransportCerthashes!=null)for(const i of n.webtransportCerthashes)r.uint32(10),r.bytes(i);if(n.streamMuxers!=null)for(const i of n.streamMuxers)r.uint32(18),r.string(i);s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={webtransportCerthashes:[],streamMuxers:[]},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{if(s.limits?.webtransportCerthashes!=null&&i.webtransportCerthashes.length===s.limits.webtransportCerthashes)throw new Gi('Decode error - map field "webtransportCerthashes" had too many elements');i.webtransportCerthashes.push(n.bytes());break}case 2:{if(s.limits?.streamMuxers!=null&&i.streamMuxers.length===s.limits.streamMuxers)throw new Gi('Decode error - map field "streamMuxers" had too many elements');i.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(d4||(d4={}));var f4;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.identityKey!=null&&n.identityKey.byteLength>0&&(r.uint32(10),r.bytes(n.identityKey)),n.identitySig!=null&&n.identitySig.byteLength>0&&(r.uint32(18),r.bytes(n.identitySig)),n.extensions!=null&&(r.uint32(34),d4.codec().encode(n.extensions,r)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={identityKey:Mt(0),identitySig:Mt(0)},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.identityKey=n.bytes();break}case 2:{i.identitySig=n.bytes();break}case 4:{i.extensions=d4.codec().decode(n,n.uint32(),{limits:s.limits?.extensions});break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(f4||(f4={}));async function jye(t,e,n){const r=await t.sign(Wye(e));return f4.encode({identityKey:Rh(t.publicKey),identitySig:r,extensions:n})}async function zye(t,e,n){try{const r=f4.decode(t),s=x0(r.identityKey);if(n?.equals(s)===!1)throw new Error(`Payload identity key ${s} does not match expected remote identity key ${n}`);if(!e)throw new Error("Remote static does not exist");const i=Wye(e);if(!await s.verify(i,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new _mt(r.message)}}function Wye(t){const e=Jt("noise-libp2p-static-key:");return t instanceof Uint8Array?Uy([e,t],e.length+t.length):(t.prepend(e),t)}async function P1t(t,e){const{log:n,connection:r,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=t,u=await jye(i,a.publicKey,l),d=new Fye({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:o,s:a});Mye(d.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(d.writeMessageA(mv),e),n.trace("Stage 0 - Initiator finished sending first message."),Lye(d.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=d.readMessageB(await r.read(e));n.trace("Stage 1 - Initiator received the message."),Bye(d.re,n),E1t(d.rs,n),n.trace("Initiator going to check remote's signature...");const p=await zye(f,d.rs,c);n.trace("All good with the signature!"),n.trace("Stage 2 - Initiator sending third handshake message."),await r.write(d.writeMessageC(u),e),n.trace("Stage 2 - Initiator sent message with signed payload.");const[m,y]=d.ss.split();return Uye(m,y,n),{payload:p,encrypt:b=>m.encryptWithAd(mv,b),decrypt:(b,v)=>y.decryptWithAd(mv,b,v)}}async function k1t(t,e){const{log:n,connection:r,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=t,u=await jye(i,a.publicKey,l),d=new Fye({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:o,s:a});Mye(d.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await r.read(e)),n.trace("Stage 0 - Responder received first message."),Bye(d.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(d.writeMessageB(u),e),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Lye(d.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const f=d.readMessageC(await r.read(e));n.trace("Stage 2 - Responder received the message, finished handshake.");const p=await zye(f,d.rs,c),[m,y]=d.ss.split();return Uye(m,y,n),{payload:p,encrypt:b=>y.encryptWithAd(mv,b),decrypt:(b,v)=>m.decryptWithAd(mv,b,v)}}const Nne=16;function R1t(t,e){return async function*(n){for await(const r of n)for(let s=0;sr.length&&(i=r.length);let o;r instanceof Uint8Array?o=t.encrypt(r.subarray(s,i)):o=t.encrypt(r.sublist(s,i)),e?.encryptedPackets.increment(),yield new mn(u4(o.byteLength),o)}}}function O1t(t,e){return async function*(n){for await(const r of n)for(let s=0;sr.length&&(i=r.length),i-Nnec4(o,{lengthDecoder:o6}),O1t(n,this.metrics),r),s}}function D1t(t={}){return e=>new $1t(e,t)}const M1t=qt("dns4"),L1t=qt("dns6"),B1t=qt("dnsaddr"),Wy=Ci(qt("dns"),B1t,M1t,L1t),f8=Ci(qt("ip4"),qt("ip6")),I1=Ci(Tn(f8,qt("tcp")),Tn(Wy,qt("tcp"))),h8=Tn(f8,qt("udp")),U1t=Tn(h8,qt("utp")),F1t=Tn(h8,qt("quic")),j1t=Tn(h8,qt("quic-v1")),lU=Ci(Tn(I1,qt("ws")),Tn(Wy,qt("ws"))),Pne=Ci(Tn(lU,qt("p2p")),lU),uU=Ci(Tn(I1,qt("wss")),Tn(Wy,qt("wss")),Tn(I1,qt("tls"),qt("ws")),Tn(Wy,qt("tls"),qt("ws"))),kne=Ci(Tn(uU,qt("p2p")),uU),dU=Ci(Tn(I1,qt("http")),Tn(f8,qt("http")),Tn(Wy,qt("http"))),fU=Ci(Tn(I1,qt("https")),Tn(f8,qt("https")),Tn(Wy,qt("https"))),Rne=Tn(h8,qt("webrtc-direct"),qt("certhash")),Vye=Ci(Tn(Rne,qt("p2p")),Rne),One=Tn(j1t,qt("webtransport"),qt("certhash"),qt("certhash")),Hye=Ci(Tn(One,qt("p2p")),One),qye=Ci(Tn(Pne,qt("p2p-webrtc-star"),qt("p2p")),Tn(kne,qt("p2p-webrtc-star"),qt("p2p")),Tn(Pne,qt("p2p-webrtc-star")),Tn(kne,qt("p2p-webrtc-star"))),Kye=Ci(Tn(dU,qt("p2p-webrtc-direct"),qt("p2p")),Tn(fU,qt("p2p-webrtc-direct"),qt("p2p")),Tn(dU,qt("p2p-webrtc-direct")),Tn(fU,qt("p2p-webrtc-direct"))),hU=Ci(lU,uU,dU,fU,qye,Kye,I1,U1t,F1t,Wy,Vye,Hye),Dg=Ci(Tn(hU,qt("p2p")),qye,Kye,Vye,Hye,qt("p2p")),$ne=Ci(Tn(Dg,qt("p2p-circuit"),Dg),Tn(Dg,qt("p2p-circuit")),Tn(qt("p2p-circuit"),Dg),Tn(hU,qt("p2p-circuit")),Tn(qt("p2p-circuit"),hU),qt("p2p-circuit")),Gye=()=>Ci(Tn($ne,Gye),$ne),A2=Gye(),z1t=Ci(Tn(A2,Dg,A2),Tn(Dg,A2),Tn(A2,Dg),A2,Dg);function Zye(t){function e(n){let r;try{r=er(n)}catch{return!1}const s=t(r.protoNames());return s===null?!1:s===!0||s===!1?s:s.length===0}return e}function Tn(...t){function e(n){if(n.length(r=typeof s=="function"?s().partialMatch(n):s.partialMatch(n),Array.isArray(r)&&(n=r),r===null)),r}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:Zye(e),partialMatch:e}}function Ci(...t){function e(r){let s=null;return t.some(i=>{const o=typeof i=="function"?i().partialMatch(r):i.partialMatch(r);return o!=null?(s=o,!0):!1}),s}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:Zye(e),partialMatch:e}}function qt(t){const e=t;function n(s){let i;try{i=er(s)}catch{return!1}const o=i.protoNames();return o.length===1&&o[0]===e}function r(s){return s.length===0?null:s[0]===e?s.slice(1):null}return{toString:function(){return e},matches:n,partialMatch:r}}const W1t="bootstrap",V1t=50,H1t=1e3;class q1t extends Oo{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,n={list:[]}){if(n.list==null||n.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=n.timeout??H1t,this.list=[];for(const r of n.list){if(!z1t.matches(r)){this.log.error("Invalid multiaddr");continue}const s=er(r),i=s.getPeerId();if(i==null){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const o={id:yf(i),multiaddrs:[s]};this.list.push(o)}this._init=n}[H_]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[lp]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error(e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??W1t]:{value:this._init.tagValue??V1t,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(n=>{this.log.error("could not dial bootstrap peer %p",e.id,n)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}}function K1t(t){return e=>new q1t(e,t)}var h4;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.publicKey!=null&&n.publicKey.byteLength>0&&(r.uint32(10),r.bytes(n.publicKey)),n.payloadType!=null&&n.payloadType.byteLength>0&&(r.uint32(18),r.bytes(n.payloadType)),n.payload!=null&&n.payload.byteLength>0&&(r.uint32(26),r.bytes(n.payload)),n.signature!=null&&n.signature.byteLength>0&&(r.uint32(42),r.bytes(n.signature)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={publicKey:Mt(0),payloadType:Mt(0),payload:Mt(0),signature:Mt(0)},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.publicKey=n.bytes();break}case 2:{i.payloadType=n.bytes();break}case 3:{i.payload=n.bytes();break}case 5:{i.signature=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(h4||(h4={}));class G1t extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class Oh{static createFromProtobuf=e=>{const n=h4.decode(e),r=x0(n.publicKey);return new Oh({publicKey:r,payloadType:n.payloadType,payload:n.payload,signature:n.signature})};static seal=async(e,n,r)=>{if(n==null)throw new Error("Missing private key");const s=e.domain,i=e.codec,o=e.marshal(),a=Dne(s,i,o),c=await n.sign(a.subarray(),r);return new Oh({publicKey:n.publicKey,payloadType:i,payload:o,signature:c})};static openAndCertify=async(e,n,r)=>{const s=Oh.createFromProtobuf(e);if(!await s.validate(n,r))throw new G1t("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:n,payloadType:r,payload:s,signature:i}=e;this.publicKey=n,this.payloadType=r,this.payload=s,this.signature=i}marshal(){return this.marshaled==null&&(this.marshaled=h4.encode({publicKey:Rh(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:As(this.marshal(),e.marshal())}async validate(e,n){const r=Dne(e,this.payloadType,this.payload);return this.publicKey.verify(r.subarray(),this.signature,n)}}const Dne=(t,e,n)=>{const r=Jt(t),s=rf(r.byteLength),i=rf(e.length),o=rf(n.length);return new mn(s,r,i,e,o,n)};function Z1t(t,e){const n=(r,s)=>r.toString().localeCompare(s.toString());return t.length!==e.length?!1:(e.sort(n),t.sort(n).every((r,s)=>e[s].equals(r)))}const Y1t="libp2p-peer-record",X1t=Uint8Array.from([3,1]);var p4;(function(t){(function(n){let r;n.codec=()=>(r==null&&(r=dn((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),o.lengthDelimited!==!1&&i.ldelim()},(s,i,o={})=>{const a={multiaddr:Mt(0)},c=i==null?s.len:s.pos+i;for(;s.pos>>3){case 1:{a.multiaddr=s.bytes();break}default:{s.skipType(l&7);break}}}return a})),r),n.encode=s=>un(s,n.codec()),n.decode=(s,i)=>ln(s,n.codec(),i)})(t.AddressInfo||(t.AddressInfo={}));let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(r.uint32(10),r.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(r.uint32(16),r.uint64(n.seq)),n.addresses!=null)for(const i of n.addresses)r.uint32(26),t.AddressInfo.codec().encode(i,r);s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={peerId:Mt(0),seq:0n,addresses:[]},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new Gi('Decode error - map field "addresses" had too many elements');i.addresses.push(t.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(p4||(p4={}));class Ol{static createFromProtobuf=e=>{const n=p4.decode(e),r=o8(Zk(n.peerId)),s=(n.addresses??[]).map(o=>er(o.multiaddr)),i=n.seq;return new Ol({peerId:r,multiaddrs:s,seqNumber:i})};static DOMAIN=Y1t;static CODEC=X1t;peerId;multiaddrs;seqNumber;domain=Ol.DOMAIN;codec=Ol.CODEC;marshaled;constructor(e){const{peerId:n,multiaddrs:r,seqNumber:s}=e;this.peerId=n,this.multiaddrs=r??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=p4.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof Ol)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Z1t(this.multiaddrs,e.multiaddrs))}}function pU(t,e){let n;const r=function(){const s=function(){n=void 0,t()};clearTimeout(n),n=setTimeout(s,e)};return r.start=()=>{},r.stop=()=>{clearTimeout(n)},r}function Q1t(t){return t[Symbol.asyncIterator]!=null}function Mne(t){if(Q1t(t))return(async()=>{for await(const e of t);})();for(const e of t);}const sI=globalThis.CustomEvent??Event;async function*J1t(t,e={}){let n=e.concurrency??1/0;n<1&&(n=1/0);const r=e.ordered??!1,s=new EventTarget,i=[];let o=qs(),a=qs(),c=!1,l,u=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(const m of t){if(i.length===n&&(o=qs(),await o.promise),u)break;const y={done:!1};i.push(y),m().then(b=>{y.done=!0,y.ok=!0,y.value=b,s.dispatchEvent(new sI("task-complete"))},b=>{y.done=!0,y.err=b,s.dispatchEvent(new sI("task-complete"))})}c=!0,s.dispatchEvent(new sI("task-complete"))}catch(m){l=m,s.dispatchEvent(new sI("task-complete"))}});function d(){return r?i[0]?.done:!!i.find(m=>m.done)}function*f(){for(;i.length>0&&i[0].done;){const m=i[0];if(i.shift(),m.ok)yield m.value;else throw u=!0,o.resolve(),m.err;o.resolve()}}function*p(){for(;d();)for(let m=0;m{const o=await n.read(i);return s.decode(o)},write:async(s,i,o)=>{await n.write(i.encode(s),o)},writeV:async(s,i,o)=>{await n.writeV(s.map(a=>i.encode(a)),o)},pb:s=>({read:async i=>r.read(s,i),write:async(i,o)=>r.write(i,s,o),writeV:async(i,o)=>r.writeV(i,s,o),unwrap:()=>r}),unwrap:()=>n.unwrap()};return r}const ext="0.1.0",txt="id",nxt="1.0.0",rxt=1024*8,sxt=32;var g4;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.protocolVersion!=null&&(r.uint32(42),r.string(n.protocolVersion)),n.agentVersion!=null&&(r.uint32(50),r.string(n.agentVersion)),n.publicKey!=null&&(r.uint32(10),r.bytes(n.publicKey)),n.listenAddrs!=null)for(const i of n.listenAddrs)r.uint32(18),r.bytes(i);if(n.observedAddr!=null&&(r.uint32(34),r.bytes(n.observedAddr)),n.protocols!=null)for(const i of n.protocols)r.uint32(26),r.string(i);n.signedPeerRecord!=null&&(r.uint32(66),r.bytes(n.signedPeerRecord)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={listenAddrs:[],protocols:[]},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 5:{i.protocolVersion=n.string();break}case 6:{i.agentVersion=n.string();break}case 1:{i.publicKey=n.bytes();break}case 2:{if(s.limits?.listenAddrs!=null&&i.listenAddrs.length===s.limits.listenAddrs)throw new Gi('Decode error - map field "listenAddrs" had too many elements');i.listenAddrs.push(n.bytes());break}case 4:{i.observedAddr=n.bytes();break}case 3:{if(s.limits?.protocols!=null&&i.protocols.length===s.limits.protocols)throw new Gi('Decode error - map field "protocols" had too many elements');i.protocols.push(n.string());break}case 8:{i.signedPeerRecord=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(g4||(g4={}));const lh={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:rxt,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:sxt};function ixt(t){if(t!=null&&t.length>0)try{return er(t)}catch{}}function oxt(t,e){return e??t.userAgent}async function axt(t,e,n,r,s){if(n("received identify from %p",r.remotePeer),s==null)throw new qd("message was null or undefined");const i={};if(s.listenAddrs.length>0&&(i.addresses=s.listenAddrs.map(c=>({isCertified:!1,multiaddr:er(c)}))),s.protocols.length>0&&(i.protocols=s.protocols),s.publicKey!=null){const c=x0(s.publicKey);if(!X_(c).equals(r.remotePeer))throw new qd("public key did not match remote PeerId");i.publicKey=c}let o;if(s.signedPeerRecord!=null){n.trace("received signedPeerRecord from %p",r.remotePeer);let c=s.signedPeerRecord;const l=await Oh.openAndCertify(c,Ol.DOMAIN);let u=Ol.createFromProtobuf(l.payload);const d=L3(l.publicKey.toCID());if(!u.peerId.equals(d))throw new qd("signing key does not match PeerId in the PeerRecord");if(!r.remotePeer.equals(u.peerId))throw new qd("signing key does not match remote PeerId");let f;try{f=await t.get(u.peerId)}catch(p){if(p.name!=="NotFoundError")throw p}if(f!=null&&(i.metadata=f.metadata,f.peerRecordEnvelope!=null)){const p=Oh.createFromProtobuf(f.peerRecordEnvelope),m=Ol.createFromProtobuf(p.payload);m.seqNumber>=u.seqNumber&&(n("sequence number was lower or equal to existing sequence number - stored: %d received: %d",m.seqNumber,u.seqNumber),u=m,c=f.peerRecordEnvelope)}i.peerRecordEnvelope=c,i.addresses=u.multiaddrs.map(p=>({isCertified:!0,multiaddr:p})),o={seq:u.seqNumber,addresses:u.multiaddrs}}else n("%p did not send a signed peer record",r.remotePeer);if(n.trace("patching %p with",r.remotePeer,i),await t.patch(r.remotePeer,i),s.agentVersion!=null||s.protocolVersion!=null){const c={};s.agentVersion!=null&&(c.AgentVersion=Jt(s.agentVersion)),s.protocolVersion!=null&&(c.ProtocolVersion=Jt(s.protocolVersion)),n.trace("merging %p metadata",r.remotePeer,c),await t.merge(r.remotePeer,{metadata:c})}const a={peerId:r.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map(c=>er(c)),observedAddr:s.observedAddr==null?void 0:er(s.observedAddr),protocols:s.protocols,signedPeerRecord:o,connection:r};return e.safeDispatchEvent("peer:identify",{detail:a}),a}class cxt{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,n){this.protocol=n.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=n.log,this.timeout=n.timeout??lh.timeout,this.maxInboundStreams=n.maxInboundStreams??lh.maxInboundStreams,this.maxOutboundStreams=n.maxOutboundStreams??lh.maxOutboundStreams,this.maxMessageSize=n.maxMessageSize??lh.maxMessageSize,this.maxObservedAddresses=n.maxObservedAddresses??lh.maxObservedAddresses,this.runOnLimitedConnection=n.runOnLimitedConnection??lh.runOnLimitedConnection,this.host={protocolVersion:`${n.protocolPrefix??lh.protocolPrefix}/${ext}`,agentVersion:oxt(e.nodeInfo,n.agentVersion)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:Jt(this.host.agentVersion),ProtocolVersion:Jt(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,e=>{this.handleProtocol(e).catch(n=>{this.log.error(n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}function lxt(t){try{for(const{code:e,value:n}of t.getComponents())if(n!=null&&e===Zu)return Jbt("2000::/3",n)}catch{}return!1}var Yye;(function(){var t,e,n,r,s,i,o,a;a=function(c){var l,u,d,f;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,d=(c&65280)>>>8,f=c&255,[l,u,d,f].join(".")},o=function(c){var l,u,d,f,p,m;for(l=[],d=f=0;f<=3&&c.length!==0;d=++f){if(d>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=e(c),p=m[0],u=m[1],c=c.substring(u),l.push(p)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},n=function(c){return c.charCodeAt(0)},r=n("0"),i=n("a"),s=n("A"),e=function(c){var l,u,d,f,p;for(f=0,l=10,u="9",d=0,c.length>1&&c[d]==="0"&&(c[d+1]==="x"||c[d+1]==="X"?(d+=2,l=16):"0"<=c[d+1]&&c[d+1]<="9"&&(d++,l=8,u="7")),p=d;d>>0;else if(l===16)if("a"<=c[d]&&c[d]<="f")f=f*l+(10+n(c[d])-i)>>>0;else if("A"<=c[d]&&c[d]<="F")f=f*l+(10+n(c[d])-s)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");d++}if(d===p)throw new Error("empty octet");return[f,d]},t=function(){function c(l,u){var d,f,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=o(u)}catch{throw new Error("Invalid mask: "+u)}for(d=f=32;f>=0;d=--f)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(l)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(o(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,d,f;for(f=o(this.first),d=o(this.last),u=0;f<=d;)l(a(f),f,u),u++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Yye=t}).call(kr);const uxt=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],dxt=uxt.map(t=>new Yye(t));function kV(t){for(const e of dxt)if(e.contains(t))return!0;return!1}function fxt(t){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(t)}function hxt(t){const e=t.split(":");if(e.length<2)return!1;const n=e[e.length-1].padStart(4,"0"),r=e[e.length-2].padStart(4,"0"),s=`${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}.${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}`;return kV(s)}function pxt(t){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)}function gxt(t){const e=t.split(":"),n=e[e.length-1];return kV(n)}function mxt(t){return/^::$/.test(t)||/^::1$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}function p8(t){if(zy(t))return kV(t);if(fxt(t))return hxt(t);if(pxt(t))return gxt(t);if(SV(t))return mxt(t)}function Xye(t){try{for(const{code:e}of t.getComponents())if(e!==xx)return e===_1||e===Zu}catch{}return!1}function nS(t){try{if(!Xye(t))return!1;const[[,e]]=t.stringTuples();return e==null?!1:p8(e)??!1}catch{}return!0}const yxt=t=>t.toString().split("/").slice(1),F3=t=>({match:e=>e.length<1?!1:t(e[0])?e.slice(1):!1,pattern:"fn"}),Kn=t=>({match:e=>F3(n=>n===t).match(e),pattern:t}),vw=()=>({match:t=>F3(e=>typeof e=="string").match(t),pattern:"{string}"}),rS=()=>({match:t=>F3(e=>!isNaN(parseInt(e))).match(t),pattern:"{number}"}),Dr=()=>({match:t=>{if(t.length<2||t[0]!=="p2p"&&t[0]!=="ipfs")return!1;if(t[1].startsWith("Q")||t[1].startsWith("1"))try{ps.decode(`z${t[1]}`)}catch{return!1}else return!1;return t.slice(2)},pattern:"/p2p/{peerid}"}),m4=()=>({match:t=>{if(t.length<2||t[0]!=="certhash")return!1;try{YW.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),Sr=t=>({match:e=>{const n=t.match(e);return n===!1?e:n},pattern:`optional(${t.pattern})`}),$o=(...t)=>({match:e=>{let n;for(const r of t){const s=r.match(e);s!==!1&&(n==null||s.lengthe.pattern).join(", ")})`}),tr=(...t)=>({match:e=>{for(const n of t){const r=n.match(e);if(r===!1)return!1;e=r}return e},pattern:`and(${t.map(e=>e.pattern).join(", ")})`});function Uo(...t){function e(s){let i=yxt(s);for(const o of t){const a=o.match(i);if(a===!1)return!1;i=a}return i}function n(s){return e(s)!==!1}function r(s){const i=e(s);return i===!1?!1:i.length===0}return{matchers:t,matches:n,exactMatch:r}}const wxt=Dr(),bxt=Uo(wxt),g8=tr(Kn("dns4"),vw()),m8=tr(Kn("dns6"),vw()),y8=tr(Kn("dnsaddr"),vw()),RV=tr(Kn("dns"),vw());Uo(g8,Sr(Dr()));Uo(m8,Sr(Dr()));Uo(y8,Sr(Dr()));Uo($o(RV,y8,g8,m8),Sr(Dr()));const Qye=tr(Kn("ip4"),F3(zy)),Jye=tr(Kn("ip6"),F3(SV)),ewe=$o(Qye,Jye),$h=$o(ewe,RV,g8,m8,y8),vxt=Uo($o(ewe,tr($o(RV,y8,g8,m8),Sr(Dr())))),Bne=Uo(Qye),Une=Uo(Jye),OV=tr($h,Kn("tcp"),rS()),w8=tr($h,Kn("udp"),rS()),y4=Uo(tr(OV,Sr(Dr()))),twe=tr(w8,Kn("quic"),Sr(Dr())),b8=tr(w8,Kn("quic-v1"),Sr(Dr())),xxt=$o(twe,b8),Ext=Uo(b8),gU=$o($h,OV,w8,twe,b8),nwe=$o(tr(gU,Kn("ws"),Sr(Dr()))),sS=Uo(nwe),rwe=$o(tr(gU,Kn("wss"),Sr(Dr())),tr(gU,Kn("tls"),Sr(tr(Kn("sni"),vw())),Kn("ws"),Sr(Dr()))),iS=Uo(rwe),swe=tr(w8,Kn("webrtc-direct"),Sr(m4()),Sr(m4()),Sr(Dr())),Fne=Uo(swe),iwe=tr(b8,Kn("webtransport"),Sr(m4()),Sr(m4()),Sr(Dr())),jne=Uo(iwe),mU=$o(nwe,rwe,tr(OV,Sr(Dr())),tr(xxt,Sr(Dr())),tr($h,Sr(Dr())),swe,iwe,Dr()),Cxt=tr(mU,Kn("p2p-circuit"),Dr()),yU=Uo(Cxt),_xt=$o(tr(mU,Kn("p2p-circuit"),Kn("webrtc"),Sr(Dr())),tr(mU,Kn("webrtc"),Sr(Dr())),tr(Kn("webrtc"),Sr(Dr()))),zne=Uo(_xt);$o(tr($h,Kn("tcp"),rS(),Kn("http"),Sr(Dr())),tr($h,Kn("http"),Sr(Dr())));$o(tr($h,Kn("tcp"),$o(tr(Kn("443"),Kn("http")),tr(rS(),Kn("https")),tr(rS(),Kn("tls"),Kn("http"))),Sr(Dr())),tr($h,Kn("tls"),Kn("http"),Sr(Dr())),tr($h,Kn("https"),Sr(Dr())));$o(tr(Kn("memory"),vw(),Sr(Dr())));$o(tr(Kn("unix"),vw(),Sr(Dr())));class Sxt extends cxt{constructor(e,n={}){super(e,{...n,protocol:`/${n.protocolPrefix??lh.protocolPrefix}/${txt}/${nxt}`,log:e.logger.forComponent("libp2p:identify")}),(n.runOnConnectionOpen??lh.runOnConnectionOpen)&&e.events.addEventListener("connection:open",r=>{const s=r.detail;this.identify(s).catch(i=>{i.name!==cV.name&&this.log.error("error during identify trigged by connection:open",i)})})}[lp]=["@libp2p/identify"];async _identify(e,n={}){let r;if(n.signal==null){const s=AbortSignal.timeout(this.timeout);n={...n,signal:s}}try{r=await e.newStream(this.protocol,{...n,runOnLimitedConnection:this.runOnLimitedConnection});const i=await Lne(r,{maxDataLength:this.maxMessageSize}).pb(g4).read(n);return await r.close(n),i}catch(s){throw r?.abort(s),s}}async identify(e,n={}){const r=await this._identify(e,n),{publicKey:s,protocols:i,observedAddr:o}=r;if(s==null)throw new qd("public key was missing from identify message");const a=x0(s),c=L3(a.toCID());if(!e.remotePeer.equals(c))throw new qd("identified peer does not match the expected peer");if(this.peerId.equals(c))throw new qd("identified peer is our own peer id?");return this.maybeAddObservedAddress(o),this.log("identify completed for peer %p and protocols %o",c,i),axt(this.peerStore,this.events,this.log,e,r)}maybeAddObservedAddress(e){const n=ixt(e);if(n==null)return;if(this.log.trace("our observed address was %a",n),nS(n)){this.log.trace("our observed address was private");return}const r=n.getComponents();if((r[0].code===Zu||r[0].code===xx&&r[1].code===Zu)&&!lxt(n)){this.log.trace("our observed address was IPv6 but not a global unicast address");return}y4.exactMatch(n)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(n))}async handleProtocol(e){const{connection:n,stream:r}=e,s=AbortSignal.timeout(this.timeout);try{const i=await this.peerStore.get(this.peerId),o=this.addressManager.getAddresses().map(u=>u.decapsulateCode(IV("p2p").code));let a=i.peerRecordEnvelope;if(o.length>0&&a==null){const u=new Ol({peerId:this.peerId,multiaddrs:o});a=(await Oh.seal(u,this.privateKey)).marshal().subarray()}let c=n.remoteAddr.bytes;vxt.matches(n.remoteAddr)||(c=void 0),await Lne(r).pb(g4).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Rh(this.privateKey.publicKey),listenAddrs:o.map(u=>u.bytes),signedPeerRecord:a,observedAddr:c,protocols:i.protocols},{signal:s}),await r.close({signal:s})}catch(i){this.log.error("could not respond to identify request",i),r.abort(i)}}}function Axt(t={}){return e=>new Sxt(e,t)}function Ixt(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function Txt(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}function owe(t,e){const n=Ixt(t).return?.();Txt(n)&&n.catch(r=>{e.error("could not cause iterator to return",r)})}const Wne=()=>{const t=new Error("Delay aborted");return t.name="AbortError",t},Nxt=new WeakMap;function Pxt({clearTimeout:t,setTimeout:e}={}){return(n,{value:r,signal:s}={})=>{if(s?.aborted)return Promise.reject(Wne());let i,o,a;const c=t??clearTimeout,l=()=>{c(i),a(Wne())},u=()=>{s&&s.removeEventListener("abort",l)},d=new Promise((f,p)=>{o=()=>{u(),f(r)},a=p,i=(e??setTimeout)(o,n)});return s&&s.addEventListener("abort",l,{once:!0}),Nxt.set(d,()=>{c(i),i=null,o()}),d}}const kxt=Pxt();class Rxt extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",n){super(e),this.name="RateLimitError",this.remainingPoints=n.remainingPoints,this.msBeforeNext=n.msBeforeNext,this.consumedPoints=n.consumedPoints,this.isFirstInDuration=n.isFirstInDuration}}let Oxt=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};class awe{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new $xt}async consume(e,n=1,r={}){const s=this.getKey(e),i=this._getKeySecDuration(r);let o=this.memoryStorage.incrby(s,n,i);if(o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.consumedPoints>this.points)throw this.blockDuration>0&&o.consumedPoints<=this.points+n&&(o=this.memoryStorage.set(s,o.consumedPoints,this.blockDuration)),new Rxt("Rate limit exceeded",o);if(this.execEvenly&&o.msBeforeNext>0&&!o.isFirstInDuration){let a=Math.ceil(o.msBeforeNext/(o.remainingPoints+2));a=0?r:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),n,r),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:n,isFirstInDuration:!1}}get(e){const n=this.memoryStorage.get(this.getKey(e));return n!=null&&(n.remainingPoints=Math.max(this.points-n.consumedPoints,0)),n}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class $xt{storage;constructor(){this.storage=new Map}incrby(e,n,r){const s=this.storage.get(e);if(s!=null){const i=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||i>0?(s.value+=n,{remainingPoints:0,msBeforeNext:i,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,n,r)}return this.set(e,n,r)}set(e,n,r){const s=r*1e3,i=this.storage.get(e);i!=null&&clearTimeout(i.timeoutId);const o={value:n,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,o),s>0&&(o.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),o.timeoutId.unref!=null&&o.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:o.value,isFirstInDuration:!0}}get(e){const n=this.storage.get(e);if(n!=null)return{remainingPoints:0,msBeforeNext:n.expiresAt!=null?n.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:n.value,isFirstInDuration:!1}}delete(e){const n=this.storage.get(e);return n!=null?(n.timeoutId!=null&&clearTimeout(n.timeoutId),this.storage.delete(e),!0):!1}}var yr;(function(t){t[t.NEW_STREAM=0]="NEW_STREAM",t[t.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",t[t.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",t[t.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",t[t.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",t[t.RESET_RECEIVER=5]="RESET_RECEIVER",t[t.RESET_INITIATOR=6]="RESET_INITIATOR"})(yr||(yr={}));const $V=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Vne=Object.freeze({NEW_STREAM:yr.NEW_STREAM,MESSAGE:yr.MESSAGE_INITIATOR,CLOSE:yr.CLOSE_INITIATOR,RESET:yr.RESET_INITIATOR}),Dxt=Object.freeze({MESSAGE:yr.MESSAGE_RECEIVER,CLOSE:yr.CLOSE_RECEIVER,RESET:yr.RESET_RECEIVER}),cwe=1<<20,Mxt=4<<20;class Lxt{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=cwe,n=Mxt){this._buffer=new mn,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=n}write(e){if(e==null||e.length===0)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new qd("Unprocessed message queue size too large!");const n=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(l){if(l.name==="InvalidMessageError")throw l;break}const{id:r,type:s,length:i,offset:o}=this._headerInfo;if(this._buffer.length-othis._maxMessageSize)throw new qd("Message size too large");return{id:n>>3,type:o,offset:r+i,length:s}}}const Bxt=128,Hne=127;function qne(t,e=0){let n=0,r=0,s=e,i;const o=t.length;do{if(s>=o||r>49)throw e=0,new RangeError("Could not decode varint");i=t.get(s++),n+=r<28?(i&Hne)<=Bxt);return e=s-e,{value:n,offset:e}}const s9=10*1024;class Uxt{_pool;_poolOffset;constructor(){this._pool=qc(s9),this._poolOffset=0}write(e,n){const r=this._pool;let s=this._poolOffset;rf(e.id<<3|e.type,r,s),s+=Vi(e.id<<3|e.type),(e.type===yr.NEW_STREAM||e.type===yr.MESSAGE_INITIATOR||e.type===yr.MESSAGE_RECEIVER)&&e.data!=null?(rf(e.data.length,r,s),s+=Vi(e.data.length)):(rf(0,r,s),s+=Vi(0));const i=r.subarray(this._poolOffset,s);s9-s<100?(this._pool=qc(s9),this._poolOffset=0):this._poolOffset=s,n.append(i),(e.type===yr.NEW_STREAM||e.type===yr.MESSAGE_INITIATOR||e.type===yr.MESSAGE_RECEIVER)&&e.data!=null&&n.append(e.data)}}const Fxt=new Uxt;async function*jxt(t){for await(const e of t){const n=new mn;Fxt.write(e,n),yield n}}class zxt extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}}const Wxt=5e3;function i9(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class Vxt{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=qs(),this.closed=qs(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??Wxt,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=R3({onEnd:n=>{n!=null?this.log.trace("source ended with error",n):this.log.trace("source ended"),this.onSourceEnd(n)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new Pmt(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const n={signal:this.sinkController.signal};if(this.direction==="outbound"){const s=this.sendNewStream(n);i9(s)&&await s}const r=()=>{owe(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let s of e){s=s instanceof Uint8Array?new mn(s):s;const i=this.sendData(s,n);i9(i)&&(this.sendingData=qs(),await i,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(n){throw this.log.trace("sink ended with error, calling abort with error",n),this.abort(n),n}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await Jo(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const n=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),n==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await Jo(this.sink([]),e.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Jo(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Jo(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");const n=this.sendReset();i9(n)&&n.catch(r=>{this.log.error("error sending reset message",r)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;const e=new Nmt("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class Hxt extends Vxt{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types=e.direction==="outbound"?Vne:Dxt,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:Vne.NEW_STREAM,data:new mn(Jt(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const n=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,n)}),e.consume(n)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function qxt(t){const{id:e,name:n,send:r,onEnd:s,type:i="initiator",maxMsgSize:o=cwe}=t;return new Hxt({id:i==="initiator"?`i${e}`:`r${e}`,streamId:e,name:`${n??e}`,direction:i==="initiator"?"outbound":"inbound",maxDataSize:o,onEnd:s,send:r,log:t.logger.forComponent(`libp2p:mplex:stream:${i}:${e}`)})}const Kxt=1024,Gxt=1024,Zxt=1024*1024*4,Yxt=5,Xxt=500;function Kne(t){const e={...t,type:`${$V[t.type]} (${t.type})`};return t.type===yr.NEW_STREAM&&(e.data=hn(t.data instanceof Uint8Array?t.data:t.data.subarray())),(t.type===yr.MESSAGE_INITIATOR||t.type===yr.MESSAGE_RECEIVER)&&(e.data=hn(t.data instanceof Uint8Array?t.data:t.data.subarray(),"base16")),e}class Qxt{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,n){n=n??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=n,this.closeTimeout=n.closeTimeout??Xxt,this.sink=this._createSink(),this._source=R3({objectMode:!0,onEnd:()=>{for(const r of this._streams.initiators.values())r.destroy();for(const r of this._streams.receivers.values())r.destroy()}}),this.source=Tl(this._source,r=>jxt(r)),this.closeController=new AbortController,this.rateLimiter=new awe({points:n.disconnectThreshold??Yxt,duration:1})}get streams(){const e=[];for(const n of this._streams.initiators.values())e.push(n);for(const n of this._streams.receivers.values())e.push(n);return e}newStream(e){if(this.closeController.signal.aborted)throw new Tmt("Muxer already closed");const n=this._streamId++;e=e==null?n.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:n,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const n=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async r=>r.close({signal:n}))),this._source.end(),await this._source.onEmpty({signal:n}),this.closeController.abort()}catch(r){this.abort(r)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach(n=>{n.abort(e)}),this.closeController.abort(e))}_newReceiverStream(e){const{id:n,name:r}=e,s=this._streams.receivers;return this._newStream({id:n,name:r,type:"receiver",registry:s})}_newStream(e){const{id:n,name:r,type:s,registry:i}=e;if(this.log("new %s stream %s",s,n),s==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??Gxt))throw new kme("Too many outbound streams open");if(i.has(n))throw new Error(`${s} stream ${n} already exists!`);const c=qxt({id:n,name:r,send:async l=>{this.log.enabled&&this.log.trace("%s stream %s send",s,n,Kne(l)),this._source.push(l)},type:s,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",s,n,c.protocol),i.delete(n),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return i.set(n,c),c}_createSink(){return async n=>{const r=()=>{owe(n,this.log)};this.closeController.signal.addEventListener("abort",r);try{const s=new Lxt(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const i of n)for(const o of s.write(i))await this._handleIncoming(o);this._source.end()}catch(s){this.log("error in sink",s),this._source.end(s)}finally{this.closeController.signal.removeEventListener("abort",r)}}}async _handleIncoming(e){const{id:n,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",Kne(e)),e.type===yr.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??Kxt)){this.log("too many inbound streams open"),this._source.push({id:n,type:yr.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}return}const a=this._newReceiverStream({id:n,name:hn(e.data instanceof Uint8Array?e.data:e.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}const i=((r&1)===1?this._streams.initiators:this._streams.receivers).get(n);if(i==null){this.log("missing stream %s for message type %s",n,$V[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}const o=this._init.maxStreamBufferSize??Zxt;try{switch(r){case yr.MESSAGE_INITIATOR:case yr.MESSAGE_RECEIVER:if(i.sourceReadableLength()>o)throw this._source.push({id:e.id,type:r===yr.MESSAGE_INITIATOR?yr.RESET_RECEIVER:yr.RESET_INITIATOR}),new zxt("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");i.sourcePush(e.data);break;case yr.CLOSE_INITIATOR:case yr.CLOSE_RECEIVER:i.remoteCloseWrite();break;case yr.RESET_INITIATOR:case yr.RESET_RECEIVER:i.reset();break;default:this.log("unknown message type %s",r)}}catch(a){this.log.error("error while processing message",a),i.abort(a)}}}class Jxt{protocol="/mplex/6.7.0";_init;components;constructor(e,n={}){this.components=e,this._init=n}[Symbol.toStringTag]="@libp2p/mplex";[lp]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new Qxt(this.components,{...e,...this._init})}}function e2t(t={}){return e=>new Jxt(e,t)}const o9=32,t2t="1.0.0",n2t="ping",r2t="ipfs",s2t=1e4,i2t=2,o2t=1;class a2t{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(e,n={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${n.protocolPrefix??r2t}/${n2t}/${t2t}`,this.timeout=n.timeout??s2t,this.maxInboundStreams=n.maxInboundStreams??i2t,this.maxOutboundStreams=n.maxOutboundStreams??o2t,this.runOnLimitedConnection=n.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[lp]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);const{stream:n}=e,r=Date.now(),s=l4(n);let i=!1;Promise.resolve().then(async()=>{for(;;){const o=AbortSignal.timeout(this.timeout);o.addEventListener("abort",()=>{n?.abort(new Nme("ping timeout"))});const a=await s.read({bytes:o9,signal:o});await s.write(a,{signal:o}),i=!0}}).catch(o=>{i&&o.name==="UnexpectedEOFError"&&n.readStatus!=="ready"||(this.log.error("incoming ping from %p failed with error - %e",e.connection.remotePeer,o),n?.abort(o))}).finally(()=>{const o=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,o);const a=AbortSignal.timeout(this.timeout);n.close({signal:a}).catch(c=>{this.log.error("error closing ping stream from %p - %e",e.connection.remotePeer,c),n?.abort(c)})})}async ping(e,n={}){this.log("pinging %p",e);const r=Date.now(),s=yV(o9),i=await this.components.connectionManager.openConnection(e,n);let o;if(n.signal==null){const a=AbortSignal.timeout(this.timeout);n={...n,signal:a}}try{o=await i.newStream(this.protocol,{...n,runOnLimitedConnection:this.runOnLimitedConnection});const a=l4(o),[,c]=await Promise.all([a.write(s,n),a.read({...n,bytes:o9})]),l=Date.now()-r;if(!As(s,c.subarray()))throw new Omt(`Received wrong ping ack after ${l}ms`);return this.log("ping %p complete in %dms",i.remotePeer,l),l}catch(a){throw this.log.error("error while pinging %p",i.remotePeer,a),o?.abort(a),a}finally{o!=null&&await o.close(n)}}}function c2t(t={}){return e=>new a2t(e,t)}const l2t=[o4,a8,l8,c8,B3];function Gne(t){return lwe("sni",t)?.value}function Zne(t){const e=lwe("tcp",t)?.value;return e==null?"":`:${e}`}function lwe(t,e){return e.find(n=>n.name===t)}function Yne(t){return t.some(({code:e})=>e===Eye)}function bu(t,e){const n=uwe[t.name];if(n==null)throw new Error(`Can't interpret protocol ${t.name}`);const r=n(t,e);return t.code===Zu?`[${r}]`:r}const uwe={ip4:(t,e)=>t.value,ip6:(t,e)=>e.length===0?t.value:`[${t.value}]`,tcp:(t,e)=>{const n=e.pop();if(n==null)throw new Error("Unexpected end of multiaddr");return`tcp://${bu(n,e)}:${t.value}`},udp:(t,e)=>{const n=e.pop();if(n==null)throw new Error("Unexpected end of multiaddr");return`udp://${bu(n,e)}:${t.value}`},dnsaddr:(t,e)=>t.value,dns4:(t,e)=>t.value,dns6:(t,e)=>t.value,dns:(t,e)=>t.value,ipfs:(t,e)=>{const n=e.pop();if(n==null)throw new Error("Unexpected end of multiaddr");return`${bu(n,e)}`},p2p:(t,e)=>{const n=e.pop();if(n==null)throw new Error("Unexpected end of multiaddr");return`${bu(n,e)}`},http:(t,e)=>{const n=Yne(e),r=Gne(e),s=Zne(e);if(n&&r!=null)return`https://${r}${s}`;const i=n?"https://":"http://",o=e.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let a=bu(o,e);return a=a?.replace("tcp://",""),`${i}${a}`},"http-path":(t,e)=>{const n=e.pop();if(n==null)throw new Error("Unexpected end of multiaddr");const r=bu(n,e),s=decodeURIComponent(t.value??"");return`${r}${s}`},tls:(t,e)=>{const n=e.pop();if(n==null)throw new Error("Unexpected end of multiaddr");return bu(n,e)},sni:(t,e)=>{const n=e.pop();if(n==null)throw new Error("Unexpected end of multiaddr");return bu(n,e)},https:(t,e)=>{const n=e.pop();if(n==null)throw new Error("Unexpected end of multiaddr");let r=bu(n,e);return r=r?.replace("tcp://",""),`https://${r}`},ws:(t,e)=>{const n=Yne(e),r=Gne(e),s=Zne(e);if(n&&r!=null)return`wss://${r}${s}`;const i=n?"wss://":"ws://",o=e.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let a=bu(o,e);return a=a?.replace("tcp://",""),`${i}${a}`},wss:(t,e)=>{const n=e.pop();if(n==null)throw new Error("Unexpected end of multiaddr");let r=bu(n,e);return r=r?.replace("tcp://",""),`wss://${r}`}};function u2t(t,e){const r=er(t).getComponents(),s=r.pop();if(s==null)throw new Error("Unexpected end of multiaddr");const i=uwe[s.name];if(i==null)throw new Error(`No interpreter found for ${s.name}`);let o=i(s,r)??"";return l2t.includes(s.code)&&(o=o.replace(/^.*:\/\//,""),s.value==="443"?o=`https://${o}`:o=`http://${o}`),(o.startsWith("http://")||o.startsWith("https://")||o.startsWith("ws://")||o.startsWith("wss://"))&&(o=new URL(o).toString(),o.endsWith("/")&&(o=o.substring(0,o.length-1))),o}const d2t=async t=>{if(t.readyState>=2)throw new Error("socket closed");t.readyState!==1&&await new Promise((e,n)=>{function r(){t.removeEventListener("open",s),t.removeEventListener("error",i)}function s(){r(),e()}function i(o){r(),n(o.error??new Error(`connect ECONNREFUSED ${t.url}`))}t.addEventListener("open",s),t.addEventListener("error",i)})},f2t=(t,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async r=>{for await(const s of r){try{await d2t(t)}catch(i){if(i.message==="socket closed")break;throw i}if(t.readyState===t.CLOSING||t.readyState===t.CLOSED)break;t.send(s)}e.closeOnEnd!=null&&t.readyState<=1&&await new Promise((s,i)=>{t.addEventListener("close",o=>{if(o.wasClean||o.code===1006)s();else{const a=Object.assign(new Error("ws error"),{event:o});i(a)}}),setTimeout(()=>{t.close()})})});var v8={},x8={};Object.defineProperty(x8,"__esModule",{value:!0});class h2t{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const n={value:e,done:!1};if(this.pullQueue.length){const r=this.pullQueue.shift();r&&r.resolve(n)}else this.pushQueue.push(Promise.resolve(n)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const n of this.pullQueue)n.reject(e);this.pullQueue.length=0}else{const n=Promise.reject(e);n.catch(()=>{}),this.pushQueue.push(n)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{const n=this.pushQueue.shift();return n?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),n):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((r,s)=>{this.pullQueue.push({resolve:r,reject:s})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}let dwe=class{constructor(e,{highWaterMark:n=100,lowWaterMark:r=1}={}){const s=new h2t;s.highWaterMark=n,s.lowWaterMark=r,s.removeCallback=e({push:i=>s.push(i),stop:()=>s.stop(),fail:i=>s.fail(i),on:(i,o)=>{s.eventHandlers[i]=o}})||(()=>{}),this[Symbol.asyncIterator]=()=>s[Symbol.asyncIterator](),Object.freeze(this)}};x8.EventIterator=dwe;x8.default=dwe;Object.defineProperty(v8,"__esModule",{value:!0});const DV=x8;var p2t=v8.EventIterator=DV.EventIterator;function g2t(t,e,n){return new DV.EventIterator(({push:r})=>(this.addEventListener(t,r,e),()=>this.removeEventListener(t,r,e)),n)}v8.subscribe=g2t;v8.default=DV.EventIterator;function Xne(t){return t instanceof ArrayBuffer||t?.constructor?.name==="ArrayBuffer"&&typeof t?.byteLength=="number"}const m2t=t=>{t.binaryType="arraybuffer";const e=async()=>{await new Promise((i,o)=>{if(r){i();return}if(s!=null){o(s);return}const a=u=>{t.removeEventListener("open",c),t.removeEventListener("error",l),u()},c=()=>{a(i)},l=u=>{a(()=>{o(u.error??new Error(`connect ECONNREFUSED ${t.url}`))})};t.addEventListener("open",c),t.addEventListener("error",l)})},n=async function*(){const i=new p2t(({push:o,stop:a,fail:c})=>{const l=d=>{let f=null;typeof d.data=="string"&&(f=Jt(d.data)),Xne(d.data)&&(f=new Uint8Array(d.data)),d.data instanceof Uint8Array&&(f=d.data),f!=null&&o(f)},u=d=>{c(d.error??new Error("Socket error"))};return t.addEventListener("message",l),t.addEventListener("error",u),t.addEventListener("close",a),()=>{t.removeEventListener("message",l),t.removeEventListener("error",u),t.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(const o of i)yield Xne(o)?new Uint8Array(o):o}();let r=t.readyState===1,s;return t.addEventListener("open",()=>{r=!0,s=null}),t.addEventListener("close",()=>{r=!1,s=null}),t.addEventListener("error",i=>{r||(s=i.error??new Error(`connect ECONNREFUSED ${t.url}`))}),Object.assign(n,{connected:e})},y2t=(t,e)=>{e=e??{};const n=m2t(t);let r=e.remoteAddress,s=e.remotePort;if(t.url!=null)try{const o=new URL(t.url);r=o.hostname,s=parseInt(o.port,10)}catch{}if(r==null||s==null)throw new Error("Remote connection did not have address and/or port");return{sink:f2t(t,e),source:n,connected:async()=>{await n.connected()},close:async()=>{(t.readyState===t.CONNECTING||t.readyState===t.OPEN)&&await new Promise(o=>{t.addEventListener("close",()=>{o()}),t.close()})},destroy:()=>{t.terminate!=null?t.terminate():t.close()},remoteAddress:r,remotePort:s,socket:t}},w2t=WebSocket,b2t={"http:":"ws:","https:":"wss:"},Qne="ws:",v2t=(t,e)=>{if(t.startsWith("//")&&(t=`${e?.protocol??Qne}${t}`),t.startsWith("/")&&e!=null){const r=e.protocol??Qne,s=e.host,i=e.port!=null&&s?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";t=`${r}//${s}${i}${t}`}const n=new URL(t);for(const[r,s]of Object.entries(b2t))n.protocol===r&&(n.protocol=s);return n};function x2t(t,e){const n=typeof window>"u"?void 0:window.location;e=e??{};const r=v2t(t,n),s=new w2t(r.toString(),e.websocket);return y2t(s,e)}class Ua extends Event{type;detail;constructor(e,n){super(e),this.type=e,this.detail=n}}function fwe(t){return t.filter(e=>iS.exactMatch(e)||sS.exactMatch(e))}function E2t(t){return t.filter(e=>iS.exactMatch(e))}function C2t(){throw new Error("WebSocket Servers can not be created in the browser!")}const _2t=500;function S2t(t,e,n){const r=n.logger.forComponent("libp2p:websockets:maconn"),s=n.metrics,i=n.metricPrefix??"",o={log:r,async sink(a){try{await t.sink(async function*(){for await(const c of a)c instanceof Uint8Array?yield c:yield c.subarray()}())}catch(c){c.type!=="aborted"&&r.error(c)}},source:t.source,remoteAddr:e,timeline:{open:Date.now()},async close(a={}){const c=Date.now();if(a.signal==null){const u=AbortSignal.timeout(_2t);a={...a,signal:u}}const l=()=>{const{host:u,port:d}=o.remoteAddr.toOptions();r("timeout closing stream to %s:%s after %dms, destroying it manually",u,d,Date.now()-c),this.abort(new b1("Socket close timeout"))};a.signal?.addEventListener("abort",l);try{await t.close()}catch(u){r.error("error closing WebSocket gracefully",u),this.abort(u)}finally{a.signal?.removeEventListener("abort",l),o.timeline.close=Date.now()}},abort(a){const{host:c,port:l}=o.remoteAddr.toOptions();r("timeout closing stream to %s:%s due to error",c,l,a),t.destroy(),o.timeline.close=Date.now(),s?.increment({[`${i}error`]:!0})}};return t.socket.addEventListener("close",()=>{s?.increment({[`${i}close`]:!0}),o.timeline.close==null&&(o.timeline.close=Date.now())},{once:!0}),o}class A2t{log;init;logger;metrics;components;constructor(e,n={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=n,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Cmt]=!0;[Symbol.toStringTag]="@libp2p/websockets";[lp]=["@libp2p/transport"];async dial(e,n){this.log("dialing %s",e),n=n??{};const r=await this._connect(e,n),s=S2t(r,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",s.remoteAddr);const i=await n.upgrader.upgradeOutbound(s,n);return this.log("outbound connection %s upgraded",s.remoteAddr),i}async _connect(e,n){n?.signal?.throwIfAborted();const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const s=qs(),i=x2t(u2t(e),this.init);i.socket.addEventListener("error",()=>{const o=new Imt(`Could not connect to ${e.toString()}`);this.log.error("connection error:",o),this.metrics?.dialerEvents.increment({error:!0}),s.reject(o)});try{n.onProgress?.(new Ua("websockets:open-connection")),await Jo(Promise.race([i.connected(),s.promise]),n.signal)}catch(o){throw n.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),i.close().catch(a=>{this.log.error("error closing raw socket",a)}),o}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),i}createListener(e){return C2t({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):fwe(e)}dialFilter(e){return this.listenFilter(e)}}function I2t(t={}){return e=>new A2t(e,t)}function w4(t){if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}const{hasOwnProperty:hwe}=Object.prototype,{propertyIsEnumerable:T2t}=Object,T1=(t,e,n)=>{Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})},N2t=void 0,Jne={concatArrays:!1,ignoreUndefined:!1},E8=t=>{const e=[];for(const n in t)hwe.call(t,n)&&e.push(n);if(Object.getOwnPropertySymbols){const n=Object.getOwnPropertySymbols(t);for(const r of n)T2t.call(t,r)&&e.push(r)}return e};function Ex(t){return Array.isArray(t)?P2t(t):w4(t)?k2t(t):t}function P2t(t){const e=t.slice(0,0);return E8(t).forEach(n=>{T1(e,n,Ex(t[n]))}),e}function k2t(t){const e=Object.getPrototypeOf(t)===null?Object.create(null):{};return E8(t).forEach(n=>{T1(e,n,Ex(t[n]))}),e}const pwe=(t,e,n,r)=>(n.forEach(s=>{typeof e[s]>"u"&&r.ignoreUndefined||(s in t&&t[s]!==Object.getPrototypeOf(t)?T1(t,s,wU(t[s],e[s],r)):T1(t,s,Ex(e[s])))}),t),R2t=(t,e,n)=>{let r=t.slice(0,0),s=0;return[t,e].forEach(i=>{const o=[];for(let a=0;a!o.includes(a)),n)}),r};function wU(t,e,n){return n.concatArrays&&Array.isArray(t)&&Array.isArray(e)?R2t(t,e,n):!w4(e)||!w4(t)?Ex(e):pwe(t,e,E8(e),n)}function gwe(...t){const e=wU(Ex(Jne),this!==N2t&&this||{},Jne);let n={_:{}};for(const r of t)if(r!==void 0){if(!w4(r))throw new TypeError("`"+r+"` is not an Option Object");n=wU(n,{_:r},e)}return n._}var mwe={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function s(c,l,u){this.fn=c,this.context=l,this.once=u||!1}function i(c,l,u,d,f){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new s(u,d||c,f),m=n?n+l:l;return c._events[m]?c._events[m].fn?c._events[m]=[c._events[m],p]:c._events[m].push(p):(c._events[m]=p,c._eventsCount++),c}function o(c,l){--c._eventsCount===0?c._events=new r:delete c._events[l]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],u,d;if(this._eventsCount===0)return l;for(d in u=this._events)e.call(u,d)&&l.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},a.prototype.listeners=function(l){var u=n?n+l:l,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,p=d.length,m=new Array(p);fglobalThis.DOMException===void 0?new D2t(t):new DOMException(t),tre=t=>{const e=t.reason===void 0?ere("This operation was aborted."):t.reason;return e instanceof Error?e:ere(e)};function M2t(t,e){const{milliseconds:n,fallback:r,message:s,customTimers:i={setTimeout,clearTimeout}}=e;let o,a;const l=new Promise((u,d)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(e.signal){const{signal:p}=e;p.aborted&&d(tre(p)),a=()=>{d(tre(p))},p.addEventListener("abort",a,{once:!0})}if(n===Number.POSITIVE_INFINITY){t.then(u,d);return}const f=new ywe;o=i.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(p){d(p)}return}typeof t.cancel=="function"&&t.cancel(),s===!1?u():s instanceof Error?d(s):(f.message=s??`Promise timed out after ${n} milliseconds`,d(f))},n),(async()=>{try{u(await t)}catch(p){d(p)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},l}function L2t(t,e,n){let r=0,s=t.length;for(;s>0;){const i=Math.trunc(s/2);let o=r+i;n(t[o],e)<=0?(r=++o,s-=i+1):s=i}return r}let B2t=class{#e=[];enqueue(e,n){n={priority:0,...n};const r={priority:n.priority,id:n.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=n.priority){this.#e.push(r);return}const s=L2t(this.#e,r,(i,o)=>o.priority-i.priority);this.#e.splice(s,0,r)}setPriority(e,n){const r=this.#e.findIndex(i=>i.id===e);if(r===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[s]=this.#e.splice(r,1);this.enqueue(s.run,{priority:n,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this.#e.length}};class U2t extends $2t{#e;#t;#n=0;#s;#i;#a=0;#o;#r;#c;#f;#l=0;#d;#u;#h;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:B2t,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#s=e.intervalCap,this.#i=e.interval,this.#c=new e.queueClass,this.#f=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#h=e.throwOnTimeout===!0,this.#u=e.autoStart===!1}get#v(){return this.#t||this.#n{this.#C()},n)),!0}return!1}#p(){if(this.#c.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#l===0&&this.emit("idle"),!1;if(!this.#u){const e=!this.#_;if(this.#v&&this.#x){const n=this.#c.dequeue();return n?(this.emit("active"),n(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#o!==void 0||(this.#o=setInterval(()=>{this.#w()},this.#i),this.#a=Date.now()+this.#i)}#w(){this.#n===0&&this.#l===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#n=this.#e?this.#l:0,this.#g()}#g(){for(;this.#p(););}get concurrency(){return this.#d}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#d=e,this.#g()}async#S(e){return new Promise((n,r)=>{e.addEventListener("abort",()=>{r(e.reason)},{once:!0})})}setPriority(e,n){this.#c.setPriority(e,n)}async add(e,n={}){return n.id??=(this.#b++).toString(),n={timeout:this.timeout,throwOnTimeout:this.#h,...n},new Promise((r,s)=>{this.#c.enqueue(async()=>{this.#l++,this.#n++;try{n.signal?.throwIfAborted();let i=e({signal:n.signal});n.timeout&&(i=M2t(Promise.resolve(i),{milliseconds:n.timeout})),n.signal&&(i=Promise.race([i,this.#S(n.signal)]));const o=await i;r(o),this.emit("completed",o)}catch(i){if(i instanceof ywe&&!n.throwOnTimeout){r();return}s(i),this.emit("error",i)}finally{this.#E()}},n),this.emit("add"),this.#p()})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this.#u?(this.#u=!1,this.#g(),this):this}pause(){this.#u=!0}clear(){this.#c=new this.#f}async onEmpty(){this.#c.size!==0&&await this.#m("empty")}async onSizeLessThan(e){this.#c.sizethis.#c.size{const s=()=>{n&&!n()||(this.off(e,s),r())};this.on(e,s)})}get size(){return this.#c.size}sizeBy(e){return this.#c.filter(e).length}get pending(){return this.#l}get isPaused(){return this.#u}}function wwe(t){const e=[E0.A];return t==null?e:Array.isArray(t)?t.length===0?e:t:[t]}const bwe=60;function vwe(t){return{Status:t.Status??0,TC:t.TC??t.flag_tc??!1,RD:t.RD??t.flag_rd??!1,RA:t.RA??t.flag_ra??!1,AD:t.AD??t.flag_ad??!1,CD:t.CD??t.flag_cd??!1,Question:(t.Question??t.questions??[]).map(e=>({name:e.name,type:E0[e.type]})),Answer:(t.Answer??t.answers??[]).map(e=>({name:e.name,type:E0[e.type],TTL:e.TTL??e.ttl??bwe,data:e.data instanceof Uint8Array?hn(e.data):e.data}))}}const F2t=4;function nre(t,e={}){const n=new U2t({concurrency:e.queryConcurrency??F2t});return async(r,s={})=>{const i=new URLSearchParams;i.set("name",r),wwe(s.types).forEach(a=>{i.append("type",E0[a])}),s.onProgress?.(new Ua("dns:query",{detail:r}));const o=await n.add(async()=>{const a=await fetch(`${t}?${i}`,{headers:{accept:"application/dns-json"},signal:s?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);const c=vwe(await a.json());return s.onProgress?.(new Ua("dns:response",{detail:c})),c},{signal:s.signal});if(o==null)throw new Error("No DNS response received");return o}}function j2t(){return[nre("https://cloudflare-dns.com/dns-query"),nre("https://dns.google/resolve")]}var z2t=function(t){if(!t)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,n=Object.create(null),r=Object.create(null);function s(i,o){n[i]=o,e++,e>=t&&(e=0,r=n,n=Object.create(null))}return{has:function(i){return n[i]!==void 0||r[i]!==void 0},remove:function(i){n[i]!==void 0&&(n[i]=void 0),r[i]!==void 0&&(r[i]=void 0)},get:function(i){var o=n[i];if(o!==void 0)return o;if((o=r[i])!==void 0)return s(i,o),o},set:function(i,o){n[i]!==void 0?n[i]=o:s(i,o)},clear:function(){n=Object.create(null),r=Object.create(null)}}};const W2t=Zi(z2t);class V2t{lru;constructor(e){this.lru=W2t(e)}get(e,n){let r=!0;const s=[];for(const i of n){const o=this.getAnswers(e,i);if(o.length===0){r=!1;break}s.push(...o)}if(r)return vwe({answers:s})}getAnswers(e,n){const r=`${e.toLowerCase()}-${n}`,s=this.lru.get(r);if(s!=null){const i=s.filter(o=>o.expires>Date.now()).map(({expires:o,value:a})=>({...a,TTL:Math.round((o-Date.now())/1e3),type:E0[a.type]}));return i.length===0&&this.lru.remove(r),i}return[]}add(e,n){const r=`${e.toLowerCase()}-${n.type}`,s=this.lru.get(r)??[];s.push({expires:Date.now()+(n.TTL??bwe)*1e3,value:n}),this.lru.set(r,s)}remove(e,n){const r=`${e.toLowerCase()}-${n}`;this.lru.remove(r)}clear(){this.lru.clear()}}function H2t(t){return new V2t(t)}const q2t=1e3;class K2t{resolvers;cache;constructor(e){this.resolvers={},this.cache=H2t(e.cacheSize??q2t),Object.entries(e.resolvers??{}).forEach(([n,r])=>{Array.isArray(r)||(r=[r]),n.endsWith(".")||(n=`${n}.`),this.resolvers[n]=r}),this.resolvers["."]==null&&(this.resolvers["."]=j2t())}async query(e,n={}){const r=wwe(n.types),s=n.cached!==!1?this.cache.get(e,r):void 0;if(s!=null)return n.onProgress?.(new Ua("dns:cache",{detail:s})),s;const i=`${e.split(".").pop()}.`,o=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(const c of o){if(n.signal?.aborted===!0)break;try{const l=await c(e,{...n,types:r});for(const u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),n.onProgress?.(new Ua("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${r} failed`)}}var E0;(function(t){t[t.A=1]="A",t[t.CNAME=5]="CNAME",t[t.TXT=16]="TXT",t[t.AAAA=28]="AAAA"})(E0||(E0={}));function G2t(t={}){return new K2t(t)}const Cc=-1,bU={},Z2t={},Y2t=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Cc,"ip6zone"],[43,8,"ipcidr"],[53,Cc,"dns",!0],[54,Cc,"dns4",!0],[55,Cc,"dns6",!0],[56,Cc,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,Cc,"unix",!1,!0],[421,Cc,"ipfs"],[421,Cc,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Cc,"garlic64"],[448,0,"tls"],[449,Cc,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,Cc,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,Cc,"http-path"],[777,Cc,"memory"]];Y2t.forEach(t=>{const e=X2t(...t);Z2t[e.code]=e,bU[e.name]=e});function X2t(t,e,n,r,s){return{code:t,size:e,name:n,resolvable:!!r,path:!!s}}function Q2t(t){{if(bU[t]!=null)return bU[t];throw new Error(`no protocol with name: ${t}`)}}const J2t=32,{code:eEt}=Q2t("dnsaddr");class tEt extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const MV=async function(e,n={}){const r=n.maxRecursiveDepth??J2t;if(r===0)throw new tEt("Max recursive depth reached");const[,s]=e.stringTuples().find(([l])=>l===eEt)??[],o=await(n?.dns??G2t()).query(`_dnsaddr.${s}`,{signal:n?.signal,types:[E0.TXT]}),a=e.getPeerId(),c=[];for(const l of o.Answer){const u=l.data.replace(/["']/g,"").trim().split("=")[1];if(u==null||a!=null&&!u.includes(a))continue;const d=er(u);if(u.startsWith("/dnsaddr")){const f=await d.resolve({...n,maxRecursiveDepth:r-1});c.push(...f.map(p=>p.toString()))}else c.push(d.toString())}return c},nEt={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:MV}},transportManager:{faultTolerance:q_.FATAL_ALL}};async function rEt(t){const e=gwe(nEt,t);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new cr("Private network is enforced, but no protector was provided");return e}const N1=1e3,P1=N1*60,k1=P1*60,Vy=k1*24,oS=Vy*7,R1=Vy*365.25,aS=R1/12;function sEt(t,e){if(typeof t=="string")return iEt(t);if(typeof t=="number")return cEt(t,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(t)}`)}var xwe=sEt;function iEt(t){if(typeof t!="string"||t.length===0||t.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(t)}`);let e=/^(?-?\d*\.?\d+) *(?milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(t);if(!e?.groups)return NaN;let{value:n,unit:r="ms"}=e.groups,s=parseFloat(n),i=r.toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return s*R1;case"months":case"month":case"mo":return s*aS;case"weeks":case"week":case"w":return s*oS;case"days":case"day":case"d":return s*Vy;case"hours":case"hour":case"hrs":case"hr":case"h":return s*k1;case"minutes":case"minute":case"mins":case"min":case"m":return s*P1;case"seconds":case"second":case"secs":case"sec":case"s":return s*N1;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:throw Error(`Unknown unit "${i}" provided to ms.parse(). value=${JSON.stringify(t)}`)}}function oEt(t){let e=Math.abs(t);return e>=R1?`${Math.round(t/R1)}y`:e>=aS?`${Math.round(t/aS)}mo`:e>=oS?`${Math.round(t/oS)}w`:e>=Vy?`${Math.round(t/Vy)}d`:e>=k1?`${Math.round(t/k1)}h`:e>=P1?`${Math.round(t/P1)}m`:e>=N1?`${Math.round(t/N1)}s`:`${t}ms`}function aEt(t){let e=Math.abs(t);return e>=R1?rm(t,e,R1,"year"):e>=aS?rm(t,e,aS,"month"):e>=oS?rm(t,e,oS,"week"):e>=Vy?rm(t,e,Vy,"day"):e>=k1?rm(t,e,k1,"hour"):e>=P1?rm(t,e,P1,"minute"):e>=N1?rm(t,e,N1,"second"):`${t} ms`}function cEt(t,e){if(typeof t!="number"||!Number.isFinite(t))throw Error("Value provided to ms.format() must be of type number.");return e?.long?aEt(t):oEt(t)}function rm(t,e,n,r){let s=e>=n*1.5;return`${Math.round(t/n)} ${r}${s?"s":""}`}function lEt(t){n.debug=n,n.default=n,n.coerce=c,n.disable=i,n.enable=s,n.enabled=o,n.humanize=xwe,n.destroy=l,Object.keys(t).forEach(u=>{n[u]=t[u]}),n.names=[],n.skips=[],n.formatters={};function e(u){let d=0;for(let f=0;f{if(k==="%%")return"%";A++;const W=n.formatters[B];if(typeof W=="function"){const S=b[A];k=W.call(v,S),b.splice(A,1),A--}return k}),n.formatArgs.call(v,b),(v.log||n.log).apply(v,b)}return y.namespace=u,y.useColors=n.useColors(),y.color=n.selectColor(u),y.extend=r,y.destroy=n.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(p!==n.namespaces&&(p=n.namespaces,m=n.enabled(u)),m),set:b=>{f=b}}),typeof n.init=="function"&&n.init(y),y}function r(u,d){const f=n(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function s(u){n.save(u),n.namespaces=u,n.names=[],n.skips=[];let d;const f=(typeof u=="string"?u:"").split(/[\s,]+/),p=f.length;for(d=0;d"-"+d)].join(",");return n.enable(""),u}function o(u){if(u[u.length-1]==="*")return!0;let d,f;for(d=0,f=n.skips.length;d=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function hEt(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+xwe(this.diff),!this.useColors)return;const e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(n++,s==="%c"&&(r=n))}),t.splice(r,0,e)}const pEt=console.debug??console.log??(()=>{});function gEt(t){try{t?b4?.setItem("debug",t):b4?.removeItem("debug")}catch{}}function mEt(){let t;try{t=b4?.getItem("debug")}catch{}return!t&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(t=uEt.DEBUG),t}function yEt(){try{return localStorage}catch{}}function wEt(t){t.j=function(e){try{return JSON.stringify(e)}catch(n){return"[UnexpectedJSONParseError]: "+n.message}}}const Qo=lEt({formatArgs:hEt,save:gEt,load:mEt,useColors:fEt,setupFormatters:wEt,colors:dEt,storage:b4,log:pEt});Qo.formatters.b=t=>t==null?"undefined":ps.baseEncode(t);Qo.formatters.t=t=>t==null?"undefined":e0.baseEncode(t);Qo.formatters.m=t=>t==null?"undefined":rme.baseEncode(t);Qo.formatters.p=t=>t==null?"undefined":t.toString();Qo.formatters.c=t=>t==null?"undefined":t.toString();Qo.formatters.k=t=>t==null?"undefined":t.toString();Qo.formatters.a=t=>t==null?"undefined":t.toString();Qo.formatters.e=t=>t==null?"undefined":rre(t.stack)??rre(t.message)??t.toString();function bEt(t){const e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function Ewe(){return{forComponent(t){return Cwe(t)}}}function Cwe(t){let e=bEt(`${t}:trace`);return Qo.enabled(`${t}:trace`)&&Qo.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(e=Qo(`${t}:trace`)),Object.assign(Qo(t),{error:Qo(`${t}:error`),trace:e,newScope:n=>Cwe(`${t}:${n}`)})}function rre(t){if(t!=null&&(t=t.trim(),t.length!==0))return t}function jE(t,e){const n={[Symbol.iterator]:()=>n,next:()=>{const r=t.next(),s=r.value;return r.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return n}function a9(t){const e=Zk(ps.decode(`z${t}`));return o8(e)}class j3{map;constructor(e){if(this.map=new Map,e!=null)for(const[n,r]of e.entries())this.map.set(n.toString(),{key:n,value:r})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return jE(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((n,r)=>{e(n.value,n.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,n){this.map.set(e.toString(),{key:e,value:n})}keys(){return jE(this.map.values(),e=>e.key)}values(){return jE(this.map.values(),e=>e.value)}get size(){return this.map.size}}class yv{set;constructor(e){if(this.set=new Set,e!=null)for(const n of e)this.set.add(n.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return jE(this.set.entries(),e=>{const n=a9(e[0]);return[n,n]})}forEach(e){this.set.forEach(n=>{const r=a9(n);e(r,r,this)})}has(e){return this.set.has(e.toString())}values(){return jE(this.set.values(),e=>a9(e))}intersection(e){const n=new yv;for(const r of e)this.has(r)&&n.add(r);return n}difference(e){const n=new yv;for(const r of this)e.has(r)||n.add(r);return n}union(e){const n=new yv;for(const r of e)n.add(r);for(const r of this)n.add(r);return n}}const LV={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},_we={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Swe=new globalThis.TextEncoder;function vEt(t,e){const n=LV[e];let r=_we[e];for(let s=0;s0;){const o=Swe.encodeInto(i,n);i=i.slice(o.read);for(let a=0;aNumber(EEt(t,{size:32})),hashV:(t,e)=>CEt(BV.hash(t,e))};function CEt(t){let e=t.toString(16);return e.length%2===1&&(e=`0${e}`),Jt(e,"base16")}const Awe=64;class Om{fp;h;seed;constructor(e,n,r,s=2){if(s>Awe)throw new TypeError("Invalid Fingerprint Size");const i=n.hashV(e,r),o=Mt(s);for(let a=0;ae.equals(n))}add(e){if(!(e instanceof Om))throw new TypeError("Invalid Fingerprint");for(let n=0;ne.equals(r));return n>-1?(this.contents[n]=null,!0):!1}}const _Et=500;class sre{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??BV,this.seed=e.seed??v4(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=Jt(e));const n=new Om(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,s=(r^n.hash())%this.filterSize;if(this.buckets[r]==null&&(this.buckets[r]=new iI(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new iI(this.bucketSize)),this.buckets[r].add(n)||this.buckets[s].add(n))return this.count++,!0;const i=[r,s];let o=i[v4(0,i.length-1)];this.buckets[o]==null&&(this.buckets[o]=new iI(this.bucketSize));for(let a=0;a<_Et;a++){const c=this.buckets[o].swap(n);if(c!=null&&(o=(o^c.hash())%this.filterSize,this.buckets[o]==null&&(this.buckets[o]=new iI(this.bucketSize)),this.buckets[o].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=Jt(e));const n=new Om(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[r]?.has(n)??!1;if(s)return s;const i=(r^n.hash())%this.filterSize;return this.buckets[i]?.has(n)??!1}remove(e){typeof e=="string"&&(e=Jt(e));const n=new Om(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[r]?.remove(n)??!1;if(s)return this.count--,s;const i=(r^n.hash())%this.filterSize,o=this.buckets[i]?.remove(n)??!1;return o&&this.count--,o}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}}const SEt={1:.5,2:.84,4:.95,8:.98};function AEt(t=.001){return t>.002?2:t>1e-5?4:8}function IEt(t,e=.001){const n=AEt(e),r=SEt[n],s=Math.round(t/r),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*n)),Awe);return{filterSize:s,bucketSize:n,fingerprintSize:i}}class TEt{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??BV,this.seed=e.seed??v4(0,Math.pow(2,10)),this.filterSeries=[new sre({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=Jt(e)),this.has(e))return!0;let n=this.filterSeries.find(r=>r.reliable);if(n==null){const r=this.filterSize*Math.pow(this.scale,this.filterSeries.length);n=new sre({filterSize:r,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(n)}return n.add(e)}has(e){typeof e=="string"&&(e=Jt(e));for(let n=0;ne+n.count,0)}}function Iwe(t,e=.001,n){return new TEt({...IEt(t,e)})}class NEt extends j3{metric;constructor(e){super();const{name:n,metrics:r}=e;this.metric=r.registerMetric(n),this.updateComponentMetric()}set(e,n){return super.set(e,n),this.updateComponentMetric(),this}delete(e){const n=super.delete(e);return this.updateComponentMetric(),n}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function PEt(t){const{name:e,metrics:n}=t;let r;return n!=null?r=new NEt({name:e,metrics:n}):r=new j3,r}let O1=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...n){super(e,...n)}};async function Ym(t,e,n,r){const s=new O1(r?.errorMessage);r?.errorCode!=null&&(s.code=r.errorCode);const i=r?.errorEvent??"error";return n?.aborted===!0?Promise.reject(s):new Promise((o,a)=>{function c(){l9(n,"abort",d),l9(t,e,l),l9(t,i,u)}const l=f=>{try{if(r?.filter?.(f)===!1)return}catch(p){c(),a(p);return}c(),o(f)},u=f=>{if(c(),f instanceof Error){a(f);return}a(f.detail??r?.error??new Error(`The "${r?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{c(),a(s)};c9(n,"abort",d),c9(t,e,l),c9(t,i,u)})}function c9(t,e,n){t!=null&&(Twe(t)?t.addEventListener(e,n):t.addListener(e,n))}function l9(t,e,n){t!=null&&(Twe(t)?t.removeEventListener(e,n):t.removeListener(e,n))}function Twe(t){return typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"}class kEt extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}let REt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new O1)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function OEt(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}let $Et=class{id;fn;options;recipients;status;timeline;controller;constructor(e,n){this.id=OEt(),this.status="queued",this.fn=e,this.options=n,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((n,r)=>n&&r.signal?.aborted===!0,!0)&&(this.controller.abort(new O1),this.cleanup())}async join(e={}){const n=new REt(e.signal);return this.recipients.push(n),e.signal?.addEventListener("abort",this.onAbort),n.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await Jo(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(n=>{n.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(n=>{n.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function ire(t,e){let n;const r=function(){const s=function(){n=void 0,t()};clearTimeout(n),n=setTimeout(s,e)};return r.start=()=>{},r.stop=()=>{clearTimeout(n)},r}let ore=class extends Oo{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=ire(this.emitEmpty.bind(this),1),this.emitIdle=ire(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending{for(let n=0;n(this.safeDispatchEvent("success",{detail:{job:r,result:s}}),s)).catch(s=>{if(r.status==="queued"){for(let i=0;i{e.abort(new O1)}),this.clear()}async onEmpty(e){this.size!==0&&await Ym(this,"empty",e?.signal)}async onSizeLessThan(e,n){this.sizethis.size{c!=null?this.abort():this.clear(),n.end(c)},s=c=>{c.detail!=null&&n.push(c.detail.result)},i=c=>{r(c.detail.error)},o=()=>{r()},a=()=>{r(new O1("Queue aborted"))};this.addEventListener("success",s),this.addEventListener("failure",i),this.addEventListener("idle",o),e?.signal?.addEventListener("abort",a);try{yield*n}finally{this.removeEventListener("success",s),this.removeEventListener("failure",i),this.removeEventListener("idle",o),e?.signal?.removeEventListener("abort",a),r()}}};const Nwe="lock:worker:request-read",Pwe="lock:worker:abort-read-request",kwe="lock:worker:release-read",Rwe="lock:master:grant-read",Owe="lock:master:error-read",$we="lock:worker:request-write",Dwe="lock:worker:abort-write-request",Mwe="lock:worker:release-write",Lwe="lock:master:grant-write",Bwe="lock:master:error-write",Uwe="lock:worker:finalize",Fwe="mortice",DEt={singleProcess:!1},are=(t,e,n,r,s,i,o,a,c)=>l=>{if(l.data==null)return;const u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&t.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(d=>{const f=p=>{if(p?.data==null)return;const m={type:p.data.type,name:p.data.name,identifier:p.data.identifier};m.type===a&&m.identifier===u.identifier&&(e.removeEventListener("message",f),d())};e.addEventListener("message",f)})},onError:d=>{e.postMessage({type:o,name:u.name,identifier:u.identifier,error:{message:d.message,name:d.name,stack:d.stack}})}}}),u.type===i&&t.safeDispatchEvent(r,{detail:{name:u.name,identifier:u.identifier}}),u.type===Uwe&&t.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})},MEt=(t=10)=>Math.random().toString().substring(2,t+2);class LEt{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Fwe)}readLock(e){return this.sendRequest(Nwe,Pwe,Rwe,Owe,kwe,e)}writeLock(e){return this.sendRequest($we,Dwe,Lwe,Bwe,Mwe,e)}finalize(){this.channel.postMessage({type:Uwe,name:this.name}),this.channel.close()}async sendRequest(e,n,r,s,i,o){o?.signal?.throwIfAborted();const a=MEt();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{const u=()=>{this.channel.postMessage({type:n,identifier:a,name:this.name})};o?.signal?.addEventListener("abort",u,{once:!0});const d=f=>{if(f.data?.identifier===a&&(f.data?.type===r&&(this.channel.removeEventListener("message",d),o?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),f.data.type===s)){this.channel.removeEventListener("message",d),o?.signal?.removeEventListener("abort",u);const p=new Error;f.data.error!=null&&(p.message=f.data.error.message,p.name=f.data.error.name,p.stack=f.data.error.stack),l(p)}};this.channel.addEventListener("message",d)})}}const BEt=t=>{if(t=Object.assign({},DEt,t),!!globalThis.document||t.singleProcess){const n=new BroadcastChannel(Fwe),r=new Oo;return n.addEventListener("message",are(r,n,"requestReadLock","abortReadLockRequest",Nwe,Pwe,Owe,kwe,Rwe)),n.addEventListener("message",are(r,n,"requestWriteLock","abortWriteLockRequest",$we,Dwe,Bwe,Mwe,Lwe)),r}return new LEt(t.name)},$m=new Map;let I2;function jwe(t){return typeof t?.readLock=="function"&&typeof t?.writeLock=="function"}function UEt(t){if(I2==null&&(I2=BEt(t),!jwe(I2))){const e=I2;e.addEventListener("requestReadLock",n=>{const r=n.detail.name,s=n.detail.identifier,i=$m.get(r);if(i==null)return;const o=new AbortController,a=c=>{c.detail.name!==r||c.detail.identifier!==s||o.abort()};e.addEventListener("abortReadLockRequest",a),i.readLock({signal:o.signal}).then(async c=>{await n.detail.handler().finally(()=>{c()})}).catch(c=>{n.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",n=>{const r=n.detail.name,s=n.detail.identifier,i=$m.get(r);if(i==null)return;const o=new AbortController,a=c=>{c.detail.name!==r||c.detail.identifier!==s||o.abort()};e.addEventListener("abortWriteLockRequest",a),i.writeLock({signal:o.signal}).then(async c=>{await n.detail.handler().finally(()=>{c()})}).catch(c=>{n.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",n=>{const r=n.detail.name,s=$m.get(r);s?.finalize()})}return I2}async function u9(t,e){let n,r;const s=new Promise((o,a)=>{n=o,r=a}),i=()=>{r(new O1)};return e?.signal?.addEventListener("abort",i,{once:!0}),t.add(async()=>{await new Promise(o=>{n(()=>{e?.signal?.removeEventListener("abort",i),o()})})},{signal:e?.signal}).catch(o=>{r(o)}),s}const FEt=(t,e)=>{let n=$m.get(t);if(n!=null)return n;const r=UEt(e);if(jwe(r))return n=r,$m.set(t,n),n;const s=new ore({concurrency:1});let i;return n={async readLock(o){if(i!=null)return u9(i,o);i=new ore({concurrency:e.concurrency,autoStart:!1});const a=i,c=u9(i,o);return s.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),c},async writeLock(o){return i=null,u9(s,o)},finalize:()=>{$m.delete(t)},queue:s},$m.set(t,n),e.autoFinalize===!0&&s.addEventListener("idle",()=>{n.finalize()},{once:!0}),n},jEt={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function zEt(t){const e=Object.assign({},jEt,t);return FEt(e.name,e)}const WEt=36e5,VEt=216e5;var Dm;(function(t){(function(n){let r;n.codec=()=>(r==null&&(r=dn((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.key!=null&&s.key!==""&&(i.uint32(10),i.string(s.key)),s.value!=null&&s.value.byteLength>0&&(i.uint32(18),i.bytes(s.value)),o.lengthDelimited!==!1&&i.ldelim()},(s,i,o={})=>{const a={key:"",value:Mt(0)},c=i==null?s.len:s.pos+i;for(;s.pos>>3){case 1:{a.key=s.string();break}case 2:{a.value=s.bytes();break}default:{s.skipType(l&7);break}}}return a})),r),n.encode=s=>un(s,n.codec()),n.decode=(s,i)=>ln(s,n.codec(),i)})(t.Peer$metadataEntry||(t.Peer$metadataEntry={})),function(n){let r;n.codec=()=>(r==null&&(r=dn((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.key!=null&&s.key!==""&&(i.uint32(10),i.string(s.key)),s.value!=null&&(i.uint32(18),E4.codec().encode(s.value,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i,o={})=>{const a={key:""},c=i==null?s.len:s.pos+i;for(;s.pos>>3){case 1:{a.key=s.string();break}case 2:{a.value=E4.codec().decode(s,s.uint32(),{limits:o.limits?.value});break}default:{s.skipType(l&7);break}}}return a})),r),n.encode=s=>un(s,n.codec()),n.decode=(s,i)=>ln(s,n.codec(),i)}(t.Peer$tagsEntry||(t.Peer$tagsEntry={}));let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.addresses!=null)for(const i of n.addresses)r.uint32(10),x4.codec().encode(i,r);if(n.protocols!=null)for(const i of n.protocols)r.uint32(18),r.string(i);if(n.publicKey!=null&&(r.uint32(34),r.bytes(n.publicKey)),n.peerRecordEnvelope!=null&&(r.uint32(42),r.bytes(n.peerRecordEnvelope)),n.metadata!=null&&n.metadata.size!==0)for(const[i,o]of n.metadata.entries())r.uint32(50),t.Peer$metadataEntry.codec().encode({key:i,value:o},r);if(n.tags!=null&&n.tags.size!==0)for(const[i,o]of n.tags.entries())r.uint32(58),t.Peer$tagsEntry.codec().encode({key:i,value:o},r);n.updated!=null&&(r.uint32(64),r.uint64Number(n.updated)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={addresses:[],protocols:[],metadata:new Map,tags:new Map},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new Gi('Decode error - map field "addresses" had too many elements');i.addresses.push(x4.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}case 2:{if(s.limits?.protocols!=null&&i.protocols.length===s.limits.protocols)throw new Gi('Decode error - map field "protocols" had too many elements');i.protocols.push(n.string());break}case 4:{i.publicKey=n.bytes();break}case 5:{i.peerRecordEnvelope=n.bytes();break}case 6:{if(s.limits?.metadata!=null&&i.metadata.size===s.limits.metadata)throw new Ote('Decode error - map field "metadata" had too many elements');const c=t.Peer$metadataEntry.codec().decode(n,n.uint32());i.metadata.set(c.key,c.value);break}case 7:{if(s.limits?.tags!=null&&i.tags.size===s.limits.tags)throw new Ote('Decode error - map field "tags" had too many elements');const c=t.Peer$tagsEntry.codec().decode(n,n.uint32(),{limits:{value:s.limits?.tags$value}});i.tags.set(c.key,c.value);break}case 8:{i.updated=n.uint64Number();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(Dm||(Dm={}));var x4;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.multiaddr!=null&&n.multiaddr.byteLength>0&&(r.uint32(10),r.bytes(n.multiaddr)),n.isCertified!=null&&(r.uint32(16),r.bool(n.isCertified)),n.observed!=null&&(r.uint32(24),r.uint64Number(n.observed)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={multiaddr:Mt(0)},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.multiaddr=n.bytes();break}case 2:{i.isCertified=n.bool();break}case 3:{i.observed=n.uint64Number();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(x4||(x4={}));var E4;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.value!=null&&n.value!==0&&(r.uint32(8),r.uint32(n.value)),n.expiry!=null&&(r.uint32(16),r.uint64(n.expiry)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={value:0},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.value=n.uint32();break}case 2:{i.expiry=n.uint64();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(E4||(E4={}));function HEt(t,e){if(t.publicKey!=null||e.publicKey==null)return t;let n;t.type==="RSA"&&(n=t.toMultihash());const r=x0(e.publicKey,n);return X_(r)}function qEt(t,e,n){const r=Dm.decode(e);return X2(t,r,n)}function X2(t,e,n){const r=new Map,s=BigInt(Date.now());for(const[i,o]of e.tags.entries())o.expiry!=null&&o.expiryi!=null&&i>Date.now()-n).map(({multiaddr:i,isCertified:o})=>({multiaddr:er(i),isCertified:o??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:r}}function KEt(t,e){return GEt(t.addresses,e.addresses)&&ZEt(t.protocols,e.protocols)&&YEt(t.publicKey,e.publicKey)&&XEt(t.peerRecordEnvelope,e.peerRecordEnvelope)&&QEt(t.metadata,e.metadata)&&JEt(t.tags,e.tags)}function GEt(t,e){return Wwe(t,e,(n,r)=>!(n.isCertified!==r.isCertified||!As(n.multiaddr,r.multiaddr)))}function ZEt(t,e){return Wwe(t,e,(n,r)=>n===r)}function YEt(t,e){return zwe(t,e)}function XEt(t,e){return zwe(t,e)}function QEt(t,e){return Vwe(t,e,(n,r)=>As(n,r))}function JEt(t,e){return Vwe(t,e,(n,r)=>n.value===r.value&&n.expiry===r.expiry)}function zwe(t,e){return t==null&&e==null?!0:t!=null&&e!=null?As(t,e):!1}function Wwe(t,e,n){if(t.length!==e.length)return!1;for(let r=0;r1&&this._buf[this._buf.byteLength-1]===oI;)this._buf=this._buf.subarray(0,-1)}less(e){const n=this.list(),r=e.list();for(let s=0;so)return!1}return n.lengthn.namespaces()))])}}function eCt(t){const e=t.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function tCt(t){const e=t.split(":");return e[e.length-1]}function nCt(t){return[].concat(...t)}const qwe="/peers/";function aI(t){if(!Zm(t)||t.type==null)throw new cr("Invalid PeerId");const e=t.toCID().toString();return new Ho(`${qwe}${e}`)}async function rCt(t,e,n,r,s){const i=new Map;for(const o of n){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=er(o.multiaddr)),!u8(o.multiaddr))throw new cr("Multiaddr was invalid");if(!await e(t,o.multiaddr,s))continue;const a=o.isCertified??!1,c=o.multiaddr.toString(),l=i.get(c);l!=null?o.isCertified=l.isCertified||a:i.set(c,{multiaddr:o.multiaddr,isCertified:a})}return[...i.values()].sort((o,a)=>o.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:o,multiaddr:a})=>{const c=a.getPeerId();return t.equals(c)&&(a=a.decapsulate(er(`/p2p/${t}`))),{isCertified:o,multiaddr:a.bytes}})}async function d9(t,e,n,r){if(e==null)throw new cr("Invalid PeerData");if(e.publicKey!=null&&t.publicKey!=null&&!e.publicKey.equals(t.publicKey))throw new cr("publicKey bytes do not match peer id publicKey bytes");const s=r.existingPeer?.peer;if(s!=null&&!t.equals(s.id))throw new cr("peer id did not match existing peer id");let i=s?.addresses??[],o=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if(n==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(i=[],e.multiaddrs!=null&&i.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&i.push(...e.addresses)),e.protocols!=null&&(o=new Set(e.protocols)),e.metadata!=null){const f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=cI(f,{validate:cre})}if(e.tags!=null){const f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=cI(f,{validate:lre,map:ure})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(n==="merge"){if(e.multiaddrs!=null&&i.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&i.push(...e.addresses),e.protocols!=null&&(o=new Set([...o,...e.protocols])),e.metadata!=null){const f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(const[p,m]of f)m==null?a.delete(p):a.set(p,m);a=cI([...a.entries()],{validate:cre})}if(e.tags!=null){const f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),p=new Map(c);for(const[m,y]of f)y==null?p.delete(m):p.set(m,y);c=cI([...p.entries()],{validate:lre,map:ure})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;s?.id.publicKey!=null?u=Rh(s.id.publicKey):e.publicKey!=null?u=Rh(e.publicKey):t.publicKey!=null&&(u=Rh(t.publicKey));const d={addresses:await rCt(t,r.addressFilter??(async()=>!0),i,r.existingPeer?.peerPB.addresses,r),protocols:[...o.values()].sort((f,p)=>f.localeCompare(p)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return d.addresses.forEach(f=>{f.observed=r.existingPeer?.peerPB.addresses?.find(p=>As(p.multiaddr,p.multiaddr))?.observed??Date.now()}),t.type!=="RSA"&&delete d.publicKey,d}function cI(t,e){const n=new Map;for(const[r,s]of t)s!=null&&e.validate(r,s);for(const[r,s]of t.sort(([i],[o])=>i.localeCompare(o)))s!=null&&n.set(r,e.map?.(r,s)??s);return n}function cre(t,e){if(typeof t!="string")throw new cr("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new cr("Metadata value must be a Uint8Array")}function lre(t,e){if(typeof t!="string")throw new cr("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new cr("Tag value must be an integer");if(e.value<0||e.value>100)throw new cr("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new cr("Tag ttl must be an integer");if(e.ttl<0)throw new cr("Tag ttl must be between greater than 0")}}function ure(t,e){let n;e.expiry!=null&&(n=e.expiry),e.ttl!=null&&(n=BigInt(Date.now()+Number(e.ttl)));const r={value:e.value??0};return n!=null&&(r.expiry=n),r}function Kwe(t){const e=t.toString().split("/")[2],n=Cr.parse(e,e0);return L3(n)}function f9(t,e,n){const r=Kwe(t);return qEt(r,e,n)}function sCt(t,e){return{prefix:qwe,filters:(t.filters??[]).map(n=>({key:r,value:s})=>n(f9(r,s,e))),orders:(t.orders??[]).map(n=>(r,s)=>n(f9(r.key,r.value,e),f9(s.key,s.value,e)))}}class iCt{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,n={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=n.addressFilter,this.locks=PEt({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=n.maxAddressAge??WEt,this.maxPeerAge=n.maxPeerAge??VEt}getLock(e){let n=this.locks.get(e);return n==null&&(n={refs:0,lock:zEt({name:e.toString(),singleProcess:!0})},this.locks.set(e,n)),n.refs++,n}maybeRemoveLock(e,n){n.refs--,n.refs===0&&(n.lock.finalize(),this.locks.delete(e))}async getReadLock(e,n){const r=this.getLock(e);try{const s=await r.lock.readLock(n);return()=>{s(),this.maybeRemoveLock(e,r)}}catch(s){throw this.maybeRemoveLock(e,r),s}}async getWriteLock(e,n){const r=this.getLock(e);try{const s=await r.lock.writeLock(n);return()=>{s(),this.maybeRemoveLock(e,r)}}catch(s){throw this.maybeRemoveLock(e,r),s}}async has(e,n){try{return await this.load(e,n),!0}catch(r){if(r.name!=="NotFoundError")throw r}return!1}async delete(e,n){this.peerId.equals(e)||await this.datastore.delete(aI(e),n)}async load(e,n){const r=aI(e),s=await this.datastore.get(r,n),i=Dm.decode(s);if(this.#n(e,i))throw await this.datastore.delete(r,n),new ZB;return X2(e,i,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,n,r){const s=await this.#e(e,r),i=await d9(e,n,"patch",{...r,addressFilter:this.addressFilter});return this.#t(e,i,s)}async patch(e,n,r){const s=await this.#e(e,r),i=await d9(e,n,"patch",{...r,addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,i,s)}async merge(e,n,r){const s=await this.#e(e,r),i=await d9(e,n,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,i,s)}async*all(e){for await(const{key:n,value:r}of this.datastore.query(sCt(e??{},this.maxAddressAge),e)){const s=Kwe(n);if(s.equals(this.peerId))continue;const i=Dm.decode(r);if(this.#n(s,i)){await this.datastore.delete(n,e);continue}yield X2(s,i,this.peerId.equals(s)?1/0:this.maxAddressAge)}}async#e(e,n){try{const r=aI(e),s=await this.datastore.get(r,n),i=Dm.decode(s);if(this.#n(e,i))throw await this.datastore.delete(r,n),new ZB;return{peerPB:i,peer:X2(e,i,this.maxAddressAge)}}catch(r){r.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",r)}}async#t(e,n,r,s){n.updated=Date.now();const i=Dm.encode(n);return await this.datastore.put(aI(e),i,s),{peer:X2(e,n,this.maxAddressAge),previous:r?.peer,updated:r==null||!KEt(n,r.peerPB)}}#n(e,n){if(n.updated==null)return!0;if(this.peerId.equals(e))return!1;const r=n.updatedo.observed!=null&&o.observed>s);return r&&i.length===0}}class oCt{store;events;peerId;log;constructor(e,n={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new iCt(e,n)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,n){for await(const r of this.store.all(n))e(r)}async all(e){return Gu(this.store.all(e))}async delete(e,n){const r=await this.store.getReadLock(e,n);try{await this.store.delete(e,n)}finally{r()}}async has(e,n){const r=await this.store.getReadLock(e,n);try{return await this.store.has(e,n)}finally{this.log.trace("has release read lock"),r?.()}}async get(e,n){const r=await this.store.getReadLock(e,n);try{return await this.store.load(e,n)}finally{r?.()}}async getInfo(e,n){const r=await this.get(e,n);return{id:r.id,multiaddrs:r.addresses.map(({multiaddr:s})=>s)}}async save(e,n,r){const s=await this.store.getWriteLock(e,r);try{const i=await this.store.save(e,n,r);return this.#e(e,i),i.peer}finally{s?.()}}async patch(e,n,r){const s=await this.store.getWriteLock(e,r);try{const i=await this.store.patch(e,n,r);return this.#e(e,i),i.peer}finally{s?.()}}async merge(e,n,r){const s=await this.store.getWriteLock(e,r);try{const i=await this.store.merge(e,n,r);return this.#e(e,i),i.peer}finally{s?.()}}async consumePeerRecord(e,n,r){const s=Zm(n)?n:Zm(n?.expectedPeer)?n.expectedPeer:void 0,i=Zm(n)||n===void 0?r:n,o=await Oh.openAndCertify(e,Ol.DOMAIN,i),a=L3(o.publicKey.toCID());if(s?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",s,a),!1;const c=Ol.createFromProtobuf(o.payload);let l;try{l=await this.get(a,i)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){const u=Oh.createFromProtobuf(l.peerRecordEnvelope),d=Ol.createFromProtobuf(u.payload);if(d.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},i),!0}#e(e,n){n.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:n}):this.events.safeDispatchEvent("peer:update",{detail:n}))}}function aCt(t,e={}){return new oCt(t,e)}class C4 extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=C4.name;code=C4.code;constructor(e="Not Found"){super(e)}}function cCt(t){const[e,n]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],r=[];return{peek:()=>e.next(),push:s=>{r.push(s)},next:()=>r.length>0?{done:!1,value:r.shift()}:e.next(),[n](){return this}}}function lCt(t){return t[Symbol.asyncIterator]!=null}function hb(t,e){let n=0;if(lCt(t))return async function*(){for await(const c of t)await e(c,n++)&&(yield c)}();const r=cCt(t),{value:s,done:i}=r.next();if(i===!0)return function*(){}();const o=e(s,n++);if(typeof o.then=="function")return async function*(){await o&&(yield s);for(const c of r)await e(c,n++)&&(yield c)}();const a=e;return function*(){o===!0&&(yield s);for(const c of r)a(c,n++)&&(yield c)}()}function uCt(t){return t[Symbol.asyncIterator]!=null}function dre(t,e){return uCt(t)?async function*(){yield*(await Gu(t)).sort(e)}():function*(){yield*Gu(t).sort(e)}()}function dCt(t){return t[Symbol.asyncIterator]!=null}function fre(t,e){return dCt(t)?async function*(){let n=0;if(!(e<1)){for await(const r of t)if(yield r,n++,n===e)return}}():function*(){let n=0;if(!(e<1)){for(const r of t)if(yield r,n++,n===e)return}}()}class fCt{put(e,n,r){return Promise.reject(new Error(".put is not implemented"))}get(e,n){return Promise.reject(new Error(".get is not implemented"))}has(e,n){return Promise.reject(new Error(".has is not implemented"))}delete(e,n){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,n={}){for await(const{key:r,value:s}of e)await this.put(r,s,n),yield r}async*getMany(e,n={}){for await(const r of e)yield{key:r,value:await this.get(r,n)}}async*deleteMany(e,n={}){for await(const r of e)await this.delete(r,n),yield r}batch(){let e=[],n=[];return{put(r,s){e.push({key:r,value:s})},delete(r){n.push(r)},commit:async r=>{await Mne(this.putMany(e,r)),e=[],await Mne(this.deleteMany(n,r)),n=[]}}}async*_all(e,n){throw new Error("._all is not implemented")}async*_allKeys(e,n){throw new Error("._allKeys is not implemented")}query(e,n){let r=this._all(e,n);if(e.prefix!=null){const s=e.prefix;r=hb(r,i=>i.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(r=e.filters.reduce((s,i)=>hb(s,i),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((s,i)=>dre(s,i),r)),e.offset!=null){let s=0;const i=e.offset;r=hb(r,()=>s++>=i)}return e.limit!=null&&(r=fre(r,e.limit)),r}queryKeys(e,n){let r=this._allKeys(e,n);if(e.prefix!=null){const s=e.prefix;r=hb(r,i=>i.toString().startsWith(s))}if(Array.isArray(e.filters)&&(r=e.filters.reduce((s,i)=>hb(s,i),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((s,i)=>dre(s,i),r)),e.offset!=null){const s=e.offset;let i=0;r=hb(r,()=>i++>=s)}return e.limit!=null&&(r=fre(r,e.limit)),r}}class hCt extends fCt{data;constructor(){super(),this.data=new Map}put(e,n,r){return r?.signal?.throwIfAborted(),this.data.set(e.toString(),n),e}get(e,n){n?.signal?.throwIfAborted();const r=this.data.get(e.toString());if(r==null)throw new C4;return r}has(e,n){return n?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,n){n?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,n){n?.signal?.throwIfAborted();for(const[r,s]of this.data.entries())yield{key:new Ho(r),value:s},n?.signal?.throwIfAborted()}*_allKeys(e,n){n?.signal?.throwIfAborted();for(const r of this.data.keys())yield new Ho(r),n?.signal?.throwIfAborted()}}class pCt extends Map{metric;constructor(e){super();const{name:n,metrics:r}=e;this.metric=r.registerMetric(n),this.updateComponentMetric()}set(e,n){return super.set(e,n),this.updateComponentMetric(),this}delete(e){const n=super.delete(e);return this.updateComponentMetric(),n}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function dp(t){const{name:e,metrics:n}=t;let r;return n!=null?r=new pCt({name:e,metrics:n}):r=new Map,r}const hre=864e13,gCt=448,h9=449,mCt=53,yCt=54,wCt=55,bCt=56;class vCt{log;mappings;constructor(e,n={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=dp({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const n=this.findHost(e);for(const r of this.mappings.values())if(r.domain===n)return!0;return!1}add(e,n){n.forEach(r=>{this.log("add DNS mapping %s to %s",r,e);const s=p8(r)===!0;this.mappings.set(r,{domain:e,verified:s,expires:s?hre-Date.now():0,lastVerified:s?hre-Date.now():void 0})})}remove(e){const n=this.findHost(e);let r=!1;for(const[s,i]of this.mappings.entries())i.domain===n&&(this.log("removing %s to %s DNS mapping %e",s,i.domain,new Error("where")),this.mappings.delete(s),r=r||i.verified);return r}getAll(e){const n=[];for(let r=0;r[IV(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return n}maybeAddSNITuple(e,n){for(let r=0;r[IV(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return n}confirm(e,n){const s=e.stringTuples()[0][1];let i=!1;for(const o of this.mappings.values())for(const a of o)a.externalIp===s&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),i=a.verified,a.verified=!0,a.expires=Date.now()+n,a.lastVerified=Date.now());return i}unconfirm(e,n){const r=e.stringTuples(),s=r[0][1]??"",i=r[1][0]===m9?"tcp":"udp",o=parseInt(r[1][1]??"0");let a=!1;for(const c of this.mappings.values())for(let l=0;l({multiaddr:er(e),verified:n.verified,type:"observed",expires:n.expires,lastVerified:n.lastVerified}))}remove(e){const n=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),n}confirm(e,n){const r=e.toString(),s=this.addresses.get(r)??{verified:!1,expires:Date.now()+n,lastVerified:Date.now()},i=s.verified;return s.verified=!0,s.expires=Date.now()+n,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",r),this.addresses.set(r,s),i}}const ACt=[_1,Zu,a8,c8,B3,l8];function pre(t){try{for(const{code:e}of t.getComponents())if(e!==xx)return ACt.includes(e)}catch{}return!1}const ICt={maxObservedAddresses:10};class TCt{log;addresses;maxObservedAddresses;constructor(e,n={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=dp({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=n.maxObservedAddresses??ICt.maxObservedAddresses}get(e,n){if(nS(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+n,lastVerified:Date.now()};const r=this.toKey(e);let s=this.addresses.get(r);return s==null&&(s={verified:!pre(e),expires:0},this.addresses.set(r,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){const n=this.toKey(e);return this.addresses.has(n)}remove(e){const n=this.toKey(e),r=this.addresses.get(n)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(n),r}confirm(e,n){const r=this.toKey(e),s=this.addresses.get(r)??{verified:!1,expires:0,lastVerified:0},i=s.verified;return s.verified=!0,s.expires=Date.now()+n,s.lastVerified=Date.now(),this.addresses.set(r,s),i}unconfirm(e,n){const r=this.toKey(e),s=this.addresses.get(r)??{verified:!1,expires:0},i=s.verified;return s.verified=!1,s.expires=Date.now()+n,this.addresses.set(r,s),i}toKey(e){if(pre(e)){const n=e.toOptions();return`${n.host}-${n.port}-${n.transport}`}return e.toString()}}const gre=6e4,mre={maxObservedAddresses:10,addressVerificationTTL:gre*10,addressVerificationRetry:gre*5},NCt=t=>t;function y9(t,e){const n=t.getPeerId();return n!=null&&yf(n).equals(e)&&(t=t.decapsulate(er(`/p2p/${e.toString()}`))),t}class PCt{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,n={}){const{listen:r=[],announce:s=[],appendAnnounce:i=[]}=n;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map(o=>o.toString()),this.announce=new Set(s.map(o=>o.toString())),this.appendAnnounce=new Set(i.map(o=>o.toString())),this.observed=new SCt(e,n),this.dnsMappings=new vCt(e,n),this.ipMappings=new ECt(e,n),this.transportAddresses=new TCt(e,n),this.announceFilter=n.announceFilter??NCt,this.observedAddressFilter=Iwe(1024),this.addressVerificationTTL=n.addressVerificationTTL??mre.addressVerificationTTL,this.addressVerificationRetry=n.addressVerificationRetry??mre.addressVerificationRetry,this._updatePeerStoreAddresses=pU(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAddresses().map(n=>n.getPeerId()===this.components.peerId.toString()?n.decapsulate(`/p2p/${this.components.peerId.toString()}`):n);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(n=>{this.log.error("error updating addresses",n)})}getListenAddrs(){return Array.from(this.listen).map(e=>er(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>er(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>er(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){const n=e.stringTuples(),r=`${n[0][1]}:${n[1][1]}`;this.observedAddressFilter.has(r)||(this.observedAddressFilter.add(r),e=y9(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,n){e=y9(e,this.components.peerId);let r=!0;(n?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,n?.ttl??this.addressVerificationTTL)&&r&&(r=!1),(n?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,n?.ttl??this.addressVerificationTTL)&&r&&(r=!1),(n?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,n?.ttl??this.addressVerificationTTL)&&r&&(r=!1),(n?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,n?.ttl??this.addressVerificationTTL),r=!1):!this.observed.confirm(e,n?.ttl??this.addressVerificationTTL)&&r&&(r=!1)),r||this._updatePeerStoreAddresses()}removeObservedAddr(e,n){e=y9(e,this.components.peerId);let r=!1;this.observed.has(e)&&!this.observed.remove(e)&&r&&(r=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,n?.ttl??this.addressVerificationRetry)&&r&&(r=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,n?.ttl??this.addressVerificationRetry)&&r&&(r=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,n?.ttl??this.addressVerificationRetry)&&r&&(r=!1),r&&this._updatePeerStoreAddresses()}getAddresses(){const e=new Set,n=this.getAddressesWithMetadata().filter(r=>{if(!r.verified)return!1;const s=r.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(r=>r.multiaddr);return this.announceFilter(n.map(r=>{const s=er(r);return s.getComponents().pop()?.value===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){const e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(e)}),e.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let n=[];n=n.concat(this.components.transportManager.getAddrs().map(s=>this.transportAddresses.get(s,this.addressVerificationTTL)));const r=this.getAppendAnnounceAddrs();return r.length>0&&(this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(r)}),n=n.concat(r.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),n=n.concat(this.observed.getAll()),n=n.concat(this.ipMappings.getAll(n)),n=n.concat(this.dnsMappings.getAll(n)),n}addDNSMapping(e,n){this.dnsMappings.add(e,n)}removeDNSMapping(e){this.dnsMappings.remove(er(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,n,r,s=n,i="tcp"){this.ipMappings.add(e,n,r,s,i),this.observed.removePrefixed(`/ip${zy(r)?4:6}/${r}/${i}/${s}`)}removePublicAddressMapping(e,n,r,s=n,i="tcp"){this.ipMappings.remove(er(`/ip${zy(r)?4:6}/${r}/${i}/${s}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;const n=e.toOptions();if(n.family===6||n.host==="127.0.0.1"||p8(n.host)===!0)return!1;const r=this.components.transportManager.getListeners(),s=[i=>sS.exactMatch(i)||iS.exactMatch(i),i=>y4.exactMatch(i),i=>Ext.exactMatch(i)];for(const i of s){if(!i(e))continue;const o=r.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&i(u)).length>0);if(o.length!==1)continue;const a=o[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;const c=a.toOptions();return this.observed.remove(e),this.ipMappings.add(c.host,c.port,n.host,n.port,n.transport),!0}return!1}}var yre;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.NOT_FOUND="Not found"})(yre||(yre={}));class kCt extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class RCt extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class w9 extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class wre extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class OCt extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class $Ct extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class DCt extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class bre extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class MCt extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class LCt extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class BCt extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class UCt extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class FCt extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class lI extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class uI extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class jCt extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class zCt{components={};_started=!1;constructor(e={}){this.components={};for(const[n,r]of Object.entries(e))this.components[n]=r;this.components.logger==null&&(this.components.logger=Ewe())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(n=>lV(n)).map(async n=>{await n[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const WCt=["metrics","connectionProtector","dns"],VCt=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function HCt(t={}){const e=new zCt(t);return new Proxy(e,{get(r,s,i){if(typeof s=="string"&&!VCt.includes(s)){const o=e.components[s];if(o==null&&!WCt.includes(s))throw new kCt(`${s} not set`);return o}return Reflect.get(r,s,i)},set(r,s,i){return typeof s=="string"?e.components[s]=i:Reflect.set(r,s,i),!0}})}function qCt(t){const e={};for(const n of Object.values(t.components))for(const r of KCt(n))e[r]=!0;for(const n of Object.values(t.components))for(const r of GCt(n))if(e[r]!==!0)throw new RCt(`Service "${ZCt(n)}" required capability "${r}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function KCt(t){return Array.isArray(t?.[lp])?t[lp]:[]}function GCt(t){return Array.isArray(t?.[Qte])?t[Qte]:[]}function ZCt(t){return t?.[Symbol.toStringTag]??t?.toString()??"unknown"}const YCt=4,XCt=41;function QCt(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(sS.matches(e))return!1;const n=e.stringTuples();return n[0][0]===YCt||n[0][0]===XCt?!!p8(`${n[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}function Gwe(t){if(Zm(t))return{peerId:t,multiaddrs:[]};let e=Array.isArray(t)?t:[t],n;if(e.length>0){const r=e[0].getPeerId();n=r==null?void 0:yf(r),e.forEach(s=>{if(!u8(s))throw new aV("Invalid multiaddr");const i=s.getPeerId();if(i==null){if(n!=null)throw new cr("Multiaddrs must all have the same peer id or have no peer id")}else{const o=yf(i);if(n?.equals(o)!==!0)throw new cr("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(r=>!bxt.exactMatch(r)),{peerId:n,multiaddrs:e}}const JCt=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function e_t(t,e){const n=t?.streams?.map(s=>s.protocol)??[],r=e?.closableProtocols??JCt;if(!(n.filter(s=>s!=null&&!r.includes(s)).length>0))try{await t?.close(e)}catch(s){t?.abort(s)}}async function t_t(t,e){let n=!1;for(const s of AV.keys())if(n=t.protoNames().includes(s),n)break;if(!n)return[t];const r=await t.resolve(e);return e.log("resolved %s to",t,r.map(s=>s.toString())),r}function vU(t){try{let e;if(typeof t=="string"?e=er(t):e=t,!e.protoNames().includes("ipcidr")){const r=e.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(r)}return evt(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${t}`)}}class n_t{connectionManager;peerStore;allow;events;log;constructor(e,n={}){this.allow=(n.allow??[]).map(r=>vU(r)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),n=e.length,r=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",n,r),n<=r)return;const s=new j3;for(const c of e){const l=c.remotePeer;if(!s.has(l)){s.set(l,0);try{const u=await this.peerStore.get(l);s.set(l,[...u.tags.values()].reduce((d,f)=>d+f.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}const i=this.sortConnections(e,s),o=Math.max(n-r,0),a=[];for(const c of i)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>u.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===o)break;await Promise.all(a.map(async c=>{await e_t(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,n){return e.sort((r,s)=>{const i=r.timeline.open,o=s.timeline.open;return io?-1:0}).sort((r,s)=>r.direction==="outbound"&&s.direction==="inbound"?1:r.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((r,s)=>r.streams.length>s.streams.length?1:r.streams.length{const i=n.get(r.remotePeer)??0,o=n.get(s.remotePeer)??0;return i>o?1:in&&r.signal?.aborted===!0,!0)&&(this.controller.abort(new b1),this.cleanup())}async join(e={}){const n=new u_t(e.signal);return this.recipients.push(n),e.signal?.addEventListener("abort",this.onAbort),n.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await Jo(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(n=>{n.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(n=>{n.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}}class Jwe extends Oo{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=pU(this.emitEmpty.bind(this),1),this.emitIdle=pU(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending{for(let n=0;n(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:r,result:s}}),s)).catch(s=>{if(r.status==="queued"){for(let i=0;i{e.abort(new b1)}),this.clear()}async onEmpty(e){this.size!==0&&await Ym(this,"empty",e?.signal)}async onSizeLessThan(e,n){this.sizethis.size{c!=null?this.abort():this.clear(),n.end(c)},s=c=>{c.detail!=null&&n.push(c.detail)},i=c=>{r(c.detail.error)},o=()=>{r()},a=()=>{r(new b1("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",i),this.addEventListener("idle",o),e?.signal?.addEventListener("abort",a);try{yield*n}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",i),this.removeEventListener("idle",o),e?.signal?.removeEventListener("abort",a),r()}}}class h_t extends Jwe{constructor(e={}){super({...e,sort:(n,r)=>n.options.priority>r.options.priority?-1:n.options.priority{r.detail?.name!==b1.name&&this.log.error("error in dial queue - %e",r.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,n={}){const{peerId:r,multiaddrs:s}=Gwe(e),i=Array.from(this.connections.values()).flat().find(a=>n.force===!0?!1:a.remotePeer.equals(r)?!0:s.find(c=>c.equals(a.remoteAddr)));if(i?.status==="open")return this.log("already connected to %a",i.remoteAddr),n.onProgress?.(new Ua("dial-queue:already-connected")),i;const o=this.queue.queue.find(a=>{if(r?.equals(a.options.peerId)===!0)return!0;const c=a.options.multiaddrs;if(c==null)return!1;for(const l of s)if(c.has(l.toString()))return!0;return!1});if(o!=null){this.log("joining existing dial target for %p",r);for(const a of s)o.options.multiaddrs.add(a.toString());return n.onProgress?.(new Ua("dial-queue:already-in-dial-queue")),o.join(n)}if(this.queue.size>=this.maxDialQueueLength)throw new BD("Dial queue is full");return this.log("creating dial target for %p",r,s.map(a=>a.toString())),n.onProgress?.(new Ua("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new Ua("dial-queue:start-dial"));const c=cS([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:r,priority:n.priority??tbe,multiaddrs:new Set(s.map(a=>a.toString())),signal:n.signal??AbortSignal.timeout(this.dialTimeout),onProgress:n.onProgress})}async dialPeer(e,n){const r=e.peerId,s=e.multiaddrs,i=new Set;let o=e.multiaddrs.size===0,a=0,c=0;const l=[];for(this.log("starting dial to %p",r);o||s.size>0;){c++,o=!1;const u=[],d=new Set(e.multiaddrs);s.clear(),this.log("calculating addrs to dial %p from %s",r,[...d]);const f=await this.calculateMultiaddrs(r,d,{...e,signal:n});for(const p of f){if(i.has(p.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",p.multiaddr,r);continue}u.push(p)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",r,u.map(p=>p.multiaddr.toString())),e?.onProgress?.(new Ua("dial-queue:calculated-addresses",u));for(const p of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new BD("Peer had more than maxPeerAddrsToDial");a++;try{const m=await this.components.transportManager.dial(p.multiaddr,{...e,signal:n});this.log("dial to %a succeeded",p.multiaddr);try{await this.components.peerStore.merge(m.remotePeer,{multiaddrs:[m.remoteAddr],metadata:{[c_t]:Jt(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p",r,y)}return m}catch(m){if(this.log.error("dial failed to %a",p.multiaddr,m),i.add(p.multiaddr.toString()),r!=null)try{await this.components.peerStore.merge(r,{metadata:{[a_t]:Jt(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p",r,y)}if(n.aborted)throw new Nme(m.message);l.push(m)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,n=new Set,r={}){const s=[...n].map(d=>({multiaddr:er(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new BD("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new bre("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{const d=await this.components.peerStore.get(e);s.push(...d.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:f})=>f.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(s.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{const d=await this.components.peerRouting.findPeer(e,r);this.log("found multiaddrs for %p in the peer routing",e,s.map(({multiaddr:f})=>f.toString())),s.push(...d.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(d){d.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,d)}}}let i=(await Promise.all(s.map(async d=>{const f=await t_t(d.multiaddr,{dns:this.components.dns,...r,log:this.log});return f.length===1&&f[0].equals(d.multiaddr)?d:f.map(p=>({multiaddr:p,isCertified:!1}))}))).flat();if(e!=null){const d=`/p2p/${e.toString()}`;i=i.map(f=>f.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:f.multiaddr.encapsulate(d),isCertified:f.isCertified}:f)}const o=i.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;const f=d.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(const d of o){const f=d.multiaddr.toString(),p=a.get(f);if(p!=null){p.isCertified=p.isCertified||d.isCertified||!1;continue}a.set(f,d)}const c=[...a.values()];if(c.length===0)throw new BCt("The dial request has no valid addresses");const l=[];for(const d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);const u=this.addressSorter==null?v_t(l):l.sort(this.addressSorter);if(u.length===0)throw new bre("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}async isDialable(e,n={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map(s=>s.toString())),n);return n.runOnLimitedConnection===!1?r.find(s=>!yU.matches(s.multiaddr))!=null:!0}catch(r){this.log.trace("error calculating if multiaddr(s) were dialable",r)}return!1}}class E_t extends Jwe{has(e){return this.find(e)!=null}find(e){return this.queue.find(n=>e.equals(n.options.peerId))}}var ebe={};function Zl(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var C_t=Zl;Zl.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Zl.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Zl.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0};Zl.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Zl.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};Zl.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};Zl.prototype.start=Zl.prototype.try;Zl.prototype.errors=function(){return this._errors};Zl.prototype.attempts=function(){return this._attempts};Zl.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,n=0,r=0;r=n&&(e=s,n=o)}return e};(function(t){var e=C_t;t.operation=function(n){var r=t.timeouts(n);return new e(r,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},t.timeouts=function(n){if(n instanceof Array)return[].concat(n);var r={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var s in n)r[s]=n[s];if(r.minTimeout>r.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],o=0;oA_t.call(t)==="[object Error]",T_t=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function N_t(t){return t&&I_t(t)&&t.name==="TypeError"&&typeof t.message=="string"?t.message==="Load failed"?t.stack===void 0:T_t.has(t.message):!1}class P_t extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const Ere=(t,e,n)=>{const r=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=r,t};async function k_t(t,e){return new Promise((n,r)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;const s=S_t.operation(e),i=()=>{s.stop(),r(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});const o=()=>{e.signal?.removeEventListener("abort",i),s.stop()};s.attempt(async a=>{try{const c=await t(a);o(),n(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof P_t)throw c.originalError;if(c instanceof TypeError&&!N_t(c))throw c;if(Ere(c,a,e),await e.shouldRetry(c)||(s.stop(),r(c)),await e.onFailedAttempt(c),!s.retry(c))throw s.mainError()}catch(l){Ere(l,a,e),o(),r(l)}}})})}class R_t{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,n={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new E_t({concurrency:n.maxParallelReconnects??o_t,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=n.retries??5,this.backoffFactor=n.backoffFactor,this.retryInterval=n.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",r=>{this.maybeReconnect(r.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",r.detail,s)})})}async maybeReconnect(e){if(!this.started)return;const n=await this.peerStore.get(e);Cre(n)&&(this.queue.has(e)||this.queue.add(async r=>{await k_t(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:r?.signal})}catch(i){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,i),i}},{signal:r?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async r=>{this.log.error("failed to reconnect to %p - %e",e,r);const s={};[...n.tags.keys()].forEach(i=>{i.startsWith(Ame)&&(s[i]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async r=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,r)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{const e=await this.peerStore.all({filters:[n=>Cre(n)]});await Promise.all(e.map(async n=>{await this.connectionManager.openConnection(n.id).catch(r=>{this.log.error(r)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}}function Cre(t){for(const e of t.tags.keys())if(e.startsWith(Ame))return!0;return!1}const tbe=50,b9={maxConnections:l_t,inboundConnectionThreshold:s_t,maxIncomingPendingConnections:i_t};class O_t{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,n={}){if(this.maxConnections=n.maxConnections??b9.maxConnections,this.maxConnections<1)throw new cr("Connection Manager maxConnections must be greater than 0");this.connections=new j3,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(n.allow??[]).map(r=>vU(r)),this.deny=(n.deny??[]).map(r=>vU(r)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=n.maxIncomingPendingConnections??b9.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new awe({points:n.inboundConnectionThreshold??b9.inboundConnectionThreshold,duration:1}),this.connectionPruner=new n_t({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:n.allow?.map(r=>er(r))}),this.dialQueue=new x_t(e,{addressSorter:n.addressSorter,maxParallelDials:n.maxParallelDials??Qwe,maxDialQueueLength:n.maxDialQueueLength??Xwe,maxPeerAddrsToDial:n.maxPeerAddrsToDial??Ywe,dialTimeout:n.dialTimeout??Zwe,resolvers:n.resolvers??{dnsaddr:MV},connections:this.connections}),this.reconnectQueue=new R_t({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:n.reconnectRetries,retryInterval:n.reconnectRetryInterval,backoffFactor:n.reconnectBackoffFactor,maxParallelReconnects:n.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const n of this.connections.values())for(const r of n)e[r.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const n of this.connections.values())for(const r of n)for(const s of r.streams){const i=`${s.direction} ${s.protocol??"unnegotiated"}`;e[i]=(e[i]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const r of this.connections.values())for(const s of r){const i={};for(const o of s.streams){const a=`${o.direction} ${o.protocol??"unnegotiated"}`;i[a]=(i[a]??0)+1}for(const[o,a]of Object.entries(i))e[o]=e[o]??[],e[o].push(a)}const n={};for(let[r,s]of Object.entries(e)){s=s.sort((o,a)=>o-a);const i=Math.floor(s.length*.9);n[r]=s[i]}return n}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Dmt(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Mmt(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const n of this.connections.values())for(const r of n)e.push((async()=>{try{await r.close()}catch(s){this.log.error(s)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new cr("Connection Manager maxConnections must be greater than 0");let n=!1;e{this.log.error(n)})}async _onConnect(e){const{detail:n}=e;if(!this.started){await n.close();return}if(n.status!=="open")return;const r=n.remotePeer,s=!this.connections.has(r),i=this.connections.get(r)??[];i.push(n),this.connections.set(r,i),r.publicKey!=null&&r.type==="RSA"&&await this.peerStore.patch(r,{publicKey:r.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:n.remotePeer})}onDisconnect(e){const{detail:n}=e,r=n.remotePeer,i=(this.connections.get(r)??[]).filter(o=>o.id!==n.id);this.connections.set(r,i),i.length===0&&(this.log("onDisconnect remove all connections for peer %p",r),this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:n.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let n=[];for(const r of this.connections.values())n=n.concat(r);return n}getConnectionsMap(){return this.connections}async openConnection(e,n={}){if(!this.started)throw new r4("Not started");this.outboundPendingConnections++;try{n.signal?.throwIfAborted();const{peerId:r}=Gwe(e);if(this.peerId.equals(r))throw new Tme("Can not dial self");if(r!=null&&n.force!==!0){this.log("dial %p",r);const a=this.getConnections(r).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",r),n.onProgress?.(new Ua("dial-queue:already-connected")),a}const s=await this.dialQueue.dial(e,{...n,priority:n.priority??tbe});if(s.status!=="open")throw new Ime("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let o=!1;for(const a of i)if(a.id===s.id&&(o=!0),n.force!==!0&&a.id!==s.id&&a.remoteAddr.equals(s.remoteAddr))return s.abort(new aV("Duplicate multiaddr connection")),a;return o||i.push(s),s}finally{this.outboundPendingConnections--}}async closeConnections(e,n={}){const r=this.connections.get(e)??[];await Promise.all(r.map(async s=>{try{await s.close(n)}catch(i){s.abort(i)}}))}async acceptIncomingConnection(e){if(this.deny.some(s=>s.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(s=>s.contains(e.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const s=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(s,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s),!1}}return this.getConnections().length({id:n.id,status:e[n.status],peerId:n.options.peerId,multiaddrs:[...n.options.multiaddrs].map(r=>er(r))}))}async isDialable(e,n={}){return this.dialQueue.isDialable(e,n)}}class v9{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,n){return 1-Math.exp(-(e-n)/this.timeSpan)}push(e,n=Date.now()){if(this.previousTime!=null){const r=this.alpha(n,this.previousTime),s=e-this.movingAverage,i=r*s;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+s*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*s}else this.movingAverage=e;this.previousTime=n}}const $_t=1.2,D_t=2,M_t=5e3,L_t=6e4,B_t=5e3;class U_t{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const n=e.interval??B_t;this.success=new v9(n),this.failure=new v9(n),this.next=new v9(n),this.failureMultiplier=e.failureMultiplier??D_t,this.timeoutMultiplier=e.timeoutMultiplier??$_t,this.minTimeout=e.minTimeout??M_t,this.maxTimeout=e.maxTimeout??L_t,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let n=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));nthis.maxTimeout&&(n=this.maxTimeout);const r=AbortSignal.timeout(n),s=cS([e.signal,r]);return s.start=Date.now(),s.timeout=n,s}cleanUp(e){const n=Date.now()-e.start;e.aborted?(this.failure.push(n),this.next.push(n*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:n})):(this.success.push(n),this.next.push(n),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:n}))}}const F_t=1e4,j_t="1.0.0",z_t="ping",W_t="ipfs",_re=32,V_t=!0;class H_t{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,n={}){this.components=e,this.protocol=`/${n.protocolPrefix??W_t}/${z_t}/${j_t}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=n.pingInterval??F_t,this.abortConnectionOnPingFailure=n.abortConnectionOnPingFailure??V_t,this.timeout=new U_t({...n.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[lp]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let n=Date.now();try{const r=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),s=await e.newStream(this.protocol,{signal:r,runOnLimitedConnection:!0}),i=l4(s);n=Date.now(),await Promise.all([i.write(yV(_re),{signal:r}),i.read({bytes:_re,signal:r})]),e.rtt=Date.now()-n,await i.unwrap().close({signal:r})}catch(r){if(r.name!=="UnsupportedProtocolError")throw r;e.rtt=(Date.now()-n)/2}}).catch(n=>{this.log.error("error during heartbeat",n),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(n)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}}class q_t{routers;started;components;constructor(e,n){this.routers=n.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([r],s)=>({...s,cid:r.toString()}),getAttributesFromYieldedValue:(r,s)=>({...s,providers:[...Array.isArray(s.providers)?s.providers:[],r.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([r],s)=>({...s,cid:r.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([r],s)=>({...s,cid:r.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([r])=>({key:hn(r,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([r])=>({key:hn(r,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,n={}){if(this.routers.length===0)throw new w9("No content routers available");const r=this,s=new yv;for await(const i of t4(...r.routers.filter(o=>o.findProviders instanceof Function).map(o=>o.findProviders(e,n))))i!=null&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},n),!s.has(i.id)&&(s.add(i.id),yield i))}async provide(e,n={}){if(this.routers.length===0)throw new w9("No content routers available");await Promise.all(this.routers.filter(r=>r.provide instanceof Function).map(async r=>{await r.provide(e,n)}))}async cancelReprovide(e,n={}){if(this.routers.length===0)throw new w9("No content routers available");await Promise.all(this.routers.filter(r=>r.cancelReprovide instanceof Function).map(async r=>{await r.cancelReprovide(e,n)}))}async put(e,n,r){if(!this.isStarted())throw new r4;await Promise.all(this.routers.filter(s=>s.put instanceof Function).map(async s=>{await s.put(e,n,r)}))}async get(e,n){if(!this.isStarted())throw new r4;return Promise.any(this.routers.filter(r=>r.get instanceof Function).map(async r=>r.get(e,n)))}}class K_t{log;peerId;peerStore;routers;constructor(e,n={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=n.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([r],s)=>({...s,peer:r.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([r],s)=>({...s,key:hn(r,"base36")}),getAttributesFromYieldedValue:(r,s)=>({...s,peers:[...Array.isArray(s.peers)?s.peers:[],r.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,n){if(this.routers.length===0)throw new wre("No peer routers available");if(e.toString()===this.peerId.toString())throw new OCt("Should not try to find self");const r=this,s=t4(...this.routers.filter(i=>i.findPeer instanceof Function).map(i=>async function*(){try{yield await i.findPeer(e,n)}catch(o){r.log.error(o)}}()));for await(const i of s)if(i!=null)return i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},n),i;throw new ZB}async*getClosestPeers(e,n={}){if(this.routers.length===0)throw new wre("No peer routers available");const r=this,s=Iwe(1024);for await(const i of J1t(async function*(){const o=t4(...r.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,n)));for await(let a of o)yield async()=>{if(a.multiaddrs.length===0)try{a=await r.findPeer(a.id,{...n,useCache:!1})}catch(c){r.log.error("could not find peer multiaddrs",c);return}return a}}()))i!=null&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},n),!s.has(i.id.toMultihash().bytes)&&(s.add(i.id.toMultihash().bytes),yield i))}}class G_t extends Oo{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const n=cS([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=qs(),yield(await Ym(this,"walk:peer",n,{errorEvent:"walk:error"})).detail}finally{n.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=cS([this.walkController.signal,this.shutdownController.signal]),n=Date.now();let r=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{const s=yV(32);let i=Date.now();for await(const o of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",o.id,Date.now()-i,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:o}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Jo(this.needNext.promise,e)),i=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,r)}catch(s){this.log.error("random walk errored",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("random walk errored",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-n),this.walking=!1})}}const nbe=32,rbe=64;class Z_t{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const n={};for(const[r,s]of this.topologies)n[r]=s.size;return n}}),this.handlers=dp({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const n=this.handlers.get(e);if(n==null)throw new $Ct(`No handler registered for protocol ${e}`);return n}getTopologies(e){const n=this.topologies.get(e);return n==null?[]:[...n.values()]}async handle(e,n,r){if(this.handlers.has(e)&&r?.force!==!0)throw new DCt(`Handler already registered for protocol ${e}`);const s=gwe.bind({ignoreUndefined:!0})({maxInboundStreams:nbe,maxOutboundStreams:rbe},r);this.handlers.set(e,{handler:n,options:s}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},r)}async unhandle(e,n){(Array.isArray(e)?e:[e]).forEach(s=>{this.handlers.delete(s)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},n)}async register(e,n){if(n==null)throw new cr("invalid topology");const r=`${(Math.random()*1e9).toString(36)}${Date.now()}`;let s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.set(r,n),r}unregister(e){for(const[n,r]of this.topologies.entries())r.has(e)&&(r.delete(e),r.size===0&&this.topologies.delete(n))}_onDisconnect(e){const n=e.detail,r={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(n,r).then(s=>{for(const i of s.protocols){const o=this.topologies.get(i);if(o!=null)for(const a of o.values())a.filter?.has(n)!==!1&&(a.filter?.remove(n),a.onDisconnect?.(n))}}).catch(s=>{s.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",n,s)})}_onPeerUpdate(e){const{peer:n,previous:r}=e.detail,s=(r?.protocols??[]).filter(i=>!n.protocols.includes(i));for(const i of s){const o=this.topologies.get(i);if(o!=null)for(const a of o.values())a.filter?.has(n.id)!==!1&&(a.filter?.remove(n.id),a.onDisconnect?.(n.id))}}_onPeerIdentify(e){const n=e.detail.protocols,r=e.detail.connection,s=e.detail.peerId;for(const i of n){const o=this.topologies.get(i);if(o!=null)for(const a of o.values())r.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),a.onConnect?.(s,r))}}}class Y_t{log;components;transports;listeners;faultTolerance;started;constructor(e,n={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=dp({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=dp({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=n.faultTolerance??q_.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const n=e[Symbol.toStringTag];if(n==null)throw new cr("Transport must have a valid tag");if(this.transports.has(n))throw new cr(`There is already a transport with the tag ${n}`);this.log("adding transport %s",n),this.transports.set(n,e),this.listeners.has(n)||this.listeners.set(n,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[n,r]of this.listeners)for(this.log("closing listeners for %s",n);r.length>0;){const s=r.pop();s!=null&&e.push(s.close())}await Promise.all(e),this.log("all listeners closed");for(const n of this.listeners.keys())this.listeners.set(n,[]);this.started=!1}async dial(e,n){const r=this.dialTransportForMultiaddr(e);if(r==null)throw new jCt(`No transport available for address ${String(e)}`);return n?.onProgress?.(new Ua("transport-manager:selected-transport",r[Symbol.toStringTag])),r.dial(e,{...n,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(const n of this.listeners.values())for(const r of n)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const n of this.transports.values())if(n.dialFilter([e]).length>0)return n}listenTransportForMultiaddr(e){for(const n of this.transports.values())if(n.listenFilter([e]).length>0)return n}async listen(e){if(!this.isStarted())throw new r4("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}const n={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(i=>{n.errors.set(i.toString(),new MCt)});const r=[];for(const[i,o]of this.transports.entries()){const a=o.listenFilter(e);for(const c of a){this.log("creating listener for %s on %a",i,c);const l=o.createListener({upgrader:this.components.upgrader});let u=this.listeners.get(i)??[];u==null&&(u=[],this.listeners.set(i,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{const d=u.findIndex(f=>f===l);u.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Bne.matches(c)?n.ipv4.attempts++:Une.matches(c)&&n.ipv6.attempts++,r.push(l.listen(c).then(()=>{n.errors.delete(c.toString()),Bne.matches(c)&&n.ipv4.success++,Une.matches(c)&&n.ipv6.success++},d=>{throw this.log.error("transport %s could not listen on address %a - %e",i,c,d),n.errors.set(c.toString(),d),d}))}}const s=await Promise.allSettled(r);if(!(s.length>0&&s.every(i=>i.status==="fulfilled"))){if(this.ipv6Unsupported(n)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===q_.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new LCt(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL: +${[...n.errors.entries()].map(([i,o])=>` + ${i}: ${`${o.stack??o}`.split(` +`).join(` + `)} +`).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;const n=e.ipv4.attempts===e.ipv4.success,r=e.ipv6.success===0;return n&&r}async remove(e){const n=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);n.length>0;){const s=n.pop();s!=null&&r.push(s.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const n of this.transports.keys())e.push(this.remove(n));await Promise.all(e)}}const Oa="/multistream/1.0.0",UV=1024,X_t=Jt(` +`);async function Q2(t,e,n){await t.write(e,n)}async function Q_t(t,e,n){await t.writeV(e,n)}async function J_t(t,e){const n=await t.read(e);if(n.byteLength===0||n.get(n.byteLength-1)!==X_t[0])throw e.log.error("Invalid mss message - missing newline",n),new qd("Missing newline");return n.sublist(0,-1)}async function wv(t,e){const n=await J_t(t,e);return hn(n.subarray())}async function x9(t,e,n){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&n.negotiateFully===!1)return eSt(t,e[0],n);const r=S1(t,{...n,maxDataLength:UV}),s=e.shift();if(s==null)throw new Error("At least one protocol must be specified");n.log.trace('select: write ["%s", "%s"]',Oa,s);const i=Jt(`${Oa} +`),o=Jt(`${s} +`);await Q_t(r,[i,o],n),n.log.trace("select: reading multistream-select header");let a=await wv(r,n);if(n.log.trace('select: read "%s"',a),a===Oa&&(n.log.trace("select: reading protocol response"),a=await wv(r,n),n.log.trace('select: read "%s"',a)),a===s)return{stream:r.unwrap(),protocol:s};for(const c of e){n.log.trace('select: write "%s"',c),await Q2(r,Jt(`${c} +`),n),n.log.trace("select: reading protocol response");const l=await wv(r,n);if(n.log.trace('select: read "%s" for "%s"',l,c),l===c)return{stream:r.unwrap(),protocol:c}}throw new cV("protocol selection failed")}function eSt(t,e,n){const r=t.sink.bind(t),s=t.source;let i=!1,o=!1;const a=qs();let c=!1,l=!1;const u=qs();let d=!1,f=!1;const p=qs(),m=S1({sink:r,source:s},{...n,maxDataLength:UV});t.sink=async x=>{const{sink:E}=m.unwrap();await E(async function*(){let A=!1;for await(const _ of x){if(l&&await u.promise,c)yield _;else{l=!0,n.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Oa,e,_.byteLength);const k=`${e} +`;yield new mn(Uint8Array.from([19]),Jt(`${Oa} +`),rf(k.length),Jt(k),_).subarray(),n.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Oa,e,_.byteLength),c=!0,l=!1,u.resolve(),y().catch(B=>{n.log.error("could not finish optimistic protocol negotiation of %s",e,B)})}A=!0}A||await y()}())};async function y(){if(o){n.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}o=!0;try{c||(n.log.trace("optimistic: doing send protocol for %s stream",e),await b()),d||(n.log.trace("optimistic: doing read protocol for %s stream",e),await v())}finally{o=!1,i=!0,a.resolve()}}async function b(){if(l){await u.promise;return}l=!0;try{n.log.trace('optimistic: write ["%s", "%s", data] in source',Oa,e),await m.writeV([Jt(`${Oa} +`),Jt(`${e} +`)]),n.log.trace('optimistic: wrote ["%s", "%s", data] in source',Oa,e)}finally{c=!0,l=!1,u.resolve()}}async function v(){if(f){await p.promise;return}f=!0;try{n.log.trace("optimistic: reading multistream select header");let x=await wv(m,n);if(n.log.trace('optimistic: read multistream select header "%s"',x),x===Oa&&(x=await wv(m,n)),n.log.trace('optimistic: read protocol "%s", expecting "%s"',x,e),x!==e)throw new cV("protocol selection failed")}finally{d=!0,f=!1,p.resolve()}}if(t.source=async function*(){await y(),n.log.trace('optimistic: reading data from "%s" stream',e),yield*m.unwrap().source}(),t.closeRead!=null){const x=t.closeRead.bind(t);t.closeRead=async E=>{i||await y().catch(A=>{n.log.error("could not negotiate protocol before close read",A)}),await x(E)}}if(t.closeWrite!=null){const x=t.closeWrite.bind(t);t.closeWrite=async E=>{i||await y().catch(A=>{n.log.error("could not negotiate protocol before close write",A)}),await x(E)}}if(t.close!=null){const x=t.close.bind(t);t.close=async E=>{const A=[];l&&A.push(u.promise),f&&A.push(p.promise),A.length>0?await Jo(Promise.all(A),E?.signal):(i=!0,o=!1,a.resolve()),await x(E)}}return{stream:t,protocol:e}}async function E9(t,e,n){e=Array.isArray(e)?e:[e],n.log.trace("handle: available protocols %s",e);const r=S1(t,{...n,maxDataLength:UV,maxLengthLength:2});for(;;){n.log.trace("handle: reading incoming string");const s=await wv(r,n);if(n.log.trace('handle: read "%s"',s),s===Oa){n.log.trace('handle: respond with "%s" for "%s"',Oa,s),await Q2(r,Jt(`${Oa} +`),n),n.log.trace('handle: responded with "%s" for "%s"',Oa,s);continue}if(e.includes(s))return n.log.trace('handle: respond with "%s" for "%s"',s,s),await Q2(r,Jt(`${s} +`),n),n.log.trace('handle: responded with "%s" for "%s"',s,s),{stream:r.unwrap(),protocol:s};if(s==="ls"){const i=new mn(...e.map(o=>NV.single(Jt(`${o} +`))),Jt(` +`));n.log.trace('handle: respond with "%s" for %s',e,s),await Q2(r,i,n),n.log.trace('handle: responded with "%s" for %s',e,s);continue}n.log.trace('handle: respond with "na" for "%s"',s),await Q2(r,Jt(`na +`),n),n.log('handle: responded with "na" for "%s"',s)}}const tSt=500;class nSt{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:n,remotePeer:r,newStream:s,close:i,abort:o,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=n,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=s,this._close=i,this._abort=o,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Emt]=!0;get streams(){return this._getStreams()}async newStream(e,n){if(this.status==="closing")throw new Amt("the connection is being closed");if(this.status==="closed")throw new Ime("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&n?.runOnLimitedConnection!==!0)throw new Pme("Cannot open protocol stream on limited connection");const r=await this._newStream(e,n);return r.direction="outbound",r}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){const n=AbortSignal.timeout(tSt);e={...e,signal:n}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(n){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,n),this.abort(n)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}}function rSt(t){return new nSt(t)}function sSt(t,e){try{const{options:n}=e.getHandler(t);return n.maxInboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return nbe}function iSt(t,e,n={}){try{const{options:r}=e.getHandler(t);if(r.maxOutboundStreams!=null)return r.maxOutboundStreams}catch(r){if(r.name!=="UnhandledProtocolError")throw r}return n.maxOutboundStreams??rbe}function Sre(t,e,n){let r=0;return n.streams.forEach(s=>{s.direction===e&&s.protocol===t&&r++}),r}class oSt{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,n){this.components=e,this.connectionEncrypters=dp({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),n.connectionEncrypters.forEach(r=>{this.connectionEncrypters.set(r.protocol,r)}),this.streamMuxers=dp({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),n.streamMuxers.forEach(r=>{this.streamMuxers.set(r.protocol,r)}),this.inboundUpgradeTimeout=n.inboundUpgradeTimeout??r_t,this.inboundStreamProtocolNegotiationTimeout=n.inboundStreamProtocolNegotiationTimeout??vre,this.outboundStreamProtocolNegotiationTimeout=n.outboundStreamProtocolNegotiationTimeout??vre,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...n){const r=this.components.connectionGater[e];if(r==null)return;if(await r.apply(this.components.connectionGater,n)===!0)throw new UCt(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){return cS([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}async upgradeInbound(e,n){let r=!1;const s=this.createInboundAbortSignal(n.signal);try{if(this.metrics.dials?.increment({inbound:!0}),r=await Jo(this.components.connectionManager.acceptIncomingConnection(e),s),!r)throw new FCt("Connection denied");await Jo(this.shouldBlockConnection("denyInboundConnection",e),s),await this._performUpgrade(e,"inbound",{...n,signal:s})}catch(i){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[i.name??"Error"]:!0}),i}finally{s.clear(),r&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,n){try{this.metrics.dials?.increment({outbound:!0});const r=e.remoteAddr.getPeerId();let s;r!=null&&(s=yf(r),await Jo(this.shouldBlockConnection("denyOutboundConnection",s,e),n.signal));let i="outbound";return n.initiator===!1&&(i="inbound"),await this._performUpgrade(e,i,n)}catch(r){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[r.name??"Error"]:!0}),r}}async _performUpgrade(e,n,r){let s,i,o,a,c;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",n);let l=e;if(r?.skipProtection!==!0){const u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",n),l=await u.protect(e,r))}try{if(s=l,r?.skipEncryption!==!0){r?.onProgress?.(new Ua(`upgrader:encrypt-${n}-connection`)),{conn:s,remotePeer:i,protocol:c,streamMuxer:a}=await(n==="inbound"?this._encryptInbound(l,r):this._encryptOutbound(l,r));const u={...l,...s};await this.shouldBlockConnection(n==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",i,u)}else{const u=e.remoteAddr.getPeerId();if(u==null)throw new aV(`${n} connection that skipped encryption must have a peer id`);const d=yf(u);c="native",i=d}if(i.equals(this.components.peerId)){const u=new Tme("Can not dial self");throw e.abort(u),u}if(o=s,r?.muxerFactory!=null)a=r.muxerFactory;else if(a==null&&this.streamMuxers.size>0){r?.onProgress?.(new Ua(`upgrader:multiplex-${n}-connection`));const u=await(n==="inbound"?this._multiplexInbound({...l,...s},this.streamMuxers,r):this._multiplexOutbound({...l,...s},this.streamMuxers,r));a=u.muxerFactory,o=u.stream}}catch(u){throw e.log.error("failed to upgrade inbound connection %s %a - %e",n==="inbound"?"from":"to",e.remoteAddr,u),u}return await this.shouldBlockConnection(n==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",i,e),e.log("successfully upgraded %s connection",n),this._createConnection({cryptoProtocol:c,direction:n,maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:i,limits:r?.limits})}_createConnection(e){const{cryptoProtocol:n,direction:r,maConn:s,upgradedConn:i,remotePeer:o,muxerFactory:a,limits:c}=e;let l,u,d;a!=null&&(l=a.createStreamMuxer({direction:r,onIncomingStream:m=>{if(d==null)return;const y=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{const b=this.components.registrar.getProtocols(),{stream:v,protocol:x}=await E9(m,b,{signal:y,log:m.log,yieldBytes:!1});if(d==null)return;d.log("incoming stream opened on %s",x);const E=sSt(x,this.components.registrar);if(Sre(x,"inbound",d)===E){const _=new $mt(`Too many inbound protocol streams for protocol "${x}" - limit ${E}`);throw m.abort(_),_}m.source=v.source,m.sink=v.sink,m.protocol=x,v.closeWrite!=null&&(m.closeWrite=v.closeWrite),v.closeRead!=null&&(m.closeRead=v.closeRead),v.close!=null&&(m.close=v.close),await this.components.peerStore.merge(o,{protocols:[x]},{signal:y}),this.components.metrics?.trackProtocolStream(m,d),this._onStream({connection:d,stream:m,protocol:x})}).catch(async b=>{d.log.error("error handling incoming stream id %s - %e",m.id,b),m.timeline.close==null&&await m.close({signal:y}).catch(v=>m.abort(v))})}}),u=async(m,y={})=>{if(l==null)throw new lI("Connection is not multiplexed");d.log.trace("starting new stream for protocols %s",m);const b=await l.newStream();d.log.trace("started new stream %s for protocols %s",b.id,m);try{if(y.signal==null){b.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",m);const _=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);y={...y,signal:_}}b.log.trace("selecting protocol from protocols %s",m);const{stream:v,protocol:x}=await x9(b,m,{...y,log:b.log,yieldBytes:!0});b.log.trace("selected protocol %s",x);const E=iSt(x,this.components.registrar,y),A=Sre(x,"outbound",d);if(A>=E){const _=new kme(`Too many outbound protocol streams for protocol "${x}" - ${A}/${E}`);throw b.abort(_),_}return await this.components.peerStore.merge(o,{protocols:[x]}),b.source=v.source,b.sink=v.sink,b.protocol=x,v.closeWrite!=null&&(b.closeWrite=v.closeWrite),v.closeRead!=null&&(b.closeRead=v.closeRead),v.close!=null&&(b.close=v.close),this.components.metrics?.trackProtocolStream(b,d),b}catch(v){throw d.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",r==="inbound"?"from":"to",e.maConn.remoteAddr,m,v),b.timeline.close==null&&b.abort(v),v}},Promise.all([l.sink(i.source),i.sink(l.source)]).catch(m=>{d.log.error("error piping data through muxer - %e",m)}));const f=s.timeline;s.timeline=new Proxy(f,{set:(...m)=>(m[1]==="close"&&m[2]!=null&&f.close==null&&(async()=>{try{d.status==="open"&&await d.close()}catch(y){d.log.error("error closing connection after timeline close %e",y)}finally{this.events.safeDispatchEvent("connection:close",{detail:d})}})().catch(y=>{d.log.error("error thrown while dispatching connection:close event %e",y)}),Reflect.set(...m))}),s.timeline.upgraded=Date.now();const p=()=>{throw new lI("Connection is not multiplexed")};return d=rSt({remoteAddr:s.remoteAddr,remotePeer:o,status:"open",direction:r,timeline:s.timeline,multiplexer:l?.protocol,encryption:n,limits:c,logger:this.components.logger,newStream:u??p,getStreams:()=>l?.streams??[],close:async m=>{await l?.close(m),await s.close(m)},abort:m=>{s.abort(m),l?.abort(m)}}),this.events.safeDispatchEvent("connection:open",{detail:d}),d.__maConnTimeline=f,d}_onStream(e){const{connection:n,stream:r,protocol:s}=e,{handler:i,options:o}=this.components.registrar.getHandler(s);if(n.limits!=null&&o.runOnLimitedConnection!==!0)throw new Pme("Cannot open protocol stream on limited connection");i({connection:n,stream:r})}async _encryptInbound(e,n){const r=Array.from(this.connectionEncrypters.keys());try{const{stream:s,protocol:i}=await E9(e,r,{...n,log:e.log}),o=this.connectionEncrypters.get(i);if(o==null)throw new uI(`no crypto module found for ${i}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,i),{...await o.secureInbound(s,n),protocol:i}}catch(s){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,s),new uI(s.message)}}async _encryptOutbound(e,n){const r=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);const{stream:s,protocol:i}=await x9(e,r,{...n,log:e.log,yieldBytes:!0}),o=this.connectionEncrypters.get(i);if(o==null)throw new uI(`no crypto module found for ${i}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,i),{...await o.secureOutbound(s,n),protocol:i}}catch(s){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,s),new uI(s.message)}}async _multiplexOutbound(e,n,r){const s=Array.from(n.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);const{stream:i,protocol:o}=await x9(e,s,{...r,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",o);const a=n.get(o);return{stream:i,muxerFactory:a}}catch(i){throw e.log.error("error multiplexing outbound connection",i),new lI(String(i))}}async _multiplexInbound(e,n,r){const s=Array.from(n.keys());e.log("inbound handling muxers %s",s);try{const{stream:i,protocol:o}=await E9(e,s,{...r,log:e.log}),a=n.get(o);return{stream:i,muxerFactory:a}}catch(i){throw e.log.error("error multiplexing inbound connection",i),new lI(String(i))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}const sbe="2.8.11",ibe="js-libp2p";function aSt(t,e){return`${t??ibe}/${e??sbe} browser/${globalThis.navigator.userAgent}`}class cSt extends Oo{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const n=new Oo,r=n.dispatchEvent.bind(n);n.dispatchEvent=l=>{const u=r(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??Ewe(),this.log=this.logger.forComponent("libp2p"),this.services={};const s=e.nodeInfo?.name??ibe,i=e.nodeInfo?.version??sbe,o=this.components=HCt({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:s,version:i,userAgent:e.nodeInfo?.userAgent??aSt(s,i)},logger:this.logger,events:n,datastore:e.datastore??new hCt,connectionGater:QCt(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",aCt(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),o.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){const u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new oSt(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Y_t(this.components,e.transportManager)),this.configureComponent("connectionManager",new O_t(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new H_t(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Z_t(this.components)),this.configureComponent("addressManager",new PCt(this.components,e.addresses));const a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new K_t(this.components,{routers:a}));const c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new q_t(this.components,{routers:c})),this.configureComponent("randomWalk",new G_t(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(const l of Object.keys(e.services)){const u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[Yte]!=null&&(this.log("registering service %s for content routing",l),c.push(d[Yte])),d[Xte]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[Xte])),d[H_]!=null&&(this.log("registering service %s for peer discovery",l),d[H_].addEventListener?.("peer",f=>{this.#e(f)}))}qCt(o)}configureComponent(e,n){return n==null&&this.log.error("component %s was null or undefined",e),this.components[e]=n,n}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new yv;for(const n of this.components.connectionManager.getConnections())e.add(n.remotePeer);return Array.from(e)}async dial(e,n={}){return this.components.connectionManager.openConnection(e,{priority:75,...n})}async dialProtocol(e,n,r={}){if(n==null)throw new cr("no protocols were provided to open a stream");if(n=Array.isArray(n)?n:[n],n.length===0)throw new cr("no protocols were provided to open a stream");return(await this.dial(e,r)).newStream(n,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,n={}){u8(e)&&(e=yf(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,n)}async getPublicKey(e,n={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{const o=await this.peerStore.get(e,n);if(o.id.publicKey!=null)return o.id.publicKey}catch(o){if(o.name!=="NotFoundError")throw o}const r=Uy([Jt("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(r,n),i=x0(s);return await this.peerStore.patch(e,{publicKey:i},n),i}async handle(e,n,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,n,r)}))}async unhandle(e,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async r=>{await this.components.registrar.unhandle(r,n)}))}async register(e,n,r){return this.components.registrar.register(e,n,r)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,n={}){return this.components.connectionManager.isDialable(e,n)}#e(e){const{detail:n}=e;if(n.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(n.id,{multiaddrs:n.multiaddrs}).catch(r=>{this.log.error(r)})}}async function lSt(t={}){t.privateKey??=await $wt();const e=new cSt({...await rEt(t),peerId:Uwt(t.privateKey)});return t.start!==!1&&await e.start(),e}function Are(){try{return process?.env?.NODE_ENV==="test"}catch{return!1}}const Ire={SANDBOX:"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",TEST:"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"},Tre=xh.BOOTSTRAP,uSt=50,dSt=1e8,a6="Invalid record id",_4=2;var obe={exports:{}};/** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.9.3 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2023 + * @license MIT + */(function(t){(function(){var e="input is invalid type",n="finalize already called",r=typeof window=="object",s=r?window:{};s.JS_SHA3_NO_WINDOW&&(r=!1);var i=!r&&typeof self=="object",o=!s.JS_SHA3_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;o?s=kr:i&&(s=self);for(var a=!s.JS_SHA3_NO_COMMON_JS&&!0&&t.exports,c=!s.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",l="0123456789abcdef".split(""),u=[31,7936,2031616,520093696],d=[4,1024,262144,67108864],f=[1,256,65536,16777216],p=[6,1536,393216,100663296],m=[0,8,16,24],y=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],b=[224,256,384,512],v=[128,256],x=["hex","buffer","arrayBuffer","array","digest"],E={128:168,256:136},A=s.JS_SHA3_NO_NODE_JS||!Array.isArray?function(V){return Object.prototype.toString.call(V)==="[object Array]"}:Array.isArray,_=c&&(s.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)?function(V){return typeof V=="object"&&V.buffer&&V.buffer.constructor===ArrayBuffer}:ArrayBuffer.isView,k=function(V){var we=typeof V;if(we==="string")return[V,!0];if(we!=="object"||V===null)throw new Error(e);if(c&&V.constructor===ArrayBuffer)return[new Uint8Array(V),!1];if(!A(V)&&!_(V))throw new Error(e);return[V,!1]},B=function(V){return k(V)[0].length===0},W=function(V){for(var we=[],Ae=0;Ae>5,this.byteCount=this.blockCount<<2,this.outputBlocks=Ae>>5,this.extraBytes=(Ae&31)>>3;for(var Ie=0;Ie<50;++Ie)this.s[Ie]=0}oe.prototype.update=function(V){if(this.finalized)throw new Error(n);var we=k(V);V=we[0];for(var Ae=we[1],Ie=this.blocks,ge=this.byteCount,Me=V.length,be=this.blockCount,pe=0,J=this.s,ie,ae;pe>2]|=ae<>2]|=(192|ae>>6)<>2]|=(128|ae&63)<=57344?(Ie[ie>>2]|=(224|ae>>12)<>2]|=(128|ae>>6&63)<>2]|=(128|ae&63)<>2]|=(240|ae>>18)<>2]|=(128|ae>>12&63)<>2]|=(128|ae>>6&63)<>2]|=(128|ae&63)<>2]|=V[pe]<=ge){for(this.start=ie-ge,this.block=Ie[be],ie=0;ie>8,Ae=V&255;Ae>0;)ge.unshift(Ae),V=V>>8,Ae=V&255,++Ie;return we?ge.push(Ie):ge.unshift(Ie),this.update(ge),ge.length},oe.prototype.encodeString=function(V){var we=k(V);V=we[0];var Ae=we[1],Ie=0,ge=V.length;if(Ae)for(var Me=0;Me=57344?Ie+=3:(be=65536+((be&1023)<<10|V.charCodeAt(++Me)&1023),Ie+=4)}else Ie=ge;return Ie+=this.encode(Ie*8),this.update(V),Ie},oe.prototype.bytepad=function(V,we){for(var Ae=this.encode(we),Ie=0;Ie>2]|=this.padding[we&3],this.lastByteIndex===this.byteCount)for(V[0]=V[Ae],we=1;we>4&15]+l[pe&15]+l[pe>>12&15]+l[pe>>8&15]+l[pe>>20&15]+l[pe>>16&15]+l[pe>>28&15]+l[pe>>24&15];Me%V===0&&(we=W(we),je(we),ge=0)}return Ie&&(pe=we[ge],be+=l[pe>>4&15]+l[pe&15],Ie>1&&(be+=l[pe>>12&15]+l[pe>>8&15]),Ie>2&&(be+=l[pe>>20&15]+l[pe>>16&15])),be},oe.prototype.arrayBuffer=function(){this.finalize();var V=this.blockCount,we=this.s,Ae=this.outputBlocks,Ie=this.extraBytes,ge=0,Me=0,be=this.outputBits>>3,pe;Ie?pe=new ArrayBuffer(Ae+1<<2):pe=new ArrayBuffer(be);for(var J=new Uint32Array(pe);Me>8&255,be[pe+2]=J>>16&255,be[pe+3]=J>>24&255;Me%V===0&&(we=W(we),je(we))}return Ie&&(pe=Me<<2,J=we[ge],be[pe]=J&255,Ie>1&&(be[pe+1]=J>>8&255),Ie>2&&(be[pe+2]=J>>16&255)),be};function Oe(V,we,Ae){oe.call(this,V,we,Ae)}Oe.prototype=new oe,Oe.prototype.finalize=function(){return this.encode(this.outputBits,!0),oe.prototype.finalize.call(this)};var je=function(V){var we,Ae,Ie,ge,Me,be,pe,J,ie,ae,Pe,$e,Re,ut,Je,ft,Z,O,F,ne,he,Te,Fe,Bt,vn,Kt,Dn,bt,Gn,Zn,Ls,Is,ha,iu,kf,Bs,eo,ou,ce,se,ue,Ce,Le,Qe,ht,pt,zt,Ut,on,kn,Mn,zr,Wr,ci,cc,lc,uc,au,dc,Jc,vd,_w,Sw;for(Ie=0;Ie<48;Ie+=2)ge=V[0]^V[10]^V[20]^V[30]^V[40],Me=V[1]^V[11]^V[21]^V[31]^V[41],be=V[2]^V[12]^V[22]^V[32]^V[42],pe=V[3]^V[13]^V[23]^V[33]^V[43],J=V[4]^V[14]^V[24]^V[34]^V[44],ie=V[5]^V[15]^V[25]^V[35]^V[45],ae=V[6]^V[16]^V[26]^V[36]^V[46],Pe=V[7]^V[17]^V[27]^V[37]^V[47],$e=V[8]^V[18]^V[28]^V[38]^V[48],Re=V[9]^V[19]^V[29]^V[39]^V[49],we=$e^(be<<1|pe>>>31),Ae=Re^(pe<<1|be>>>31),V[0]^=we,V[1]^=Ae,V[10]^=we,V[11]^=Ae,V[20]^=we,V[21]^=Ae,V[30]^=we,V[31]^=Ae,V[40]^=we,V[41]^=Ae,we=ge^(J<<1|ie>>>31),Ae=Me^(ie<<1|J>>>31),V[2]^=we,V[3]^=Ae,V[12]^=we,V[13]^=Ae,V[22]^=we,V[23]^=Ae,V[32]^=we,V[33]^=Ae,V[42]^=we,V[43]^=Ae,we=be^(ae<<1|Pe>>>31),Ae=pe^(Pe<<1|ae>>>31),V[4]^=we,V[5]^=Ae,V[14]^=we,V[15]^=Ae,V[24]^=we,V[25]^=Ae,V[34]^=we,V[35]^=Ae,V[44]^=we,V[45]^=Ae,we=J^($e<<1|Re>>>31),Ae=ie^(Re<<1|$e>>>31),V[6]^=we,V[7]^=Ae,V[16]^=we,V[17]^=Ae,V[26]^=we,V[27]^=Ae,V[36]^=we,V[37]^=Ae,V[46]^=we,V[47]^=Ae,we=ae^(ge<<1|Me>>>31),Ae=Pe^(Me<<1|ge>>>31),V[8]^=we,V[9]^=Ae,V[18]^=we,V[19]^=Ae,V[28]^=we,V[29]^=Ae,V[38]^=we,V[39]^=Ae,V[48]^=we,V[49]^=Ae,ut=V[0],Je=V[1],pt=V[11]<<4|V[10]>>>28,zt=V[10]<<4|V[11]>>>28,bt=V[20]<<3|V[21]>>>29,Gn=V[21]<<3|V[20]>>>29,Jc=V[31]<<9|V[30]>>>23,vd=V[30]<<9|V[31]>>>23,Ce=V[40]<<18|V[41]>>>14,Le=V[41]<<18|V[40]>>>14,iu=V[2]<<1|V[3]>>>31,kf=V[3]<<1|V[2]>>>31,ft=V[13]<<12|V[12]>>>20,Z=V[12]<<12|V[13]>>>20,Ut=V[22]<<10|V[23]>>>22,on=V[23]<<10|V[22]>>>22,Zn=V[33]<<13|V[32]>>>19,Ls=V[32]<<13|V[33]>>>19,_w=V[42]<<2|V[43]>>>30,Sw=V[43]<<2|V[42]>>>30,ci=V[5]<<30|V[4]>>>2,cc=V[4]<<30|V[5]>>>2,Bs=V[14]<<6|V[15]>>>26,eo=V[15]<<6|V[14]>>>26,O=V[25]<<11|V[24]>>>21,F=V[24]<<11|V[25]>>>21,kn=V[34]<<15|V[35]>>>17,Mn=V[35]<<15|V[34]>>>17,Is=V[45]<<29|V[44]>>>3,ha=V[44]<<29|V[45]>>>3,Bt=V[6]<<28|V[7]>>>4,vn=V[7]<<28|V[6]>>>4,lc=V[17]<<23|V[16]>>>9,uc=V[16]<<23|V[17]>>>9,ou=V[26]<<25|V[27]>>>7,ce=V[27]<<25|V[26]>>>7,ne=V[36]<<21|V[37]>>>11,he=V[37]<<21|V[36]>>>11,zr=V[47]<<24|V[46]>>>8,Wr=V[46]<<24|V[47]>>>8,Qe=V[8]<<27|V[9]>>>5,ht=V[9]<<27|V[8]>>>5,Kt=V[18]<<20|V[19]>>>12,Dn=V[19]<<20|V[18]>>>12,au=V[29]<<7|V[28]>>>25,dc=V[28]<<7|V[29]>>>25,se=V[38]<<8|V[39]>>>24,ue=V[39]<<8|V[38]>>>24,Te=V[48]<<14|V[49]>>>18,Fe=V[49]<<14|V[48]>>>18,V[0]=ut^~ft&O,V[1]=Je^~Z&F,V[10]=Bt^~Kt&bt,V[11]=vn^~Dn&Gn,V[20]=iu^~Bs&ou,V[21]=kf^~eo&ce,V[30]=Qe^~pt&Ut,V[31]=ht^~zt&on,V[40]=ci^~lc&au,V[41]=cc^~uc&dc,V[2]=ft^~O&ne,V[3]=Z^~F&he,V[12]=Kt^~bt&Zn,V[13]=Dn^~Gn&Ls,V[22]=Bs^~ou&se,V[23]=eo^~ce&ue,V[32]=pt^~Ut&kn,V[33]=zt^~on&Mn,V[42]=lc^~au&Jc,V[43]=uc^~dc&vd,V[4]=O^~ne&Te,V[5]=F^~he&Fe,V[14]=bt^~Zn&Is,V[15]=Gn^~Ls&ha,V[24]=ou^~se&Ce,V[25]=ce^~ue&Le,V[34]=Ut^~kn&zr,V[35]=on^~Mn&Wr,V[44]=au^~Jc&_w,V[45]=dc^~vd&Sw,V[6]=ne^~Te&ut,V[7]=he^~Fe&Je,V[16]=Zn^~Is&Bt,V[17]=Ls^~ha&vn,V[26]=se^~Ce&iu,V[27]=ue^~Le&kf,V[36]=kn^~zr&Qe,V[37]=Mn^~Wr&ht,V[46]=Jc^~_w&ci,V[47]=vd^~Sw&cc,V[8]=Te^~ut&ft,V[9]=Fe^~Je&Z,V[18]=Is^~Bt&Kt,V[19]=ha^~vn&Dn,V[28]=Ce^~iu&Bs,V[29]=Le^~kf&eo,V[38]=zr^~Qe&pt,V[39]=Wr^~ht&zt,V[48]=_w^~ci&lc,V[49]=Sw^~cc&uc,V[0]^=y[Ie],V[1]^=y[Ie+1]};if(a)t.exports=P;else for(Y=0;Y=t.byteLength);){const r=FV(t,e);if(r===null)break;n.push(r)}return n}function ySt(t,e){const n=z3(t,e),r=e.offset,s=e.offset+n,i=[];for(let o=r;o{try{return await lS.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function BSt(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await lS.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await lS.get().subtle.verify({name:"Ed25519"},r,e,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function USt(t,e,n){return K_.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}async function FSt(t,e,n){return I9==null&&(I9=await LSt),I9?BSt(t,e,n):USt(t,e,n)}function lbe(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class jSt{type="Ed25519";raw;constructor(e){this.raw=ube(e,zV)}toMultihash(){return L0.digest(WV(this))}toCID(){return Cr.createV1(114,this.toMultihash())}toString(){return ps.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:As(this.raw,e.raw)}verify(e,n,r){r?.signal?.throwIfAborted();const s=FSt(this.raw,n,e);return lbe(s)?s.then(i=>(r?.signal?.throwIfAborted(),i)):s}}function zSt(t){return t=ube(t,zV),new jSt(t)}function ube(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new cr(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var wf;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(wf||(wf={}));var CU;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(CU||(CU={}));(function(t){t.codec=()=>JW(CU)})(wf||(wf={}));var S4;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),wf.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.Type=wf.codec().decode(n);break}case 2:{i.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(S4||(S4={}));var kre;(function(t){let e;t.codec=()=>(e==null&&(e=dn((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),wf.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const i={},o=r==null?n.len:n.pos+r;for(;n.pos>>3){case 1:{i.Type=wf.codec().decode(n);break}case 2:{i.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),e),t.encode=n=>un(n,t.codec()),t.decode=(n,r)=>ln(n,t.codec(),r)})(kre||(kre={}));class WSt{type="RSA";jwk;_raw;_multihash;constructor(e,n){this.jwk=e,this._multihash=n}get raw(){return this._raw==null&&(this._raw=KSt(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Cr.createV1(114,this._multihash)}toString(){return ps.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:As(this.raw,e.raw)}verify(e,n,r){return YSt(this.jwk,n,e,r)}}const VSt=18,HSt=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function qSt(t){const e=FV(t[1],{offset:0});return{kty:"RSA",n:hn(e[0],"base64url"),e:hn(e[1],"base64url")}}function KSt(t){if(t.n==null||t.e==null)throw new cr("JWK was missing components");return zE([HSt,cbe(zE([EU(Jt(t.n,"base64url")),EU(Jt(t.e,"base64url"))]))]).subarray()}function GSt(t,e,n){const r=qSt(t);if(n==null){const s=Th(S4.encode({Type:wf.RSA,Data:e}));n=k3(VSt,s)}return new WSt(r,n)}const ZSt="1.2.840.113549.1.1.1";async function YSt(t,e,n,r){const s=await lS.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const i=await lS.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),i}const XSt=33;function QSt(t,e,n,r){const s=QW.digest(n instanceof Uint8Array?n:n.subarray());if(lbe(s))return s.then(({digest:i})=>(r?.signal?.throwIfAborted(),up.secp256k1.verify(e,i,t))).catch(i=>{throw i.name==="AbortError"?i:new Pre(String(i))});try{return r?.signal?.throwIfAborted(),up.secp256k1.verify(e,s.digest,t)}catch(i){throw new Pre(String(i))}}class JSt{type="secp256k1";raw;_key;constructor(e){this._key=n3t(e),this.raw=t3t(this._key)}toMultihash(){return L0.digest(WV(this))}toCID(){return Cr.createV1(114,this.toMultihash())}toString(){return ps.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:As(this.raw,e.raw)}verify(e,n,r){return QSt(this._key,n,e,r)}}function e3t(t){return new JSt(t)}function t3t(t){return up.secp256k1.ProjectivePoint.fromHex(t).toRawBytes(!0)}function n3t(t){try{return up.secp256k1.ProjectivePoint.fromHex(t),t}catch(e){throw new oV(String(e))}}function r3t(t){if(t.byteLength===zV)return zSt(t);if(t.byteLength===XSt)return e3t(t);const e=FV(t),n=e[1]?.[0];if(n===CSt||n===_St||n===SSt)return OSt(e);if(e[0]?.[0]===ZSt)return GSt(e,t);throw new cr("Could not extract public key from raw bytes")}function WV(t){return S4.encode({Type:wf[t.type],Data:t.raw})}const s3t=Symbol.for("nodejs.util.inspect.custom"),i3t=114;class VV{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Jk]=!0;toString(){return this.string==null&&(this.string=ps.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Cr.createV1(i3t,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return As(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return As(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[s3t](){return`PeerId(${this.toString()})`}}class o3t extends VV{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class a3t extends VV{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class c3t extends VV{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}function l3t(t){if(t.type==="Ed25519")return new a3t({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new c3t({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new o3t({multihash:t.toCID().multihash,publicKey:t});throw new e8}const u3t="Keypair type not implemented";function d3t(t){const e=r3t(t);if(e.type!=="secp256k1")throw new Error(u3t);return l3t(e)}function f3t(t){const e=[];let n=0;for(;ni+_4+o.bytes.length,0),n=new Uint8Array(e),r=new DataView(n.buffer);let s=0;return t.forEach(i=>{if(i.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");r.setUint16(s,i.bytes.length),s+=_4,n.set(i.bytes,s),s+=i.bytes.length}),n}function p3t(t){let e=0;return t.lightPush&&(e+=1),e=e<<1,t.filter&&(e+=1),e=e<<1,t.store&&(e+=1),e=e<<1,t.relay&&(e+=1),e}function g3t(t){const e={relay:!1,store:!1,filter:!1,lightPush:!1};return t%2&&(e.relay=!0),t=t>>1,t%2&&(e.store=!0),t=t>>1,t%2&&(e.filter=!0),t=t>>1,t%2&&(e.lightPush=!0),e}class m3t extends Map{seq;signature;constructor(e={},n=BigInt(1),r){super(Object.entries(e)),this.seq=n,this.signature=r}set(e,n){return this.signature=void 0,this.seq++,super.set(e,n)}get id(){const e=this.get("id");if(!e)throw new Error("id not found.");return j_(e)}get publicKey(){switch(this.id){case"v4":return this.get("secp256k1");default:throw new Error(a6)}}get rs(){const e=this.get("rs");if(e)return qB(e)}get rsv(){const e=this.get("rsv");if(e)return qB(e)}get ip(){return Rre(this,"ip","ip4")}set ip(e){_U(this,"ip","ip4",e)}get tcp(){return fI(this,"tcp","tcp")}set tcp(e){hI(this,"tcp","tcp",e)}get udp(){return fI(this,"udp","udp")}set udp(e){hI(this,"udp","udp",e)}get ip6(){return Rre(this,"ip6","ip6")}set ip6(e){_U(this,"ip6","ip6",e)}get tcp6(){return fI(this,"tcp6","tcp")}set tcp6(e){hI(this,"tcp6","tcp",e)}get udp6(){return fI(this,"udp6","udp")}set udp6(e){hI(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return f3t(e)}set multiaddrs(e){SU(this,"multiaddrs",e,h3t)}get waku2(){const e=this.get("waku2");if(e)return g3t(e[0])}set waku2(e){SU(this,"waku2",e,n=>new Uint8Array([p3t(n)]))}}function Rre(t,e,n){const r=t.get(e);if(r)return a4(n,r)}function fI(t,e,n){const r=t.get(e);if(r)return Number(a4(n,r))}function _U(t,e,n,r){SU(t,e,r,tvt.bind({},n))}function hI(t,e,n,r){_U(t,e,n,r?.toString(10))}function SU(t,e,n,r){n!==void 0?t.set(e,r(n)):t.delete(e)}async function y3t(t,e){return Yv.sign(C8(e),t,{der:!1})}function w3t(t){const n=Yv.Point.fromHex(t).toRawBytes(!1);return Yk(C8(n.slice(1)))}const Ore=new rr("enr");var $re;(function(t){t.TCP="tcp",t.UDP="udp"})($re||($re={}));var AU;(function(t){t.TCP4="tcp4",t.UDP4="udp4",t.TCP6="tcp6",t.UDP6="udp6"})(AU||(AU={}));class $1 extends m3t{static RECORD_PREFIX="enr:";peerId;static create(e={},n=BigInt(1),r){const s=new $1(e,n,r);try{const i=s.publicKey;i&&(s.peerId=d3t(i))}catch(i){Ore.error("Could not calculate peer id for ENR",i)}return s}get nodeId(){switch(this.id){case"v4":return this.publicKey?w3t(this.publicKey):void 0;default:throw new Error(a6)}}getLocationMultiaddr=J2.bind({},this);get shardInfo(){return this.rs&&this.rsv&&Ore.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const n=e.protoNames();if(n.length!==2&&n[1]!=="udp"&&n[1]!=="tcp")throw new Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw new Error("Invalid multiaddr");r[0][0]===4?(this.set("ip",r[0][1]),this.set(n[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(n[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){const e=[];for(const r of Object.values(AU)){const s=this.getLocationMultiaddr(r);s&&e.push(s)}const n=this.multiaddrs??[];return e.concat(n).map(r=>this.peerId?r.encapsulate(`/p2p/${this.peerId.toString()}`):r)}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const n=this.getLocationMultiaddr(e);if(n)return n.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const e=this.peerId;return this.multiaddrs.map(n=>n.encapsulate(`/p2p/${e.toString()}`))}return[]}verify(e,n){if(!this.get("id")||this.id!=="v4")throw new Error(a6);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return abe(n,C8(e),this.publicKey)}async sign(e,n){switch(this.id){case"v4":this.signature=await y3t(n,e);break;default:throw new Error(a6)}return this.signature}}const b3t="logger/5.8.0";let Dre=!1,Mre=!1;const c6={debug:1,default:2,info:2,warning:3,error:4,off:5};let Lre=c6.default,T9=null;function v3t(){try{const t=[];if(["NFD","NFC","NFKD","NFKC"].forEach(e=>{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{t.push(e)}}),t.length)throw new Error("missing "+t.join(", "));if("é".normalize("NFD")!=="é")throw new Error("broken implementation")}catch(t){return t.message}return null}const Bre=v3t();var IU;(function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR",t.OFF="OFF"})(IU||(IU={}));var Pu;(function(t){t.UNKNOWN_ERROR="UNKNOWN_ERROR",t.NOT_IMPLEMENTED="NOT_IMPLEMENTED",t.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.TIMEOUT="TIMEOUT",t.BUFFER_OVERRUN="BUFFER_OVERRUN",t.NUMERIC_FAULT="NUMERIC_FAULT",t.MISSING_NEW="MISSING_NEW",t.INVALID_ARGUMENT="INVALID_ARGUMENT",t.MISSING_ARGUMENT="MISSING_ARGUMENT",t.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",t.CALL_EXCEPTION="CALL_EXCEPTION",t.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",t.NONCE_EXPIRED="NONCE_EXPIRED",t.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",t.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",t.TRANSACTION_REPLACED="TRANSACTION_REPLACED",t.ACTION_REJECTED="ACTION_REJECTED"})(Pu||(Pu={}));const Ure="0123456789abcdef";class Er{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,n){const r=e.toLowerCase();c6[r]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(Lre>c6[r])&&console.log.apply(console,n)}debug(...e){this._log(Er.levels.DEBUG,e)}info(...e){this._log(Er.levels.INFO,e)}warn(...e){this._log(Er.levels.WARNING,e)}makeError(e,n,r){if(Mre)return this.makeError("censored error",n,{});n||(n=Er.errors.UNKNOWN_ERROR),r||(r={});const s=[];Object.keys(r).forEach(c=>{const l=r[c];try{if(l instanceof Uint8Array){let u="";for(let d=0;d>4],u+=Ure[l[d]&15];s.push(c+"=Uint8Array(0x"+u+")")}else s.push(c+"="+JSON.stringify(l))}catch{s.push(c+"="+JSON.stringify(r[c].toString()))}}),s.push(`code=${n}`),s.push(`version=${this.version}`);const i=e;let o="";switch(n){case Pu.NUMERIC_FAULT:{o="NUMERIC_FAULT";const c=e;switch(c){case"overflow":case"underflow":case"division-by-zero":o+="-"+c;break;case"negative-power":case"negative-width":o+="-unsupported";break;case"unbound-bitwise-result":o+="-unbound-result";break}break}case Pu.CALL_EXCEPTION:case Pu.INSUFFICIENT_FUNDS:case Pu.MISSING_NEW:case Pu.NONCE_EXPIRED:case Pu.REPLACEMENT_UNDERPRICED:case Pu.TRANSACTION_REPLACED:case Pu.UNPREDICTABLE_GAS_LIMIT:o=n;break}o&&(e+=" [ See: https://links.ethers.org/v5-errors-"+o+" ]"),s.length&&(e+=" ("+s.join(", ")+")");const a=new Error(e);return a.reason=i,a.code=n,Object.keys(r).forEach(function(c){a[c]=r[c]}),a}throwError(e,n,r){throw this.makeError(e,n,r)}throwArgumentError(e,n,r){return this.throwError(e,Er.errors.INVALID_ARGUMENT,{argument:n,value:r})}assert(e,n,r,s){e||this.throwError(n,r,s)}assertArgument(e,n,r,s){e||this.throwArgumentError(n,r,s)}checkNormalize(e){Bre&&this.throwError("platform missing String.prototype.normalize",Er.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Bre})}checkSafeUint53(e,n){typeof e=="number"&&(n==null&&(n="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(n,Er.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(n,Er.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,n,r){r?r=": "+r:r="",en&&this.throwError("too many arguments"+r,Er.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:n})}checkNew(e,n){(e===Object||e==null)&&this.throwError("missing new",Er.errors.MISSING_NEW,{name:n.name})}checkAbstract(e,n){e===n?this.throwError("cannot instantiate abstract class "+JSON.stringify(n.name)+" directly; use a sub-class",Er.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",Er.errors.MISSING_NEW,{name:n.name})}static globalLogger(){return T9||(T9=new Er(b3t)),T9}static setCensorship(e,n){if(!e&&n&&this.globalLogger().throwError("cannot permanently disable censorship",Er.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),Dre){if(!e)return;this.globalLogger().throwError("error censorship permanent",Er.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}Mre=!!e,Dre=!!n}static setLogLevel(e){const n=c6[e.toLowerCase()];if(n==null){Er.globalLogger().warn("invalid log level - "+e);return}Lre=n}static from(e){return new Er(e)}}Er.errors=Pu;Er.levels=IU;const x3t="bytes/5.8.0",bv=new Er(x3t);function dbe(t){return!!t.toHexString}function l6(t){return t.slice||(t.slice=function(){const e=Array.prototype.slice.call(arguments);return l6(new Uint8Array(Array.prototype.slice.apply(t,e)))}),t}function E3t(t){return qV(t)&&!(t.length%2)||HV(t)}function Fre(t){return typeof t=="number"&&t==t&&t%1===0}function HV(t){if(t==null)return!1;if(t.constructor===Uint8Array)return!0;if(typeof t=="string"||!Fre(t.length)||t.length<0)return!1;for(let e=0;e=256)return!1}return!0}function fbe(t,e){if(e||(e={}),typeof t=="number"){bv.checkSafeUint53(t,"invalid arrayify value");const n=[];for(;t;)n.unshift(t&255),t=parseInt(String(t/256));return n.length===0&&n.push(0),l6(new Uint8Array(n))}if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),dbe(t)&&(t=t.toHexString()),qV(t)){let n=t.substring(2);n.length%2&&(e.hexPad==="left"?n="0"+n:e.hexPad==="right"?n+="0":bv.throwArgumentError("hex data is odd-length","value",t));const r=[];for(let s=0;s>4]+N9[s&15]}return n}return bv.throwArgumentError("invalid hexlify value","value",t)}const C3t="rlp/5.8.0",Ud=new Er(C3t);function jre(t){const e=[];for(;t;)e.unshift(t&255),t>>=8;return e}function zre(t,e,n){let r=0;for(let s=0;se+1+r&&Ud.throwError("child data too short",Er.errors.BUFFER_OVERRUN,{})}return{consumed:1+r,result:s}}function pbe(t,e){if(t.length===0&&Ud.throwError("data too short",Er.errors.BUFFER_OVERRUN,{}),t[e]>=248){const n=t[e]-247;e+1+n>t.length&&Ud.throwError("data short segment too short",Er.errors.BUFFER_OVERRUN,{});const r=zre(t,e+1,n);return e+1+n+r>t.length&&Ud.throwError("data long segment too short",Er.errors.BUFFER_OVERRUN,{}),Wre(t,e,e+1+n,n+r)}else if(t[e]>=192){const n=t[e]-192;return e+1+n>t.length&&Ud.throwError("data array too short",Er.errors.BUFFER_OVERRUN,{}),Wre(t,e,e+1,n)}else if(t[e]>=184){const n=t[e]-183;e+1+n>t.length&&Ud.throwError("data array too short",Er.errors.BUFFER_OVERRUN,{});const r=zre(t,e+1,n);e+1+n+r>t.length&&Ud.throwError("data array too short",Er.errors.BUFFER_OVERRUN,{});const s=u6(t.slice(e+1+n,e+1+n+r));return{consumed:1+n+r,result:s}}else if(t[e]>=128){const n=t[e]-128;e+1+n>t.length&&Ud.throwError("data too short",Er.errors.BUFFER_OVERRUN,{});const r=u6(t.slice(e+1,e+1+n));return{consumed:1+n,result:r}}return{consumed:1,result:u6(t[e])}}function S3t(t){const e=fbe(t),n=pbe(e,0);return n.consumed!==e.length&&Ud.throwArgumentError("invalid rlp data","data",t),n.result}const A3t=new rr("enr:decoder");class _8{static fromString(e){if(!e.startsWith($1.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${$1.RECORD_PREFIX}'`);return _8.fromRLP(Jt(e.slice(4),"base64url"))}static fromRLP(e){const n=S3t(e).map(ume);return I3t(n)}}async function I3t(t){const{signature:e,seq:n,kvs:r}=N3t(t),s={};for(let a=0;a0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.#s=e.maxSize,this.#i=e.maxAge||Number.POSITIVE_INFINITY,this.#a=e.onEviction}get __oldCache(){return this.#n}#o(e){if(typeof this.#a=="function")for(const[n,r]of e)this.#a(n,r.value)}#r(e,n){return typeof n.expiry=="number"&&n.expiry<=Date.now()?(typeof this.#a=="function"&&this.#a(e,n.value),this.delete(e)):!1}#c(e,n){if(this.#r(e,n)===!1)return n.value}#f(e,n){return n.expiry?this.#c(e,n):n.value}#l(e,n){const r=n.get(e);return this.#f(e,r)}#d(e,n){this.#t.set(e,n),this.#e++,this.#e>=this.#s&&(this.#e=0,this.#o(this.#n),this.#n=this.#t,this.#t=new Map)}#u(e,n){this.#n.delete(e),this.#d(e,n)}*#h(){for(const e of this.#n){const[n,r]=e;this.#t.has(n)||this.#r(n,r)===!1&&(yield e)}for(const e of this.#t){const[n,r]=e;this.#r(n,r)===!1&&(yield e)}}get(e){if(this.#t.has(e)){const n=this.#t.get(e);return this.#f(e,n)}if(this.#n.has(e)){const n=this.#n.get(e);if(this.#r(e,n)===!1)return this.#u(e,n),n.value}}set(e,n,{maxAge:r=this.#i}={}){const s=typeof r=="number"&&r!==Number.POSITIVE_INFINITY?Date.now()+r:void 0;return this.#t.has(e)?this.#t.set(e,{value:n,expiry:s}):this.#d(e,{value:n,expiry:s}),this}has(e){return this.#t.has(e)?!this.#r(e,this.#t.get(e)):this.#n.has(e)?!this.#r(e,this.#n.get(e)):!1}peek(e){if(this.#t.has(e))return this.#l(e,this.#t);if(this.#n.has(e))return this.#l(e,this.#n)}expiresIn(e){const n=this.#t.get(e)??this.#n.get(e);if(n)return n.expiry?n.expiry-Date.now():Number.POSITIVE_INFINITY}delete(e){const n=this.#t.delete(e);return n&&this.#e--,this.#n.delete(e)||n}clear(){this.#t.clear(),this.#n.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");const n=[...this.#h()],r=n.length-e;r<0?(this.#t=new Map(n),this.#n=new Map,this.#e=n.length):(r>0&&this.#o(n.slice(0,r)),this.#n=new Map(n.slice(r)),this.#t=new Map,this.#e=0),this.#s=e}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[Symbol.iterator](){for(const e of this.#t){const[n,r]=e;this.#r(n,r)===!1&&(yield[n,r.value])}for(const e of this.#n){const[n,r]=e;this.#t.has(n)||this.#r(n,r)===!1&&(yield[n,r.value])}}*entriesDescending(){let e=[...this.#t];for(let n=e.length-1;n>=0;--n){const r=e[n],[s,i]=r;this.#r(s,i)===!1&&(yield[s,i.value])}e=[...this.#n];for(let n=e.length-1;n>=0;--n){const r=e[n],[s,i]=r;this.#t.has(s)||this.#r(s,i)===!1&&(yield[s,i.value])}}*entriesAscending(){for(const[e,n]of this.#h())yield[e,n.value]}get size(){if(!this.#e)return this.#n.size;let e=0;for(const n of this.#n.keys())this.#t.has(n)||e++;return Math.min(this.#e+e,this.#s)}get maxSize(){return this.#s}entries(){return this.entriesAscending()}forEach(e,n=this){for(const[r,s]of this.entriesAscending())e.call(n,s,r,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function P9(t,e,n){return`${t}?name=${e}&type=${n}`}async function k3t(t,e){return await(await fetch(t,{headers:new Headers({accept:"application/dns-json"}),signal:e})).json()}function pb(t,e){return`${e}_${t}`}const k9=Object.assign(Qo("dns-over-http-resolver"),{error:Qo("dns-over-http-resolver:error")});class R3t{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new Vre({maxSize:e?.maxCache??100}),this._TXTcache=new Vre({maxSize:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??k3t,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>{e.abort()})}getServers(){return this._servers}_getShuffledServers(){const e=[...this._servers];for(let n=e.length-1;n>0;n--){const r=Math.floor(Math.random()*n),s=e[n];e[n]=e[r],e[r]=s}return e}setServers(e){this._servers=e}async resolve(e,n="A"){switch(n){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${n} is not supported`)}}async resolve4(e){const n="A",r=this._cache.get(pb(e,n));if(r!=null)return r;let s=!1;for(const i of this._getShuffledServers()){const o=new AbortController;this._abortControllers.push(o);try{const a=await this._request(P9(i,e,n),o.signal),c=a.Answer.map(u=>u.data),l=Math.min(...a.Answer.map(u=>u.TTL));return this._cache.set(pb(e,n),c,{maxAge:l}),c}catch{o.signal.aborted&&(s=!0),k9.error(`${i} could not resolve ${e} record ${n}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw s?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${n}`)}async resolve6(e){const n="AAAA",r=this._cache.get(pb(e,n));if(r!=null)return r;let s=!1;for(const i of this._getShuffledServers()){const o=new AbortController;this._abortControllers.push(o);try{const a=await this._request(P9(i,e,n),o.signal),c=a.Answer.map(u=>u.data),l=Math.min(...a.Answer.map(u=>u.TTL));return this._cache.set(pb(e,n),c,{maxAge:l}),c}catch{o.signal.aborted&&(s=!0),k9.error(`${i} could not resolve ${e} record ${n}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw s?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${n}`)}async resolveTxt(e){const n="TXT",r=this._TXTcache.get(pb(e,n));if(r!=null)return r;let s=!1;for(const i of this._getShuffledServers()){const o=new AbortController;this._abortControllers.push(o);try{const a=await this._request(P9(i,e,n),o.signal),c=a.Answer.map(u=>[u.data.replace(/['"]+/g,"")]),l=Math.min(...a.Answer.map(u=>u.TTL));return this._TXTcache.set(pb(e,n),c,{maxAge:l}),c}catch{o.signal.aborted&&(s=!0),k9.error(`${i} could not resolve ${e} record ${n}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw s?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${n}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}}const O3t=new rr("dns-over-https");class KV{resolver;static async create(){return new KV}constructor(e=new R3t){this.resolver=e}async resolveTXT(e){let n;try{n=await this.resolver.resolveTxt(e)}catch(s){throw O3t.error("query failed: ",s),new Error("DNS query failed")}if(!n)throw new Error(`Could not resolve ${e}`);const r=[];return n.forEach(s=>{typeof s=="string"?r.push(s):Array.isArray(s)?s.forEach(i=>{typeof i=="string"?r.push(i):r.push(j_(i))}):r.push(j_(s))}),r}}var gbe={exports:{}};/* + * [hi-base32]{@link https://github.com/emn178/hi-base32} + * + * @version 0.5.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT + */(function(t){(function(){var e=typeof window=="object"?window:{},n=!e.HI_BASE32_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;n&&(e=kr);var r=!e.HI_BASE32_NO_COMMON_JS&&!0&&t.exports,s="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),i={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},o=[0,0,0,0,0,0,0,0],a=function(b,v){v.length>10&&(v="..."+v.substr(-10));var x=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+b+" bytes: "+v+" <-");throw x.position=b,x},c=function(b){for(var v="",x=b.length,E=0,A=0,_,k;E191&&_<=223?(k=_&31,A=1):_<=239?(k=_&15,A=2):_<=247?(k=_&7,A=3):a(E,v);for(var B=0;B191)&&a(E,v),k<<=6,k+=_&63;k>=55296&&k<=57343&&a(E,v),k>1114111&&a(E,v),k<=65535?v+=String.fromCharCode(k):(k-=65536,v+=String.fromCharCode((k>>10)+55296),v+=String.fromCharCode((k&1023)+56320))}return v},l=function(b){if(b==="")return[];if(!/^[A-Z2-7=]+$/.test(b))throw new Error("Invalid base32 characters");b=b.replace(/=/g,"");for(var v,x,E,A,_,k,B,W,S=[],$=0,R=b.length,M=0,j=R>>3<<3;M>>2)&255,S[$++]=(x<<6|E<<1|A>>>4)&255,S[$++]=(A<<4|_>>>1)&255,S[$++]=(_<<7|k<<2|B>>>3)&255,S[$++]=(B<<5|W)&255;var z=R-j;return z===2?(v=i[b.charAt(M++)],x=i[b.charAt(M++)],S[$++]=(v<<3|x>>>2)&255):z===4?(v=i[b.charAt(M++)],x=i[b.charAt(M++)],E=i[b.charAt(M++)],A=i[b.charAt(M++)],S[$++]=(v<<3|x>>>2)&255,S[$++]=(x<<6|E<<1|A>>>4)&255):z===5?(v=i[b.charAt(M++)],x=i[b.charAt(M++)],E=i[b.charAt(M++)],A=i[b.charAt(M++)],_=i[b.charAt(M++)],S[$++]=(v<<3|x>>>2)&255,S[$++]=(x<<6|E<<1|A>>>4)&255,S[$++]=(A<<4|_>>>1)&255):z===7&&(v=i[b.charAt(M++)],x=i[b.charAt(M++)],E=i[b.charAt(M++)],A=i[b.charAt(M++)],_=i[b.charAt(M++)],k=i[b.charAt(M++)],B=i[b.charAt(M++)],S[$++]=(v<<3|x>>>2)&255,S[$++]=(x<<6|E<<1|A>>>4)&255,S[$++]=(A<<4|_>>>1)&255,S[$++]=(_<<7|k<<2|B>>>3)&255),S},u=function(b){for(var v,x,E,A,_,k="",B=b.length,W=0,S=parseInt(B/5)*5;W>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[(x<<4|E>>>4)&31]+s[(E<<1|A>>>7)&31]+s[A>>>2&31]+s[(A<<3|_>>>5)&31]+s[_&31];var $=B-S;return $===1?(v=b.charCodeAt(W),k+=s[v>>>3]+s[v<<2&31]+"======"):$===2?(v=b.charCodeAt(W++),x=b.charCodeAt(W),k+=s[v>>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[x<<4&31]+"===="):$===3?(v=b.charCodeAt(W++),x=b.charCodeAt(W++),E=b.charCodeAt(W),k+=s[v>>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[(x<<4|E>>>4)&31]+s[E<<1&31]+"==="):$===4&&(v=b.charCodeAt(W++),x=b.charCodeAt(W++),E=b.charCodeAt(W++),A=b.charCodeAt(W),k+=s[v>>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[(x<<4|E>>>4)&31]+s[(E<<1|A>>>7)&31]+s[A>>>2&31]+s[A<<3&31]+"="),k},d=function(b){var v,x,E,A,_,k,B=!1,W="",S=0,$,R=0,M=b.length;if(b==="")return W;do{for(o[0]=o[5],o[1]=o[6],o[2]=o[7],$=R;S>6,o[$++]=128|k&63):k<55296||k>=57344?(o[$++]=224|k>>12,o[$++]=128|k>>6&63,o[$++]=128|k&63):(k=65536+((k&1023)<<10|b.charCodeAt(++S)&1023),o[$++]=240|k>>18,o[$++]=128|k>>12&63,o[$++]=128|k>>6&63,o[$++]=128|k&63);R=$-5,S===M&&++S,S>M&&$<6&&(B=!0),v=o[0],$>4?(x=o[1],E=o[2],A=o[3],_=o[4],W+=s[v>>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[(x<<4|E>>>4)&31]+s[(E<<1|A>>>7)&31]+s[A>>>2&31]+s[(A<<3|_>>>5)&31]+s[_&31]):$===1?W+=s[v>>>3]+s[v<<2&31]+"======":$===2?(x=o[1],W+=s[v>>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[x<<4&31]+"===="):$===3?(x=o[1],E=o[2],W+=s[v>>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[(x<<4|E>>>4)&31]+s[E<<1&31]+"==="):(x=o[1],E=o[2],A=o[3],W+=s[v>>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[(x<<4|E>>>4)&31]+s[(E<<1|A>>>7)&31]+s[A>>>2&31]+s[A<<3&31]+"=")}while(!B);return W},f=function(b){for(var v,x,E,A,_,k="",B=b.length,W=0,S=parseInt(B/5)*5;W>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[(x<<4|E>>>4)&31]+s[(E<<1|A>>>7)&31]+s[A>>>2&31]+s[(A<<3|_>>>5)&31]+s[_&31];var $=B-S;return $===1?(v=b[W],k+=s[v>>>3]+s[v<<2&31]+"======"):$===2?(v=b[W++],x=b[W],k+=s[v>>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[x<<4&31]+"===="):$===3?(v=b[W++],x=b[W++],E=b[W],k+=s[v>>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[(x<<4|E>>>4)&31]+s[E<<1&31]+"==="):$===4&&(v=b[W++],x=b[W++],E=b[W++],A=b[W],k+=s[v>>>3]+s[(v<<2|x>>>6)&31]+s[x>>>1&31]+s[(x<<4|E>>>4)&31]+s[(E<<1|A>>>7)&31]+s[A>>>2&31]+s[A<<3&31]+"="),k},p=function(b,v){var x=typeof b!="string";return x&&b.constructor===ArrayBuffer&&(b=new Uint8Array(b)),x?f(b):v?u(b):d(b)},m=function(b,v){if(!v)return c(l(b));if(b==="")return"";if(!/^[A-Z2-7=]+$/.test(b))throw new Error("Invalid base32 characters");var x,E,A,_,k,B,W,S,$="",R=b.indexOf("=");R===-1&&(R=b.length);for(var M=0,j=R>>3<<3;M>>2)&255)+String.fromCharCode((E<<6|A<<1|_>>>4)&255)+String.fromCharCode((_<<4|k>>>1)&255)+String.fromCharCode((k<<7|B<<2|W>>>3)&255)+String.fromCharCode((W<<5|S)&255);var z=R-j;return z===2?(x=i[b.charAt(M++)],E=i[b.charAt(M++)],$+=String.fromCharCode((x<<3|E>>>2)&255)):z===4?(x=i[b.charAt(M++)],E=i[b.charAt(M++)],A=i[b.charAt(M++)],_=i[b.charAt(M++)],$+=String.fromCharCode((x<<3|E>>>2)&255)+String.fromCharCode((E<<6|A<<1|_>>>4)&255)):z===5?(x=i[b.charAt(M++)],E=i[b.charAt(M++)],A=i[b.charAt(M++)],_=i[b.charAt(M++)],k=i[b.charAt(M++)],$+=String.fromCharCode((x<<3|E>>>2)&255)+String.fromCharCode((E<<6|A<<1|_>>>4)&255)+String.fromCharCode((_<<4|k>>>1)&255)):z===7&&(x=i[b.charAt(M++)],E=i[b.charAt(M++)],A=i[b.charAt(M++)],_=i[b.charAt(M++)],k=i[b.charAt(M++)],B=i[b.charAt(M++)],W=i[b.charAt(M++)],$+=String.fromCharCode((x<<3|E>>>2)&255)+String.fromCharCode((E<<6|A<<1|_>>>4)&255)+String.fromCharCode((_<<4|k>>>1)&255)+String.fromCharCode((k<<7|B<<2|W>>>3)&255)),$},y={encode:p,decode:m};m.asBytes=l,r?t.exports=y:e.base32=y})()})(gbe);var $3t=gbe.exports;const D3t=Zi($3t);class Ma{static RECORD_PREFIX=$1.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(e,n){if(!e.startsWith(this.ROOT_PREFIX))throw new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=Ma.parseRootValues(e),s=D3t.decode.asBytes(n),i=e.split(" sig")[0],o=y1(i),a=Jt(r.signature,"base64url").slice(0,64);if(!abe(a,C8(o),new Uint8Array(s)))throw new Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const n=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(n))throw new Error("Could not parse ENRTree root entry");n.shift();const[r,s,i,o]=n;if(!r)throw new Error("Could not parse 'e' value from ENRTree root entry");if(!s)throw new Error("Could not parse 'l' value from ENRTree root entry");if(!i)throw new Error("Could not parse 'seq' value from ENRTree root entry");if(!o)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:s,seq:Number(i),signature:o}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const n=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(n))throw new Error("Could not parse ENRTree tree entry");n.shift();const[r,s]=n;if(!r)throw new Error("Could not parse public key from ENRTree tree entry");if(!s)throw new Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:s}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const M3t=new rr("discovery:fetch_nodes");async function*L3t(t,e=10,n=3){const r=new Set;let s=0,i=0;for(;sthis._search(s,i)))yield o}}async _search(e,n){try{const r=await this._getTXTRecord(e,n);n.visits[e]=!0;let s,i;const o=B3t(r);try{switch(o){case Ma.ROOT_PREFIX:return s=Ma.parseAndVerifyRoot(r,n.publicKey),await this._search(s,n);case Ma.BRANCH_PREFIX:return i=Ma.parseBranch(r),s=U3t(i,n),await this._search(s,n);case Ma.RECORD_PREFIX:return _8.fromString(r);default:return null}}catch(a){return Hre.error(`Failed to search DNS tree ${o} at subdomain ${e}: ${a}`),null}}catch(r){return Hre.error(`Failed to retrieve TXT record at subdomain ${e}: ${r}`),null}}async _getTXTRecord(e,n){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==n.domain?`${e}.${n.domain}`:n.domain,s=await this.dns.resolveTXT(r);if(!s.length)throw new Error("Received empty result array while fetching TXT record");if(!s[0].length)throw new Error("Received empty TXT record");const i=s.join("");return this._DNSTreeCache[e]=i,i}}function B3t(t){return t.startsWith(Ma.ROOT_PREFIX)?Ma.ROOT_PREFIX:t.startsWith(Ma.BRANCH_PREFIX)?Ma.BRANCH_PREFIX:t.startsWith(Ma.RECORD_PREFIX)?Ma.RECORD_PREFIX:""}function U3t(t,e){const n={};for(const[s,i]of t.entries())e.visits[i]&&(n[s]=!0);if(Object.keys(n).length===t.length)throw new Error("Unresolvable circular path detected");let r;do r=Math.floor(Math.random()*t.length);while(n[r]);return t[r]}const qre=new rr("peer-discovery-dns");class F3t extends Oo{nextPeer;_started;_components;_options;constructor(e,n){super(),this._started=!1,this._components=e,this._options=n;const{enrUrls:r}=n;qre.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){qre.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const n=await GV.dnsOverHttp();this.nextPeer=n.getNextPeer.bind(n,e)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:n,shardInfo:r}=e;if(!n)continue;const s={[Tre]:{value:this._options.tagValue??uSt,ttl:this._options.tagTTL??dSt}};let i=!1;await this._components.peerStore.has(n.id)?(await this._components.peerStore.get(n.id)).tags.has(Tre)||(i=!0,await this._components.peerStore.merge(n.id,{tags:s})):(i=!0,await this._components.peerStore.save(n.id,{tags:s,...r&&{metadata:{shardInfo:nV(r)}}})),i&&this.dispatchEvent(new CustomEvent("peer",{detail:n}))}}stop(){this._started=!1}get[H_](){return!0}get[Symbol.toStringTag](){return L0t}}function j3t(t){return e=>new F3t(e,{enrUrls:t})}const z3t=60,W3t=xh.PEER_EXCHANGE,V3t=50,H3t=3e4,mbe="/vac/waku/peer-exchange/2.0.0-alpha1";class uS{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:n}=e;return new uS({query:{numPeers:n},response:void 0})}encode(){return YN.encode(this.proto)}static decode(e){const n=YN.decode(e);return new uS(n)}get query(){return this.proto.query}get response(){return this.proto.response}}const R9=new rr("peer-exchange");class q3t{components;streamManager;constructor(e){this.components=e,this.streamManager=new O3(mbe,e)}async query(e){const{numPeers:n,peerId:r}=e,s=uS.createRequest({numPeers:BigInt(n)});if(!await this.components.peerStore.has(r))return{peerInfos:null,error:Sn.NO_PEER_AVAILABLE};const o=await this.streamManager.getStream(r);if(!o)return R9.error(`Failed to get a stream for remote peer:${r?.toString?.()}`),{peerInfos:null,error:Sn.NO_STREAM_AVAILABLE};const a=await Tl([s.encode()],NV,o,c4,async c=>await Gu(c));try{const c=new mn;a.forEach(d=>{c.append(d)});const{response:l}=uS.decode(c);return l?{peerInfos:await Promise.all(l.peerInfos.map(d=>d.enr).filter(eV).map(async d=>({ENR:await _8.fromRLP(d)}))),error:null}:(R9.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:Sn.EMPTY_PAYLOAD})}catch(c){return R9.error("Failed to decode push reply",c),{peerInfos:null,error:Sn.DECODE_FAILED}}}}const vu=new rr("peer-exchange-discovery");class K3t extends Oo{components;peerExchange;options;isStarted=!1;queryingPeers=new Set;peerExpirationRecords=new Map;continuousDiscoveryInterval=null;constructor(e,n={}){super(),this.components=e,this.peerExchange=new q3t(e),this.options={...n,TTL:n.TTL??H3t},this.handleDiscoveredPeer=this.handleDiscoveredPeer.bind(this)}start(){this.isStarted||(vu.info("Starting peer exchange node discovery, discovering peers"),this.isStarted=!0,this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),this.continuousDiscoveryInterval=setInterval(()=>{this.handlePeriodicDiscovery()},this.options.TTL))}stop(){this.isStarted&&(vu.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.peerExpirationRecords.clear(),this.continuousDiscoveryInterval&&clearInterval(this.continuousDiscoveryInterval),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[H_](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}async handleDiscoveredPeer(e){this.runQuery(e.detail.peerId,e.detail.protocols)}async handlePeriodicDiscovery(){const e=this.components.connectionManager.getConnections();await Promise.all(e.map(async n=>{try{const r=n.remotePeer.toString();if(!(this.peerExpirationRecords.has(r)?this.peerExpirationRecords.get(r)<=Date.now():!0))return null;const i=await this.components.peerStore.get(n.remotePeer);return this.runQuery(n.remotePeer,i.protocols)}catch(r){return vu.warn("Error getting peer info",r),null}}))}async runQuery(e,n){if(!n.includes(mbe)||this.queryingPeers.has(e.toString())){vu.info(`Skipping peer ${e} as it is already querying or does not support peer exchange`);return}try{this.queryingPeers.add(e.toString()),await this.query(e)}catch(r){vu.error("Error querying peer",r)}this.peerExpirationRecords.set(e.toString(),Date.now()+this.options.TTL),this.queryingPeers.delete(e.toString())}async query(e){const n=e.toString();vu.info(`Querying peer exchange for ${n}`);const{error:r,peerInfos:s}=await this.peerExchange.query({numPeers:z3t,peerId:e});if(r){vu.error(`Peer exchange query to ${n} failed`,r);return}for(const{ENR:i}of s){if(!i){vu.warn(`No ENR in peerInfo object from ${n}, skipping`);continue}const{peerInfo:o,shardInfo:a}=i;if(!o){vu.warn(`No peerInfo in ENR from ${n}, skipping`);continue}const l=!await this.hasShardInfo(o.id)&&a?{metadata:{shardInfo:nV(a)}}:void 0;await this.components.peerStore.merge(o.id,{tags:{[W3t]:{value:V3t}},...l,...o.multiaddrs&&{multiaddrs:o.multiaddrs}}),vu.info(`Discovered peer: ${o.id.toString()}`),this.dispatchEvent(new CustomEvent("peer",{detail:{id:o.id,multiaddrs:o.multiaddrs}}))}}async hasShardInfo(e){try{const n=await this.components.peerStore.get(e);return n?n.metadata.has("shardInfo"):!1}catch(n){vu.warn(`Error getting shard info for ${e.toString()}`,n)}return!1}}function G3t(t={}){return e=>new K3t(e,t)}const Kre=xh.PEER_CACHE,Z3t=50,Y3t=t=>!!t&&typeof t=="object"&&"id"in t&&typeof t.id=="string"&&"multiaddrs"in t&&Array.isArray(t.multiaddrs);class X3t{get(){return[]}set(e){}remove(){}}class Q3t{get(){try{const e=localStorage.getItem("waku:peers");return(e?JSON.parse(e):[]).filter(Y3t)}catch{return[]}}set(e){try{localStorage.setItem("waku:peers",JSON.stringify(e))}catch{}}remove(){try{localStorage.removeItem("waku:peers")}catch{}}}const J3t=()=>{try{if(typeof localStorage<"u")return new Q3t}catch{}return new X3t},pI=new rr("peer-cache");class e5t extends Oo{components;isStarted=!1;cache;constructor(e,n){super(),this.components=e,this.cache=n?.cache??J3t()}get[Symbol.toStringTag](){return`@waku/${Kre}`}async start(){this.isStarted||(pI.info("Starting Peer Cache Discovery"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),await this.discoverPeers(),this.isStarted=!0)}stop(){this.isStarted&&(pI.info("Stopping Peer Cache Discovery"),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer),this.isStarted=!1)}handleDiscoveredPeer=e=>{const{peerId:n,listenAddrs:r}=e.detail,s=r.map(c=>c.toString()),i=n.toString(),o=this.readPeerInfoFromCache(),a=o.findIndex(c=>c.id===i);a!==-1?o[a].multiaddrs=s:o.push({id:i,multiaddrs:s}),this.writePeerInfoToCache(o)};async discoverPeers(){const e=this.readPeerInfoFromCache();for(const n of e){const r=yf(n.id),s=n.multiaddrs.map(i=>er(i));await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:s,tags:{[Kre]:{value:Z3t}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:s}})))}}readPeerInfoFromCache(){try{return this.cache.get()}catch(e){return pI.error("Error parsing peers from cache:",e),[]}}writePeerInfoToCache(e){try{this.cache.set(e)}catch(n){pI.error("Error saving peers to cache:",n)}}}function t5t(t={}){return e=>new e5t(e,t)}function Gre(t,e){const n=[Ire.SANDBOX,Ire.TEST],r=[];return t?.dns&&r.push(j3t(n)),(t?.peerCache||e)&&r.push(t5t({cache:e})),t?.peerExchange&&r.push(G3t()),r}const n5t=new rr("sdk:create"),r5t="js-waku",s5t=10;async function i5t(t,e,n){!e?.hideWebSocketInfo&&!Are()&&(console.info("%cIgnore WebSocket connection failures","background: gray; color: white; font-size: x-large"),console.info("%cWaku tries to discover peers and some of them are expected to fail","background: gray; color: white; font-size: x-large"));const r=e?.filterMultiaddrs===!1||Are()?fwe:E2t;return lSt({transports:[I2t({filter:r})],streamMuxers:[e2t()],connectionEncrypters:[D1t()],...e,services:{identify:Axt({agentVersion:n??r5t}),ping:c2t({maxInboundStreams:e?.pingMaxInboundStreams??s5t}),metadata:pvt(t),...e?.services}})}async function o5t(t){const n=(t.networkConfig??vme).clusterId??bme;n5t.info("Creating Waku node with cluster id: ",n);const r=t?.libp2p??{},s=r.peerDiscovery??[];t?.defaultBootstrap?s.push(...Gre({dns:!0,peerExchange:!0,peerCache:!0,...t.discovery},t.peerCache)):s.push(...Gre(t.discovery,t.peerCache));const i=[...t.bootstrapPeers||[],...t.store?.peers||[]];return i.length&&s.push(K1t({list:i})),r.peerDiscovery=s,i5t(n,r,t?.userAgent)}async function a5t(t={}){const e=await o5t(t),n=new Lvt(t,e,{store:!0,lightpush:!0,filter:!0});return t?.autoStart!==!1&&await n.start(),n}var d6=0,ZV={size:0,kind:17,base:null,node:null,finalizer:null},YV={size:0,kind:17,base:null,node:null,finalizer:null},XV={size:0,kind:17,base:null,node:null,finalizer:null},QV={size:0,kind:17,base:null,node:null,finalizer:null},ybe={size:0,kind:17,base:null,node:null,finalizer:null},wbe={size:0,kind:22,base:null,node:null,finalizer:null},A4={size:0,kind:28,base:null,node:null,finalizer:null},c5t={size:0,kind:29,base:null,node:null,finalizer:null},bbe={size:0,kind:22,base:null,node:null,finalizer:null},W3={size:0,kind:17,base:null,node:null,finalizer:null},Cx={size:0,kind:17,base:null,node:null,finalizer:null},S8={size:0,kind:17,base:null,node:null,finalizer:null},JV={size:0,kind:17,base:null,node:null,finalizer:null},l5t={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};JV.node=l5t;var u5t={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};S8.node=u5t;var d5t={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};Cx.node=d5t;bbe.base=W3;wbe.base=W3;var f5t={kind:2,len:5,offset:0,typ:null,name:null,sons:[{kind:1,offset:"parent",len:0,typ:bbe,name:"parent",sons:null},{kind:1,offset:"name",len:0,typ:c5t,name:"name",sons:null},{kind:1,offset:"message",len:0,typ:A4,name:"msg",sons:null},{kind:1,offset:"trace",len:0,typ:A4,name:"trace",sons:null},{kind:1,offset:"up",len:0,typ:wbe,name:"up",sons:null}]};W3.node=f5t;var h5t={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};ybe.node=h5t;W3.base=ybe;Cx.base=W3;S8.base=Cx;JV.base=S8;var p5t={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};QV.node=p5t;QV.base=S8;var g5t={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};XV.node=g5t;XV.base=Cx;var m5t={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};YV.node=m5t;YV.base=Cx;var y5t={kind:2,len:0,offset:0,typ:null,name:null,sons:[]};ZV.node=y5t;ZV.base=Cx;function w5t(t){var e=null,n=Zre(t.length),r=0,s=0;e:for(;;){if(!(r2147483647||t<-2147483648)&&eH()}function S5t(){V3({message:[118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101],parent:null,m_type:XV,name:null,trace:[],up:null},"RangeDefect")}function A5t(t,e,n,r,s){var i,o=t[e].length;if(t[e].length<(i=v5t(Mg(o,s),0,2147483647),i))for(var a=t[e].length;a>>16&r)>>>0,i=(t&r)>>>0,o=(e>>>16&r)>>>0,a=(e&r)>>>0;return n=(i*a>>>0)+((s*a>>>0)+(i*o>>>0)>>>0<<16>>>0)>>>0,n}function D9(t,e){var n=0;return n=(t<>>0|t>>>TU(32,e))>>>0,n}function R5t(t){var e=0;e:{var n=t.length,r=4,s=b5t(n,r),i=0,o=0;t:for(;;){if(!(o>>0|Number(BigInt.asUintN(32,BigInt(t[I4(Mg(o,c),0,t.length-1)]))))>>>0}o=Mg(o,r),a=gb(a,3432918353),a=D9(a,15),a=gb(a,461845907),i=(i^a)>>>0,i=D9(i,13),i=(i*5>>>0)+3864292196>>>0}var l=0,u=f6(n,r);t:for(;;){if(!(0>>0|Number(BigInt.asUintN(32,BigInt(t[I4(Mg(o,u),0,t.length-1)]))))>>>0}l=gb(l,3432918353),l=D9(l,15),l=gb(l,461845907),i=(i^l)>>>0,i=(i^Number(BigInt.asUintN(32,BigInt(n))))>>>0,i=(i^i>>>16)>>>0,i=gb(i,2246822507),i=(i^i>>>13)>>>0,i=gb(i,3266489909),i=(i^i>>>16)>>>0,e=Number(BigInt.asIntN(32,BigInt(i)));break e}return e}function Yre(t){var e=0;return e=R5t(t.slice(0,t.length-1+1)),e}function Ebe(t,e,n){var r=0,s=f6(O9(Yre(t)),n),i=f6(O9(Yre(t.concat([32,98]))),n);return r=f6(O9(Mg(s,vbe(e,i))),n),r}function O5t(t){V3({message:Xm(null,t,A4),m_type:ZV,parent:null,name:null,trace:[],up:null},"AssertionDefect")}function $5t(t){O5t(t)}function D5t(t){$5t(t)}Ebe([100,117,109,109,121],0,1)!=0&&D5t([110,105,109,95,104,97,115,104,46,110,105,109,40,50,54,44,32,51,41,32,96,104,97,115,104,78,40,34,100,117,109,109,121,34,44,32,48,44,32,49,41,32,61,61,32,48,96,32]);function Xre(t,e,n){const r=Array.from(t).map(s=>s.charCodeAt(0));return Ebe(r,e,n)}const M5t=[new Float32Array([1]),new Float32Array([1,1,.393,.283,.221,.181,.154,.133,.118,.105,.0952,.0869,.08,.074,.0689,.0645,.0606,.0571,.054,.0513,.0488,.0465,.0444,.0425,.0408,.0392,.0377,.0364,.0351,.0339,.0328,.0317,.0308]),new Float32Array([1,1,.4,.237,.155,.109,.0804,.0618,.0489,.0397,.0329,.0276,.0236,.0203,.0177,.0156,.0138,.0123,.0111,.00998,.00906,.00825,.00755,.00694,.00639,.00591,.00548,.0051,.00475,.00444,.00416,.0039,.00367]),new Float32Array([1,1,1,.253,.147,.092,.0609,.0423,.0306,.0228,.0174,.0136,.0108,.00875,.00718,.00596,.0108,.00875,.00718,.00596,.005,.00423,.00362,.00312,.0027,.00236,.00207,.00183,.00162,.00145,.00129,.00116,.00105,949e-6,862e-6,785e-6,717e-6]),new Float32Array([1,1,1,1,.16,.092,.0561,.0359,.024,.0166,.0118,.00864,.00646,.00492,.00381,.003,.00239,.00193,.00158,.0013,.00108,905e-6,764e-6,649e-6,555e-6,478e-6,413e-6,359e-6,314e-6,276e-6,243e-6,215e-6,191e-6]),new Float32Array([1,1,1,1,1,.101,.0578,.0347,.0217,.0141,.00943,.0065,.00459,.00332,.00244,.00183,.00139,.00107,839e-6,663e-6,53e-5,427e-6,347e-6,285e-6,235e-6,196e-6,164e-6,138e-6,117e-6,996e-7,853e-7,733e-7,633e-7]),new Float32Array([1,1,1,1,1,1,.0638,.0364,.0216,.0133,.00844,.00552,.00371,.00255,.00179,.00128,935e-6,692e-6,519e-6,394e-6,303e-6,236e-6,185e-6,147e-6,117e-6,944e-7,766e-7,626e-7,515e-7,426e-7,355e-7,297e-7,25e-6]),new Float32Array([1,1,1,1,1,1,1,1,.0229,.0135,.00819,.00513,.00329,.00217,.00146,.001,702e-6,499e-6,36e-5,264e-6,196e-6,147e-6,112e-6,856e-7,663e-7,518e-7,408e-7,324e-7,259e-7,209e-7,169e-7,138e-7,113e-7]),new Float32Array([1,1,1,1,1,1,1,1,1,.0145,.00846,.00509,.00314,.00199,.00129,852e-6,574e-6,394e-6,275e-6,194e-6,14e-5,101e-6,746e-7,555e-7,417e-7,316e-7,242e-7,187e-7,146e-7,114e-7,901e-8,716e-8,573e-8]),new Float32Array([1,1,1,1,1,1,1,1,1,1,1,.00531,.00317,.00194,.00121,775e-6,505e-6,335e-6,226e-6,155e-6,108e-6,759e-7,542e-7,392e-7,286e-7,211e-7,157e-7,118e-7,896e-8,685e-8,528e-8,41e-7,32e-7]),new Float32Array([1,1,1,1,1,1,1,1,1,1,1,1,.00334,.00198,.0012,744e-6,47e-5,302e-6,198e-6,132e-6,889e-7,609e-7,423e-7,297e-7,211e-7,152e-7,11e-6,807e-8,597e-8,445e-8,335e-8,254e-8,194e-8]),new Float32Array([1,1,1,1,1,1,1,1,1,1,1,1,1,.0021,.00124,747e-6,459e-6,287e-6,183e-6,118e-6,777e-7,518e-7,35e-6,24e-6,166e-7,116e-7,823e-8,589e-8,425e-8,31e-7,228e-8,169e-8,126e-8]),new Float32Array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,778e-6,466e-6,284e-6,176e-6,111e-6,712e-7,463e-7,305e-7,204e-7,138e-7,942e-8,652e-8,456e-8,322e-8,229e-8,165e-8,12e-7,874e-9])],L5t="K must be <= 12",B5t="Specified value of k and error rate not achievable using less than 4 bytes / element.";function U5t(t,e,n=M5t){if(t<0||t>12)throw new Error(L5t);for(let r=2;r + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */N4.exports;(function(t,e){(function(){var n,r="4.17.21",s=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",o="Expected a function",a="Invalid `variable` option passed into `_.template`",c="__lodash_hash_undefined__",l=500,u="__lodash_placeholder__",d=1,f=2,p=4,m=1,y=2,b=1,v=2,x=4,E=8,A=16,_=32,k=64,B=128,W=256,S=512,$=30,R="...",M=800,j=16,z=1,N=2,T=3,U=1/0,L=9007199254740991,P=17976931348623157e292,H=NaN,Y=4294967295,re=Y-1,de=Y>>>1,fe=[["ary",B],["bind",b],["bindKey",v],["curry",E],["curryRight",A],["flip",S],["partial",_],["partialRight",k],["rearg",W]],ve="[object Arguments]",Ee="[object Array]",oe="[object AsyncFunction]",Oe="[object Boolean]",je="[object Date]",V="[object DOMException]",we="[object Error]",Ae="[object Function]",Ie="[object GeneratorFunction]",ge="[object Map]",Me="[object Number]",be="[object Null]",pe="[object Object]",J="[object Promise]",ie="[object Proxy]",ae="[object RegExp]",Pe="[object Set]",$e="[object String]",Re="[object Symbol]",ut="[object Undefined]",Je="[object WeakMap]",ft="[object WeakSet]",Z="[object ArrayBuffer]",O="[object DataView]",F="[object Float32Array]",ne="[object Float64Array]",he="[object Int8Array]",Te="[object Int16Array]",Fe="[object Int32Array]",Bt="[object Uint8Array]",vn="[object Uint8ClampedArray]",Kt="[object Uint16Array]",Dn="[object Uint32Array]",bt=/\b__p \+= '';/g,Gn=/\b(__p \+=) '' \+/g,Zn=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Ls=/&(?:amp|lt|gt|quot|#39);/g,Is=/[&<>"']/g,ha=RegExp(Ls.source),iu=RegExp(Is.source),kf=/<%-([\s\S]+?)%>/g,Bs=/<%([\s\S]+?)%>/g,eo=/<%=([\s\S]+?)%>/g,ou=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ce=/^\w*$/,se=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ue=/[\\^$.*+?()[\]{}|]/g,Ce=RegExp(ue.source),Le=/^\s+/,Qe=/\s/,ht=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,pt=/\{\n\/\* \[wrapped with (.+)\] \*/,zt=/,? & /,Ut=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,on=/[()=,{}\[\]\/\s]/,kn=/\\(\\)?/g,Mn=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,zr=/\w*$/,Wr=/^[-+]0x[0-9a-f]+$/i,ci=/^0b[01]+$/i,cc=/^\[object .+?Constructor\]$/,lc=/^0o[0-7]+$/i,uc=/^(?:0|[1-9]\d*)$/,au=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,dc=/($^)/,Jc=/['\n\r\u2028\u2029\\]/g,vd="\\ud800-\\udfff",_w="\\u0300-\\u036f",Sw="\\ufe20-\\ufe2f",V2e="\\u20d0-\\u20ff",XH=_w+Sw+V2e,QH="\\u2700-\\u27bf",JH="a-z\\xdf-\\xf6\\xf8-\\xff",H2e="\\xac\\xb1\\xd7\\xf7",q2e="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",K2e="\\u2000-\\u206f",G2e=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",eq="A-Z\\xc0-\\xd6\\xd8-\\xde",tq="\\ufe0e\\ufe0f",nq=H2e+q2e+K2e+G2e,eR="['’]",Z2e="["+vd+"]",rq="["+nq+"]",Q3="["+XH+"]",sq="\\d+",Y2e="["+QH+"]",iq="["+JH+"]",oq="[^"+vd+nq+sq+QH+JH+eq+"]",tR="\\ud83c[\\udffb-\\udfff]",X2e="(?:"+Q3+"|"+tR+")",aq="[^"+vd+"]",nR="(?:\\ud83c[\\udde6-\\uddff]){2}",rR="[\\ud800-\\udbff][\\udc00-\\udfff]",Aw="["+eq+"]",cq="\\u200d",lq="(?:"+iq+"|"+oq+")",Q2e="(?:"+Aw+"|"+oq+")",uq="(?:"+eR+"(?:d|ll|m|re|s|t|ve))?",dq="(?:"+eR+"(?:D|LL|M|RE|S|T|VE))?",fq=X2e+"?",hq="["+tq+"]?",J2e="(?:"+cq+"(?:"+[aq,nR,rR].join("|")+")"+hq+fq+")*",eEe="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",tEe="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",pq=hq+fq+J2e,nEe="(?:"+[Y2e,nR,rR].join("|")+")"+pq,rEe="(?:"+[aq+Q3+"?",Q3,nR,rR,Z2e].join("|")+")",sEe=RegExp(eR,"g"),iEe=RegExp(Q3,"g"),sR=RegExp(tR+"(?="+tR+")|"+rEe+pq,"g"),oEe=RegExp([Aw+"?"+iq+"+"+uq+"(?="+[rq,Aw,"$"].join("|")+")",Q2e+"+"+dq+"(?="+[rq,Aw+lq,"$"].join("|")+")",Aw+"?"+lq+"+"+uq,Aw+"+"+dq,tEe,eEe,sq,nEe].join("|"),"g"),aEe=RegExp("["+cq+vd+XH+tq+"]"),cEe=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,lEe=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],uEe=-1,ts={};ts[F]=ts[ne]=ts[he]=ts[Te]=ts[Fe]=ts[Bt]=ts[vn]=ts[Kt]=ts[Dn]=!0,ts[ve]=ts[Ee]=ts[Z]=ts[Oe]=ts[O]=ts[je]=ts[we]=ts[Ae]=ts[ge]=ts[Me]=ts[pe]=ts[ae]=ts[Pe]=ts[$e]=ts[Je]=!1;var Zr={};Zr[ve]=Zr[Ee]=Zr[Z]=Zr[O]=Zr[Oe]=Zr[je]=Zr[F]=Zr[ne]=Zr[he]=Zr[Te]=Zr[Fe]=Zr[ge]=Zr[Me]=Zr[pe]=Zr[ae]=Zr[Pe]=Zr[$e]=Zr[Re]=Zr[Bt]=Zr[vn]=Zr[Kt]=Zr[Dn]=!0,Zr[we]=Zr[Ae]=Zr[Je]=!1;var dEe={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},fEe={"&":"&","<":"<",">":">",'"':""","'":"'"},hEe={"&":"&","<":"<",">":">",""":'"',"'":"'"},pEe={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},gEe=parseFloat,mEe=parseInt,gq=typeof kr=="object"&&kr&&kr.Object===Object&&kr,yEe=typeof self=="object"&&self&&self.Object===Object&&self,Si=gq||yEe||Function("return this")(),iR=e&&!e.nodeType&&e,F0=iR&&!0&&t&&!t.nodeType&&t,mq=F0&&F0.exports===iR,oR=mq&&gq.process,el=function(){try{var xe=F0&&F0.require&&F0.require("util").types;return xe||oR&&oR.binding&&oR.binding("util")}catch{}}(),yq=el&&el.isArrayBuffer,wq=el&&el.isDate,bq=el&&el.isMap,vq=el&&el.isRegExp,xq=el&&el.isSet,Eq=el&&el.isTypedArray;function fc(xe,Ve,Be){switch(Be.length){case 0:return xe.call(Ve);case 1:return xe.call(Ve,Be[0]);case 2:return xe.call(Ve,Be[0],Be[1]);case 3:return xe.call(Ve,Be[0],Be[1],Be[2])}return xe.apply(Ve,Be)}function wEe(xe,Ve,Be,kt){for(var xn=-1,xr=xe==null?0:xe.length;++xn-1}function aR(xe,Ve,Be){for(var kt=-1,xn=xe==null?0:xe.length;++kt-1;);return Be}function Pq(xe,Ve){for(var Be=xe.length;Be--&&Iw(Ve,xe[Be],0)>-1;);return Be}function IEe(xe,Ve){for(var Be=xe.length,kt=0;Be--;)xe[Be]===Ve&&++kt;return kt}var TEe=dR(dEe),NEe=dR(fEe);function PEe(xe){return"\\"+pEe[xe]}function kEe(xe,Ve){return xe==null?n:xe[Ve]}function Tw(xe){return aEe.test(xe)}function REe(xe){return cEe.test(xe)}function OEe(xe){for(var Ve,Be=[];!(Ve=xe.next()).done;)Be.push(Ve.value);return Be}function gR(xe){var Ve=-1,Be=Array(xe.size);return xe.forEach(function(kt,xn){Be[++Ve]=[xn,kt]}),Be}function kq(xe,Ve){return function(Be){return xe(Ve(Be))}}function Tp(xe,Ve){for(var Be=-1,kt=xe.length,xn=0,xr=[];++Be-1}function vCe(h,g){var C=this.__data__,D=m5(C,h);return D<0?(++this.size,C.push([h,g])):C[D][1]=g,this}Rf.prototype.clear=mCe,Rf.prototype.delete=yCe,Rf.prototype.get=wCe,Rf.prototype.has=bCe,Rf.prototype.set=vCe;function Of(h){var g=-1,C=h==null?0:h.length;for(this.clear();++g=g?h:g)),h}function sl(h,g,C,D,q,te){var le,me=g&d,Se=g&f,Ze=g&p;if(C&&(le=q?C(h,D,q,te):C(h)),le!==n)return le;if(!gs(h))return h;var Xe=Cn(h);if(Xe){if(le=__e(h),!me)return pa(h,le)}else{var tt=no(h),xt=tt==Ae||tt==Ie;if($p(h))return hK(h,me);if(tt==pe||tt==ve||xt&&!q){if(le=Se||xt?{}:RK(h),!me)return Se?h_e(h,MCe(le,h)):f_e(h,Wq(le,h))}else{if(!Zr[tt])return q?h:{};le=S_e(h,tt,me)}}te||(te=new lu);var Ft=te.get(h);if(Ft)return Ft;te.set(h,le),aG(h)?h.forEach(function(rn){le.add(sl(rn,g,C,rn,h,te))}):iG(h)&&h.forEach(function(rn,Vn){le.set(Vn,sl(rn,g,C,Vn,h,te))});var nn=Ze?Se?jR:FR:Se?ma:li,Ln=Xe?n:nn(h);return tl(Ln||h,function(rn,Vn){Ln&&(Vn=rn,rn=h[Vn]),Rx(le,Vn,sl(rn,g,C,Vn,h,te))}),le}function LCe(h){var g=li(h);return function(C){return Vq(C,h,g)}}function Vq(h,g,C){var D=C.length;if(h==null)return!D;for(h=Vr(h);D--;){var q=C[D],te=g[q],le=h[q];if(le===n&&!(q in h)||!te(le))return!1}return!0}function Hq(h,g,C){if(typeof h!="function")throw new nl(o);return Ux(function(){h.apply(n,C)},g)}function Ox(h,g,C,D){var q=-1,te=J3,le=!0,me=h.length,Se=[],Ze=g.length;if(!me)return Se;C&&(g=cs(g,hc(C))),D?(te=aR,le=!1):g.length>=s&&(te=Ax,le=!1,g=new W0(g));e:for(;++qq?0:q+C),D=D===n||D>q?q:Rn(D),D<0&&(D+=q),D=C>D?0:lG(D);C0&&C(me)?g>1?Ai(me,g-1,C,D,q):Ip(q,me):D||(q[q.length]=me)}return q}var ER=bK(),Gq=bK(!0);function xd(h,g){return h&&ER(h,g,li)}function CR(h,g){return h&&Gq(h,g,li)}function w5(h,g){return Ap(g,function(C){return Bf(h[C])})}function H0(h,g){g=Rp(g,h);for(var C=0,D=g.length;h!=null&&Cg}function FCe(h,g){return h!=null&&Rr.call(h,g)}function jCe(h,g){return h!=null&&g in Vr(h)}function zCe(h,g,C){return h>=to(g,C)&&h=120&&Xe.length>=120)?new W0(le&&Xe):n}Xe=h[0];var tt=-1,xt=me[0];e:for(;++tt-1;)me!==h&&l5.call(me,Se,1),l5.call(h,Se,1);return h}function iK(h,g){for(var C=h?g.length:0,D=C-1;C--;){var q=g[C];if(C==D||q!==te){var te=q;Lf(q)?l5.call(h,q,1):OR(h,q)}}return h}function PR(h,g){return h+f5(Uq()*(g-h+1))}function t_e(h,g,C,D){for(var q=-1,te=Ys(d5((g-h)/(C||1)),0),le=Be(te);te--;)le[D?te:++q]=h,h+=C;return le}function kR(h,g){var C="";if(!h||g<1||g>L)return C;do g%2&&(C+=h),g=f5(g/2),g&&(h+=h);while(g);return C}function jn(h,g){return GR(DK(h,g,ya),h+"")}function n_e(h){return zq(Uw(h))}function r_e(h,g){var C=Uw(h);return N5(C,V0(g,0,C.length))}function Mx(h,g,C,D){if(!gs(h))return h;g=Rp(g,h);for(var q=-1,te=g.length,le=te-1,me=h;me!=null&&++qq?0:q+g),C=C>q?q:C,C<0&&(C+=q),q=g>C?0:C-g>>>0,g>>>=0;for(var te=Be(q);++D>>1,le=h[te];le!==null&&!gc(le)&&(C?le<=g:le=s){var Ze=g?null:y_e(h);if(Ze)return t5(Ze);le=!1,q=Ax,Se=new W0}else Se=g?[]:me;e:for(;++D=D?h:il(h,g,C)}var fK=GEe||function(h){return Si.clearTimeout(h)};function hK(h,g){if(g)return h.slice();var C=h.length,D=$q?$q(C):new h.constructor(C);return h.copy(D),D}function LR(h){var g=new h.constructor(h.byteLength);return new a5(g).set(new a5(h)),g}function c_e(h,g){var C=g?LR(h.buffer):h.buffer;return new h.constructor(C,h.byteOffset,h.byteLength)}function l_e(h){var g=new h.constructor(h.source,zr.exec(h));return g.lastIndex=h.lastIndex,g}function u_e(h){return kx?Vr(kx.call(h)):{}}function pK(h,g){var C=g?LR(h.buffer):h.buffer;return new h.constructor(C,h.byteOffset,h.length)}function gK(h,g){if(h!==g){var C=h!==n,D=h===null,q=h===h,te=gc(h),le=g!==n,me=g===null,Se=g===g,Ze=gc(g);if(!me&&!Ze&&!te&&h>g||te&&le&&Se&&!me&&!Ze||D&&le&&Se||!C&&Se||!q)return 1;if(!D&&!te&&!Ze&&h=me)return Se;var Ze=C[D];return Se*(Ze=="desc"?-1:1)}}return h.index-g.index}function mK(h,g,C,D){for(var q=-1,te=h.length,le=C.length,me=-1,Se=g.length,Ze=Ys(te-le,0),Xe=Be(Se+Ze),tt=!D;++me1?C[q-1]:n,le=q>2?C[2]:n;for(te=h.length>3&&typeof te=="function"?(q--,te):n,le&&jo(C[0],C[1],le)&&(te=q<3?n:te,q=1),g=Vr(g);++D-1?q[te?g[le]:le]:n}}function EK(h){return Mf(function(g){var C=g.length,D=C,q=rl.prototype.thru;for(h&&g.reverse();D--;){var te=g[D];if(typeof te!="function")throw new nl(o);if(q&&!le&&I5(te)=="wrapper")var le=new rl([],!0)}for(D=le?D:C;++D1&&Yn.reverse(),Xe&&Seme))return!1;var Ze=te.get(h),Xe=te.get(g);if(Ze&&Xe)return Ze==g&&Xe==h;var tt=-1,xt=!0,Ft=C&y?new W0:n;for(te.set(h,g),te.set(g,h);++tt1?"& ":"")+g[D],g=g.join(C>2?", ":" "),h.replace(ht,`{ +/* [wrapped with `+g+`] */ +`)}function I_e(h){return Cn(h)||G0(h)||!!(Lq&&h&&h[Lq])}function Lf(h,g){var C=typeof h;return g=g??L,!!g&&(C=="number"||C!="symbol"&&uc.test(h))&&h>-1&&h%1==0&&h0){if(++g>=M)return arguments[0]}else g=0;return h.apply(n,arguments)}}function N5(h,g){var C=-1,D=h.length,q=D-1;for(g=g===n?D:g;++C1?h[g-1]:n;return C=typeof C=="function"?(h.pop(),C):n,KK(h,C)});function GK(h){var g=Q(h);return g.__chain__=!0,g}function BSe(h,g){return g(h),h}function P5(h,g){return g(h)}var USe=Mf(function(h){var g=h.length,C=g?h[0]:0,D=this.__wrapped__,q=function(te){return xR(te,h)};return g>1||this.__actions__.length||!(D instanceof qn)||!Lf(C)?this.thru(q):(D=D.slice(C,+C+(g?1:0)),D.__actions__.push({func:P5,args:[q],thisArg:n}),new rl(D,this.__chain__).thru(function(te){return g&&!te.length&&te.push(n),te}))});function FSe(){return GK(this)}function jSe(){return new rl(this.value(),this.__chain__)}function zSe(){this.__values__===n&&(this.__values__=cG(this.value()));var h=this.__index__>=this.__values__.length,g=h?n:this.__values__[this.__index__++];return{done:h,value:g}}function WSe(){return this}function VSe(h){for(var g,C=this;C instanceof g5;){var D=jK(C);D.__index__=0,D.__values__=n,g?q.__wrapped__=D:g=D;var q=D;C=C.__wrapped__}return q.__wrapped__=h,g}function HSe(){var h=this.__wrapped__;if(h instanceof qn){var g=h;return this.__actions__.length&&(g=new qn(this)),g=g.reverse(),g.__actions__.push({func:P5,args:[ZR],thisArg:n}),new rl(g,this.__chain__)}return this.thru(ZR)}function qSe(){return uK(this.__wrapped__,this.__actions__)}var KSe=E5(function(h,g,C){Rr.call(h,C)?++h[C]:$f(h,C,1)});function GSe(h,g,C){var D=Cn(h)?Cq:BCe;return C&&jo(h,g,C)&&(g=n),D(h,en(g,3))}function ZSe(h,g){var C=Cn(h)?Ap:Kq;return C(h,en(g,3))}var YSe=xK(zK),XSe=xK(WK);function QSe(h,g){return Ai(k5(h,g),1)}function JSe(h,g){return Ai(k5(h,g),U)}function e3e(h,g,C){return C=C===n?1:Rn(C),Ai(k5(h,g),C)}function ZK(h,g){var C=Cn(h)?tl:Pp;return C(h,en(g,3))}function YK(h,g){var C=Cn(h)?bEe:qq;return C(h,en(g,3))}var t3e=E5(function(h,g,C){Rr.call(h,C)?h[C].push(g):$f(h,C,[g])});function n3e(h,g,C,D){h=ga(h)?h:Uw(h),C=C&&!D?Rn(C):0;var q=h.length;return C<0&&(C=Ys(q+C,0)),M5(h)?C<=q&&h.indexOf(g,C)>-1:!!q&&Iw(h,g,C)>-1}var r3e=jn(function(h,g,C){var D=-1,q=typeof g=="function",te=ga(h)?Be(h.length):[];return Pp(h,function(le){te[++D]=q?fc(g,le,C):$x(le,g,C)}),te}),s3e=E5(function(h,g,C){$f(h,C,g)});function k5(h,g){var C=Cn(h)?cs:Jq;return C(h,en(g,3))}function i3e(h,g,C,D){return h==null?[]:(Cn(g)||(g=g==null?[]:[g]),C=D?n:C,Cn(C)||(C=C==null?[]:[C]),rK(h,g,C))}var o3e=E5(function(h,g,C){h[C?0:1].push(g)},function(){return[[],[]]});function a3e(h,g,C){var D=Cn(h)?cR:Iq,q=arguments.length<3;return D(h,en(g,4),C,q,Pp)}function c3e(h,g,C){var D=Cn(h)?vEe:Iq,q=arguments.length<3;return D(h,en(g,4),C,q,qq)}function l3e(h,g){var C=Cn(h)?Ap:Kq;return C(h,$5(en(g,3)))}function u3e(h){var g=Cn(h)?zq:n_e;return g(h)}function d3e(h,g,C){(C?jo(h,g,C):g===n)?g=1:g=Rn(g);var D=Cn(h)?OCe:r_e;return D(h,g)}function f3e(h){var g=Cn(h)?$Ce:i_e;return g(h)}function h3e(h){if(h==null)return 0;if(ga(h))return M5(h)?Nw(h):h.length;var g=no(h);return g==ge||g==Pe?h.size:IR(h).length}function p3e(h,g,C){var D=Cn(h)?lR:o_e;return C&&jo(h,g,C)&&(g=n),D(h,en(g,3))}var g3e=jn(function(h,g){if(h==null)return[];var C=g.length;return C>1&&jo(h,g[0],g[1])?g=[]:C>2&&jo(g[0],g[1],g[2])&&(g=[g[0]]),rK(h,Ai(g,1),[])}),R5=ZEe||function(){return Si.Date.now()};function m3e(h,g){if(typeof g!="function")throw new nl(o);return h=Rn(h),function(){if(--h<1)return g.apply(this,arguments)}}function XK(h,g,C){return g=C?n:g,g=h&&g==null?h.length:g,Df(h,B,n,n,n,n,g)}function QK(h,g){var C;if(typeof g!="function")throw new nl(o);return h=Rn(h),function(){return--h>0&&(C=g.apply(this,arguments)),h<=1&&(g=n),C}}var XR=jn(function(h,g,C){var D=b;if(C.length){var q=Tp(C,Lw(XR));D|=_}return Df(h,D,g,C,q)}),JK=jn(function(h,g,C){var D=b|v;if(C.length){var q=Tp(C,Lw(JK));D|=_}return Df(g,D,h,C,q)});function eG(h,g,C){g=C?n:g;var D=Df(h,E,n,n,n,n,n,g);return D.placeholder=eG.placeholder,D}function tG(h,g,C){g=C?n:g;var D=Df(h,A,n,n,n,n,n,g);return D.placeholder=tG.placeholder,D}function nG(h,g,C){var D,q,te,le,me,Se,Ze=0,Xe=!1,tt=!1,xt=!0;if(typeof h!="function")throw new nl(o);g=al(g)||0,gs(C)&&(Xe=!!C.leading,tt="maxWait"in C,te=tt?Ys(al(C.maxWait)||0,g):te,xt="trailing"in C?!!C.trailing:xt);function Ft(Ns){var du=D,Ff=q;return D=q=n,Ze=Ns,le=h.apply(Ff,du),le}function nn(Ns){return Ze=Ns,me=Ux(Vn,g),Xe?Ft(Ns):le}function Ln(Ns){var du=Ns-Se,Ff=Ns-Ze,xG=g-du;return tt?to(xG,te-Ff):xG}function rn(Ns){var du=Ns-Se,Ff=Ns-Ze;return Se===n||du>=g||du<0||tt&&Ff>=te}function Vn(){var Ns=R5();if(rn(Ns))return Yn(Ns);me=Ux(Vn,Ln(Ns))}function Yn(Ns){return me=n,xt&&D?Ft(Ns):(D=q=n,le)}function mc(){me!==n&&fK(me),Ze=0,D=Se=q=me=n}function zo(){return me===n?le:Yn(R5())}function yc(){var Ns=R5(),du=rn(Ns);if(D=arguments,q=this,Se=Ns,du){if(me===n)return nn(Se);if(tt)return fK(me),me=Ux(Vn,g),Ft(Se)}return me===n&&(me=Ux(Vn,g)),le}return yc.cancel=mc,yc.flush=zo,yc}var y3e=jn(function(h,g){return Hq(h,1,g)}),w3e=jn(function(h,g,C){return Hq(h,al(g)||0,C)});function b3e(h){return Df(h,S)}function O5(h,g){if(typeof h!="function"||g!=null&&typeof g!="function")throw new nl(o);var C=function(){var D=arguments,q=g?g.apply(this,D):D[0],te=C.cache;if(te.has(q))return te.get(q);var le=h.apply(this,D);return C.cache=te.set(q,le)||te,le};return C.cache=new(O5.Cache||Of),C}O5.Cache=Of;function $5(h){if(typeof h!="function")throw new nl(o);return function(){var g=arguments;switch(g.length){case 0:return!h.call(this);case 1:return!h.call(this,g[0]);case 2:return!h.call(this,g[0],g[1]);case 3:return!h.call(this,g[0],g[1],g[2])}return!h.apply(this,g)}}function v3e(h){return QK(2,h)}var x3e=a_e(function(h,g){g=g.length==1&&Cn(g[0])?cs(g[0],hc(en())):cs(Ai(g,1),hc(en()));var C=g.length;return jn(function(D){for(var q=-1,te=to(D.length,C);++q=g}),G0=Yq(function(){return arguments}())?Yq:function(h){return xs(h)&&Rr.call(h,"callee")&&!Mq.call(h,"callee")},Cn=Be.isArray,M3e=yq?hc(yq):VCe;function ga(h){return h!=null&&D5(h.length)&&!Bf(h)}function Ts(h){return xs(h)&&ga(h)}function L3e(h){return h===!0||h===!1||xs(h)&&Fo(h)==Oe}var $p=XEe||lO,B3e=wq?hc(wq):HCe;function U3e(h){return xs(h)&&h.nodeType===1&&!Fx(h)}function F3e(h){if(h==null)return!0;if(ga(h)&&(Cn(h)||typeof h=="string"||typeof h.splice=="function"||$p(h)||Bw(h)||G0(h)))return!h.length;var g=no(h);if(g==ge||g==Pe)return!h.size;if(Bx(h))return!IR(h).length;for(var C in h)if(Rr.call(h,C))return!1;return!0}function j3e(h,g){return Dx(h,g)}function z3e(h,g,C){C=typeof C=="function"?C:n;var D=C?C(h,g):n;return D===n?Dx(h,g,n,C):!!D}function JR(h){if(!xs(h))return!1;var g=Fo(h);return g==we||g==V||typeof h.message=="string"&&typeof h.name=="string"&&!Fx(h)}function W3e(h){return typeof h=="number"&&Bq(h)}function Bf(h){if(!gs(h))return!1;var g=Fo(h);return g==Ae||g==Ie||g==oe||g==ie}function sG(h){return typeof h=="number"&&h==Rn(h)}function D5(h){return typeof h=="number"&&h>-1&&h%1==0&&h<=L}function gs(h){var g=typeof h;return h!=null&&(g=="object"||g=="function")}function xs(h){return h!=null&&typeof h=="object"}var iG=bq?hc(bq):KCe;function V3e(h,g){return h===g||AR(h,g,WR(g))}function H3e(h,g,C){return C=typeof C=="function"?C:n,AR(h,g,WR(g),C)}function q3e(h){return oG(h)&&h!=+h}function K3e(h){if(P_e(h))throw new xn(i);return Xq(h)}function G3e(h){return h===null}function Z3e(h){return h==null}function oG(h){return typeof h=="number"||xs(h)&&Fo(h)==Me}function Fx(h){if(!xs(h)||Fo(h)!=pe)return!1;var g=c5(h);if(g===null)return!0;var C=Rr.call(g,"constructor")&&g.constructor;return typeof C=="function"&&C instanceof C&&s5.call(C)==HEe}var eO=vq?hc(vq):GCe;function Y3e(h){return sG(h)&&h>=-L&&h<=L}var aG=xq?hc(xq):ZCe;function M5(h){return typeof h=="string"||!Cn(h)&&xs(h)&&Fo(h)==$e}function gc(h){return typeof h=="symbol"||xs(h)&&Fo(h)==Re}var Bw=Eq?hc(Eq):YCe;function X3e(h){return h===n}function Q3e(h){return xs(h)&&no(h)==Je}function J3e(h){return xs(h)&&Fo(h)==ft}var e5e=A5(TR),t5e=A5(function(h,g){return h<=g});function cG(h){if(!h)return[];if(ga(h))return M5(h)?cu(h):pa(h);if(Ix&&h[Ix])return OEe(h[Ix]());var g=no(h),C=g==ge?gR:g==Pe?t5:Uw;return C(h)}function Uf(h){if(!h)return h===0?h:0;if(h=al(h),h===U||h===-U){var g=h<0?-1:1;return g*P}return h===h?h:0}function Rn(h){var g=Uf(h),C=g%1;return g===g?C?g-C:g:0}function lG(h){return h?V0(Rn(h),0,Y):0}function al(h){if(typeof h=="number")return h;if(gc(h))return H;if(gs(h)){var g=typeof h.valueOf=="function"?h.valueOf():h;h=gs(g)?g+"":g}if(typeof h!="string")return h===0?h:+h;h=Tq(h);var C=ci.test(h);return C||lc.test(h)?mEe(h.slice(2),C?2:8):Wr.test(h)?H:+h}function uG(h){return Ed(h,ma(h))}function n5e(h){return h?V0(Rn(h),-L,L):h===0?h:0}function Ir(h){return h==null?"":pc(h)}var r5e=Dw(function(h,g){if(Bx(g)||ga(g)){Ed(g,li(g),h);return}for(var C in g)Rr.call(g,C)&&Rx(h,C,g[C])}),dG=Dw(function(h,g){Ed(g,ma(g),h)}),L5=Dw(function(h,g,C,D){Ed(g,ma(g),h,D)}),s5e=Dw(function(h,g,C,D){Ed(g,li(g),h,D)}),i5e=Mf(xR);function o5e(h,g){var C=$w(h);return g==null?C:Wq(C,g)}var a5e=jn(function(h,g){h=Vr(h);var C=-1,D=g.length,q=D>2?g[2]:n;for(q&&jo(g[0],g[1],q)&&(D=1);++C1),te}),Ed(h,jR(h),C),D&&(C=sl(C,d|f|p,w_e));for(var q=g.length;q--;)OR(C,g[q]);return C});function S5e(h,g){return hG(h,$5(en(g)))}var A5e=Mf(function(h,g){return h==null?{}:JCe(h,g)});function hG(h,g){if(h==null)return{};var C=cs(jR(h),function(D){return[D]});return g=en(g),sK(h,C,function(D,q){return g(D,q[0])})}function I5e(h,g,C){g=Rp(g,h);var D=-1,q=g.length;for(q||(q=1,h=n);++Dg){var D=h;h=g,g=D}if(C||h%1||g%1){var q=Uq();return to(h+q*(g-h+gEe("1e-"+((q+"").length-1))),g)}return PR(h,g)}var B5e=Mw(function(h,g,C){return g=g.toLowerCase(),h+(C?mG(g):g)});function mG(h){return rO(Ir(h).toLowerCase())}function yG(h){return h=Ir(h),h&&h.replace(au,TEe).replace(iEe,"")}function U5e(h,g,C){h=Ir(h),g=pc(g);var D=h.length;C=C===n?D:V0(Rn(C),0,D);var q=C;return C-=g.length,C>=0&&h.slice(C,q)==g}function F5e(h){return h=Ir(h),h&&iu.test(h)?h.replace(Is,NEe):h}function j5e(h){return h=Ir(h),h&&Ce.test(h)?h.replace(ue,"\\$&"):h}var z5e=Mw(function(h,g,C){return h+(C?"-":"")+g.toLowerCase()}),W5e=Mw(function(h,g,C){return h+(C?" ":"")+g.toLowerCase()}),V5e=vK("toLowerCase");function H5e(h,g,C){h=Ir(h),g=Rn(g);var D=g?Nw(h):0;if(!g||D>=g)return h;var q=(g-D)/2;return S5(f5(q),C)+h+S5(d5(q),C)}function q5e(h,g,C){h=Ir(h),g=Rn(g);var D=g?Nw(h):0;return g&&D>>0,C?(h=Ir(h),h&&(typeof g=="string"||g!=null&&!eO(g))&&(g=pc(g),!g&&Tw(h))?Op(cu(h),0,C):h.split(g,C)):[]}var J5e=Mw(function(h,g,C){return h+(C?" ":"")+rO(g)});function eAe(h,g,C){return h=Ir(h),C=C==null?0:V0(Rn(C),0,h.length),g=pc(g),h.slice(C,C+g.length)==g}function tAe(h,g,C){var D=Q.templateSettings;C&&jo(h,g,C)&&(g=n),h=Ir(h),g=L5({},g,D,IK);var q=L5({},g.imports,D.imports,IK),te=li(q),le=pR(q,te),me,Se,Ze=0,Xe=g.interpolate||dc,tt="__p += '",xt=mR((g.escape||dc).source+"|"+Xe.source+"|"+(Xe===eo?Mn:dc).source+"|"+(g.evaluate||dc).source+"|$","g"),Ft="//# sourceURL="+(Rr.call(g,"sourceURL")?(g.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++uEe+"]")+` +`;h.replace(xt,function(rn,Vn,Yn,mc,zo,yc){return Yn||(Yn=mc),tt+=h.slice(Ze,yc).replace(Jc,PEe),Vn&&(me=!0,tt+=`' + +__e(`+Vn+`) + +'`),zo&&(Se=!0,tt+=`'; +`+zo+`; +__p += '`),Yn&&(tt+=`' + +((__t = (`+Yn+`)) == null ? '' : __t) + +'`),Ze=yc+rn.length,rn}),tt+=`'; +`;var nn=Rr.call(g,"variable")&&g.variable;if(!nn)tt=`with (obj) { +`+tt+` +} +`;else if(on.test(nn))throw new xn(a);tt=(Se?tt.replace(bt,""):tt).replace(Gn,"$1").replace(Zn,"$1;"),tt="function("+(nn||"obj")+`) { +`+(nn?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(me?", __e = _.escape":"")+(Se?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+tt+`return __p +}`;var Ln=bG(function(){return xr(te,Ft+"return "+tt).apply(n,le)});if(Ln.source=tt,JR(Ln))throw Ln;return Ln}function nAe(h){return Ir(h).toLowerCase()}function rAe(h){return Ir(h).toUpperCase()}function sAe(h,g,C){if(h=Ir(h),h&&(C||g===n))return Tq(h);if(!h||!(g=pc(g)))return h;var D=cu(h),q=cu(g),te=Nq(D,q),le=Pq(D,q)+1;return Op(D,te,le).join("")}function iAe(h,g,C){if(h=Ir(h),h&&(C||g===n))return h.slice(0,Rq(h)+1);if(!h||!(g=pc(g)))return h;var D=cu(h),q=Pq(D,cu(g))+1;return Op(D,0,q).join("")}function oAe(h,g,C){if(h=Ir(h),h&&(C||g===n))return h.replace(Le,"");if(!h||!(g=pc(g)))return h;var D=cu(h),q=Nq(D,cu(g));return Op(D,q).join("")}function aAe(h,g){var C=$,D=R;if(gs(g)){var q="separator"in g?g.separator:q;C="length"in g?Rn(g.length):C,D="omission"in g?pc(g.omission):D}h=Ir(h);var te=h.length;if(Tw(h)){var le=cu(h);te=le.length}if(C>=te)return h;var me=C-Nw(D);if(me<1)return D;var Se=le?Op(le,0,me).join(""):h.slice(0,me);if(q===n)return Se+D;if(le&&(me+=Se.length-me),eO(q)){if(h.slice(me).search(q)){var Ze,Xe=Se;for(q.global||(q=mR(q.source,Ir(zr.exec(q))+"g")),q.lastIndex=0;Ze=q.exec(Xe);)var tt=Ze.index;Se=Se.slice(0,tt===n?me:tt)}}else if(h.indexOf(pc(q),me)!=me){var xt=Se.lastIndexOf(q);xt>-1&&(Se=Se.slice(0,xt))}return Se+D}function cAe(h){return h=Ir(h),h&&ha.test(h)?h.replace(Ls,LEe):h}var lAe=Mw(function(h,g,C){return h+(C?" ":"")+g.toUpperCase()}),rO=vK("toUpperCase");function wG(h,g,C){return h=Ir(h),g=C?n:g,g===n?REe(h)?FEe(h):CEe(h):h.match(g)||[]}var bG=jn(function(h,g){try{return fc(h,n,g)}catch(C){return JR(C)?C:new xn(C)}}),uAe=Mf(function(h,g){return tl(g,function(C){C=Cd(C),$f(h,C,XR(h[C],h))}),h});function dAe(h){var g=h==null?0:h.length,C=en();return h=g?cs(h,function(D){if(typeof D[1]!="function")throw new nl(o);return[C(D[0]),D[1]]}):[],jn(function(D){for(var q=-1;++qL)return[];var C=Y,D=to(h,Y);g=en(g),h-=Y;for(var q=hR(D,g);++C0||g<0)?new qn(C):(h<0?C=C.takeRight(-h):h&&(C=C.drop(h)),g!==n&&(g=Rn(g),C=g<0?C.dropRight(-g):C.take(g-h)),C)},qn.prototype.takeRightWhile=function(h){return this.reverse().takeWhile(h).reverse()},qn.prototype.toArray=function(){return this.take(Y)},xd(qn.prototype,function(h,g){var C=/^(?:filter|find|map|reject)|While$/.test(g),D=/^(?:head|last)$/.test(g),q=Q[D?"take"+(g=="last"?"Right":""):g],te=D||/^find/.test(g);q&&(Q.prototype[g]=function(){var le=this.__wrapped__,me=D?[1]:arguments,Se=le instanceof qn,Ze=me[0],Xe=Se||Cn(le),tt=function(Vn){var Yn=q.apply(Q,Ip([Vn],me));return D&&xt?Yn[0]:Yn};Xe&&C&&typeof Ze=="function"&&Ze.length!=1&&(Se=Xe=!1);var xt=this.__chain__,Ft=!!this.__actions__.length,nn=te&&!xt,Ln=Se&&!Ft;if(!te&&Xe){le=Ln?le:new qn(this);var rn=h.apply(le,me);return rn.__actions__.push({func:P5,args:[tt],thisArg:n}),new rl(rn,xt)}return nn&&Ln?h.apply(this,me):(rn=this.thru(tt),nn?D?rn.value()[0]:rn.value():rn)})}),tl(["pop","push","shift","sort","splice","unshift"],function(h){var g=n5[h],C=/^(?:push|sort|unshift)$/.test(h)?"tap":"thru",D=/^(?:pop|shift)$/.test(h);Q.prototype[h]=function(){var q=arguments;if(D&&!this.__chain__){var te=this.value();return g.apply(Cn(te)?te:[],q)}return this[C](function(le){return g.apply(Cn(le)?le:[],q)})}}),xd(qn.prototype,function(h,g){var C=Q[g];if(C){var D=C.name+"";Rr.call(Ow,D)||(Ow[D]=[]),Ow[D].push({name:g,func:C})}}),Ow[C5(n,v).name]=[{name:"wrapper",func:n}],qn.prototype.clone=cCe,qn.prototype.reverse=lCe,qn.prototype.value=uCe,Q.prototype.at=USe,Q.prototype.chain=FSe,Q.prototype.commit=jSe,Q.prototype.next=zSe,Q.prototype.plant=VSe,Q.prototype.reverse=HSe,Q.prototype.toJSON=Q.prototype.valueOf=Q.prototype.value=qSe,Q.prototype.first=Q.prototype.head,Ix&&(Q.prototype[Ix]=WSe),Q},Pw=jEe();F0?((F0.exports=Pw)._=Pw,iR._=Pw):Si._=Pw}).call(kr)})(N4,N4.exports);var F5t=N4.exports;const j5t=Zi(F5t);class _x{messageId;channelId;senderId;causalHistory;lamportTimestamp;bloomFilter;content;retrievalHint;constructor(e,n,r,s,i,o,a,c){this.messageId=e,this.channelId=n,this.senderId=r,this.causalHistory=s,this.lamportTimestamp=i,this.bloomFilter=o,this.content=a,this.retrievalHint=c}encode(){return JN.encode(this)}static decode(e){const{messageId:n,channelId:r,senderId:s,causalHistory:i,lamportTimestamp:o,bloomFilter:a,content:c}=JN.decode(e);return new _x(n,r,s,i,o,a,c)}}class z5t extends _x{messageId;channelId;senderId;causalHistory;lamportTimestamp;bloomFilter;content;retrievalHint;constructor(e,n,r,s,i,o,a,c){super(e,n,r,s,i,o,a,c),this.messageId=e,this.channelId=n,this.senderId=r,this.causalHistory=s,this.lamportTimestamp=i,this.bloomFilter=o,this.content=a,this.retrievalHint=c}}function Jre(t){return"lamportTimestamp"in t&&typeof t.lamportTimestamp=="number"&&(t.content===void 0||t.content.length===0)}class W5t extends _x{messageId;channelId;senderId;causalHistory;lamportTimestamp;bloomFilter;content;retrievalHint;constructor(e,n,r,s,i,o,a,c){if(!a||!a.length)throw Error("Ephemeral Message must have content");super(e,n,r,s,i,o,a,c),this.messageId=e,this.channelId=n,this.senderId=r,this.causalHistory=s,this.lamportTimestamp=i,this.bloomFilter=o,this.content=a,this.retrievalHint=c}}function V5t(t){return!!(t.lamportTimestamp===void 0&&"content"in t&&t.content&&t.content.length)}class H5t extends _x{messageId;channelId;senderId;causalHistory;lamportTimestamp;bloomFilter;content;retrievalHint;constructor(e,n,r,s,i,o,a,c){if(!a.length)throw Error("Content Message must have content");super(e,n,r,s,i,o,a,c),this.messageId=e,this.channelId=n,this.senderId=r,this.causalHistory=s,this.lamportTimestamp=i,this.bloomFilter=o,this.content=a,this.retrievalHint=c}valueOf(){return`${this.lamportTimestamp.toString().padStart(16,"0")}_${this.messageId}`}}function ph(t){return!!("lamportTimestamp"in t&&typeof t.lamportTimestamp=="number"&&t.content&&t.content.length)}class q5t{items=[];constructor(){return new Proxy(this,{get(e,n){return typeof n=="string"&&!isNaN(Number(n))?e.items[Number(n)]:e[n]}})}get length(){return this.items.length}push(...e){for(const n of e)this.validateMessage(n);return this.items=j5t.sortedUniqBy([...this.items,...e],"messageId"),this.items.length}some(e,n){return this.items.some(e,n)}slice(e,n){return this.items.slice(e,n)}find(e,n){return this.items.find(e,n)}validateMessage(e){if(!ph(e))throw new Error("Message must have lamportTimestamp and content defined, sync and ephemeral messages cannot be stored")}}const K5t={capacity:1e4,errorRate:.001},G5t=200,Z5t=2,us=new rr("waku:sds:message-channel");let ese=class PU extends Oo{channelId;senderId;lamportTimestamp;filter;outgoingBuffer;possibleAcks;incomingBuffer;localHistory;timeReceived;causalHistorySize;possibleAcksThreshold;timeoutForLostMessagesMs;tasks=[];handlers={[yg.Send]:async e=>{await this._pushOutgoingMessage(e.payload,e.callback)},[yg.Receive]:async e=>{this._pushIncomingMessage(e.message)},[yg.SendEphemeral]:async e=>{await this._pushOutgoingEphemeralMessage(e.payload,e.callback)}};constructor(e,n,r={},s=new q5t){super(),this.channelId=e,this.senderId=n,this.lamportTimestamp=0,this.filter=new Qre(K5t),this.outgoingBuffer=[],this.possibleAcks=new Map,this.incomingBuffer=[],this.localHistory=s,this.causalHistorySize=r.causalHistorySize??G5t,this.possibleAcksThreshold=r.possibleAcksThreshold??Z5t,this.timeReceived=new Map,this.timeoutForLostMessagesMs=r.timeoutForLostMessagesMs}static getMessageId(e){return Dv(VP(e))}async processTasks(){for(;this.tasks.length>0;){const e=this.tasks.shift();e&&await this.executeTask(e)}}async pushOutgoingMessage(e,n){if(!e||!e.length)throw Error("Only messages with valid payloads are allowed");this.tasks.push({command:yg.Send,params:{payload:e,callback:n}})}async pushOutgoingEphemeralMessage(e,n){this.tasks.push({command:yg.SendEphemeral,params:{payload:e,callback:n}})}pushIncomingMessage(e,n){e.retrievalHint=n,this.tasks.push({command:yg.Receive,params:{message:e}})}sweepIncomingBuffer(){const{buffer:e,missing:n}=this.incomingBuffer.reduce(({buffer:r,missing:s},i)=>{us.info(this.senderId,"sweeping incoming buffer",i.messageId,i.causalHistory.map(a=>a.messageId));const o=i.causalHistory.filter(a=>!this.localHistory.some(({messageId:c})=>c===a.messageId));if(o.length===0)return ph(i)&&this.deliverMessage(i)&&this.safeSendEvent(Ps.InMessageDelivered,{detail:i.messageId}),{buffer:r,missing:s};if(us.info(this.senderId,i.messageId,"is missing dependencies",o.map(({messageId:a,retrievalHint:c})=>({messageId:a,retrievalHint:c}))),this.timeoutForLostMessagesMs){const a=this.timeReceived.get(i.messageId);if(a&&Date.now()-a>this.timeoutForLostMessagesMs)return this.safeSendEvent(Ps.InMessageLost,{detail:Array.from(o)}),{buffer:r,missing:s}}return o.forEach(a=>{s.add(a)}),{buffer:r.concat(i),missing:s}},{buffer:new Array,missing:new Set});return this.incomingBuffer=e,this.safeSendEvent(Ps.InMessageMissing,{detail:Array.from(n)}),Array.from(n)}sweepOutgoingBuffer(){return this.outgoingBuffer.reduce(({unacknowledged:e,possiblyAcknowledged:n},r)=>this.possibleAcks.has(r.messageId)?{unacknowledged:e,possiblyAcknowledged:n.concat(r)}:{unacknowledged:e.concat(r),possiblyAcknowledged:n},{unacknowledged:new Array,possiblyAcknowledged:new Array})}async pushOutgoingSyncMessage(e){this.lamportTimestamp++;const n=new z5t(`sync-${Math.random().toString(36).substring(2)}`,this.channelId,this.senderId,this.localHistory.slice(-this.causalHistorySize).map(({messageId:r,retrievalHint:s})=>({messageId:r,retrievalHint:s})),this.lamportTimestamp,this.filter.toBytes(),void 0);if(e)try{return await e(n),us.info(this.senderId,"sync message sent",n.messageId),this.safeSendEvent(Ps.OutSyncSent,{detail:n}),!0}catch(r){throw us.error("Callback execution failed in pushOutgoingSyncMessage:",r),r}return!1}_pushIncomingMessage(e){if(e.channelId!==this.channelId){us.warn("dropping message on different channel",e.channelId);return}if(us.info(`${this.senderId} incoming message ${e.messageId}`,`retrieval hint: ${Dv(e.retrievalHint??new Uint8Array)}`),e.content&&e.content.length>0&&this.timeReceived.has(e.messageId)){us.info(this.senderId,"dropping dupe incoming message",e.messageId);return}if(this.senderId===e.senderId){us.info(this.senderId,"ignoring own incoming message");return}if(V5t(e)){us.info(this.senderId,"delivering ephemeral message");return}if(!Jre(e)&&!ph(e)){us.error(this.senderId,"internal error, a message is neither sync nor ephemeral nor content, ignoring it",e);return}Jre(e)?this.safeSendEvent(Ps.InSyncReceived,{detail:e}):this.safeSendEvent(Ps.InMessageReceived,{detail:e}),this.reviewAckStatus(e),ph(e)&&this.filter.insert(e.messageId);const s=e.causalHistory.filter(i=>!this.localHistory.some(({messageId:o})=>o===i.messageId));s.length>0?(this.incomingBuffer.push(e),this.timeReceived.set(e.messageId,Date.now()),us.info(this.senderId,e.messageId,"is missing dependencies",s.map(i=>i.messageId))):ph(e)&&this.deliverMessage(e)&&this.safeSendEvent(Ps.InMessageDelivered,{detail:e.messageId})}async executeTask(e){try{const n=this.handlers[e.command];await n(e.params)}catch(n){us.error(`Task execution failed for command ${e.command}:`,n),this.dispatchEvent(new CustomEvent("taskError",{detail:{command:e.command,error:n,params:e.params}})),this.safeSendEvent(Ps.ErrorTask,{detail:{command:e.command,error:n,params:e.params}})}}safeSendEvent(e,n){try{this.dispatchEvent(new CustomEvent(e,n))}catch(r){us.error(`Failed to dispatch event ${e}:`,r)}}async _pushOutgoingMessage(e,n){this.lamportTimestamp++;const r=PU.getMessageId(e);let s=this.outgoingBuffer.find(i=>i.messageId===r);if(s?us.info(this.senderId,"resending message",r):(us.info(this.senderId,"sending new message",r),s=new H5t(r,this.channelId,this.senderId,this.localHistory.slice(-this.causalHistorySize).map(({messageId:i,retrievalHint:o})=>({messageId:i,retrievalHint:o})),this.lamportTimestamp,this.filter.toBytes(),e),this.outgoingBuffer.push(s)),n)try{const{success:i,retrievalHint:o}=await n(s);i&&ph(s)&&(s.retrievalHint=o,this.filter.insert(r),this.localHistory.push(s),this.timeReceived.set(r,Date.now()),this.safeSendEvent(Ps.OutMessageSent,{detail:s}))}catch(i){throw us.error("Callback execution failed in _pushOutgoingMessage:",i),i}}async _pushOutgoingEphemeralMessage(e,n){const r=new W5t(PU.getMessageId(e),this.channelId,this.senderId,[],void 0,void 0,e);if(n)try{await n(r)}catch(s){throw us.error("Callback execution failed in _pushOutgoingEphemeralMessage:",s),s}}deliverMessage(e){return ph(e)?(us.info(this.senderId,"delivering message",e.messageId,e.retrievalHint),e.lamportTimestamp>this.lamportTimestamp&&(this.lamportTimestamp=e.lamportTimestamp),this.localHistory.find(({messageId:r})=>r===e.messageId)||(e.retrievalHint||us.warn("message delivered without a retrieval hint",e.messageId),this.localHistory.push(e)),!0):!1}reviewAckStatus(e){if(us.info(this.senderId,"reviewing ack status using causal history:",e.causalHistory.map(r=>r.messageId)),us.info(this.senderId,"current outgoing buffer:",this.outgoingBuffer.map(r=>r.messageId)),e.causalHistory.forEach(({messageId:r})=>{this.outgoingBuffer=this.outgoingBuffer.filter(({messageId:s})=>s!==r?!0:(us.info(this.senderId,"message acknowledged",r),this.safeSendEvent(Ps.OutMessageAcknowledged,{detail:r}),!1))}),!e.bloomFilter)return;const n=Qre.fromBytes(e.bloomFilter,this.filter.options);this.outgoingBuffer=this.outgoingBuffer.filter(r=>{if(!n.lookup(r.messageId))return!0;const s=(this.possibleAcks.get(r.messageId)??0)+1;return sthis.lastSuccessfulQuery||n>this.forceQueryThresholdMs?await this.query(e):og.info("no querying")}async query(e){og.info(`perform store query to ${e.toString()}`);const{timeStart:n,timeEnd:r}=this.queryTimeRange();try{for await(const s of this._queryGenerator(this.decoders,{timeStart:n,timeEnd:r,peerId:e})){const i=(await Promise.all(s)).filter(o=>o!==void 0);this.dispatchMessages(i)}this.lastSuccessfulQuery=Date.now()}catch(s){og.warn(`store query to ${e.toString()} failed`,s)}}queryTimeRange(){return J5t(Date.now(),this.lastSuccessfulQuery,X5t)}dispatchMessages(e){og.info("dispatching messages",e.map(n=>n.hashStr)),this.dispatchEvent(new CustomEvent(P4.MessagesRetrieved,{detail:e}))}setupEventListeners(){this.peerManagerEventEmitter.addEventListener(Uu.StoreConnect,e=>void this.maybeQuery(e.detail).catch(n=>og.error("query-on-connect error",n))),this.wakuEventEmitter.addEventListener(cp.Health,this.updateLastOfflineDate.bind(this))}unsetEventListeners(){this.peerManagerEventEmitter.removeEventListener(Uu.StoreConnect,e=>void this.maybeQuery(e.detail).catch(n=>og.error("query-on-connect error",n))),this.wakuEventEmitter.removeEventListener(cp.Health,this.updateLastOfflineDate.bind(this))}updateLastOfflineDate(e){e.detail===Vs.Unhealthy&&(this.lastTimeOffline=Date.now())}}function J5t(t,e,n){const r=Math.min(t-e,n),s=new Date(t-r),i=new Date(t);return{timeStart:s,timeEnd:i}}var Il;(function(t){t.OutMessageSending="channel:out:message-sending",t.OutMessageSent="channel:out:message-sent",t.OutMessagePossiblyAcknowledged="channel:out:message-possibly-acknowledged",t.OutMessageAcknowledged="channel:out:message-acknowledged",t.OutMessageRetriesError="channel:out:message-retries-error",t.OutMessageIrrecoverableError="channel:out:message-irrecoverable-error",t.InMessageReceived="channel:in:message-received",t.InIrretrievableMessage="channel:in:message-irretrievable"})(Il||(Il={}));const M9=new rr("sdk:missing-message-retriever"),eAt=10*1e3;class tAt{decoder;retrieveFrequencyMs;_retrieve;onMessageRetrieved;retrieveInterval;missingMessages;constructor(e,n=eAt,r,s){this.decoder=e,this.retrieveFrequencyMs=n,this._retrieve=r,this.onMessageRetrieved=s,this.missingMessages=new Map}start(){this.retrieveInterval&&clearInterval(this.retrieveInterval),this.retrieveFrequencyMs&&(M9.info(`start retrieve loop every ${this.retrieveFrequencyMs}ms`),this.retrieveInterval=setInterval(()=>{this.retrieveMissingMessage()},this.retrieveFrequencyMs))}stop(){this.retrieveInterval&&clearInterval(this.retrieveInterval)}addMissingMessage(e,n){this.missingMessages.has(e)||(M9.info("missing message notice",e,n),this.missingMessages.set(e,n))}removeMissingMessage(e){this.missingMessages.has(e)&&this.missingMessages.delete(e)}async retrieveMissingMessage(){if(this.missingMessages.size){const e=Array.from(this.missingMessages.values());M9.info("attempting to retrieve missing message",e.length);for await(const n of this._retrieve([this.decoder],{messageHashes:e}))for await(const r of n)r&&this.onMessageRetrieved&&await this.onMessageRetrieved(r)}}}class nAt{retryIntervalMs;maxRetryNumber;timeouts;constructor(e,n){if(this.retryIntervalMs=e,this.maxRetryNumber=n,this.timeouts=new Map,!e||e<=0||!n||n<=0)throw Error(`Invalid retryIntervalMs ${e} or maxRetryNumber ${n} values`)}stopRetries(e){const n=this.timeouts.get(e);n&&clearTimeout(n)}startRetries(e,n){this.retry(e,n,0)}retry(e,n,r){if(clearTimeout(this.timeouts.get(e)),r{n(),this.retry(e,n,++r)},this.retryIntervalMs);this.timeouts.set(e,s)}}}const mb=new rr("sdk:reliable-channel"),rAt=30*1e3,sAt=30*1e3,iAt=10,oAt=[Sn.ENCODE_FAILED,Sn.EMPTY_PAYLOAD,Sn.SIZE_TOO_BIG,Sn.RLN_PROOF_GENERATION,Sn.TOPIC_DECODER_MISMATCH,Sn.INVALID_DECODER_TOPICS];class Mm extends Oo{node;messageChannel;encoder;decoder;_send;_subscribe;_retrieve;syncMinIntervalMs;syncTimeout;retryManager;missingMessageRetriever;queryOnConnect;isStarted;constructor(e,n,r,s,i){if(super(),this.node=e,this.messageChannel=n,this.encoder=r,this.decoder=s,e.lightPush)this._send=e.lightPush.send.bind(e.lightPush);else if(e.relay)this._send=e.relay.send.bind(e.relay);else throw"No protocol available to send messages";if(e.filter)this._subscribe=e.filter.subscribe.bind(e.filter);else throw e.relay?"Not implemented":"No protocol available to receive messages";if(e.store){this._retrieve=e.store.queryGenerator.bind(e.store);const c=e?.peerManager?.events;c!==void 0&&(i?.queryOnConnect??!0)&&(mb.info("auto-query enabled"),this.queryOnConnect=new Q5t([this.decoder],c,e.events,this._retrieve.bind(this)))}this.syncMinIntervalMs=i?.syncMinIntervalMs??rAt;const o=i?.retryIntervalMs??sAt,a=i?.maxRetryAttempts??iAt;o&&a&&(this.retryManager=new nAt(o,a)),this._retrieve&&(this.missingMessageRetriever=new tAt(this.decoder,i?.retrieveFrequencyMs,this._retrieve,async c=>{await this.processIncomingMessage(c),await this.messageChannel.processTasks(),this.messageChannel.sweepIncomingBuffer()})),this.isStarted=!1}static getMessageId(e){return ese.getMessageId(e)}static async create(e,n,r,s,i,o){const a=new ese(n,r,o),c=new Mm(e,a,s,i,o);return(o?.autoStart??!0)&&(await e.start(),await c.start()),c}async send(e){this.assertStarted();const n=this._wrapAndSend.bind(this,e),r=Mm.getMessageId(e);return this.retryManager?.startRetries(r,n),n()}async _wrapAndSend(e){await this.messageChannel.pushOutgoingMessage(e,async n=>{const s={payload:n.encode()},i=await this.encoder.toProtoObj(s);if(!i)return{success:!1};const o=Xk(this.encoder.pubsubTopic,i),a=Mm.getMessageId(e);this.safeSendEvent(Il.OutMessageSending,{detail:a});const c=await this._send(this.encoder,s);for(const{error:l}of c.failures)if(oAt.includes(l))return mb.error("Irrecoverable error, cannot send message: ",l),this.safeSendEvent(Il.OutMessageIrrecoverableError,{detail:{messageId:a,error:l}}),{success:!1,retrievalHint:o};return{success:!0,retrievalHint:o}}),await this.messageChannel.processTasks(),this.messageChannel.sweepOutgoingBuffer()}async subscribe(){return this.assertStarted(),this._subscribe(this.decoder,async e=>{await this.processIncomingMessage(e),this.messageChannel.sweepIncomingBuffer()})}async processIncomingMessage(e){const n=_x.decode(e.payload);if(n.channelId!==this.messageChannel.channelId){mb.warn("ignoring message with different channel id",n.channelId);return}const r=e.hash;if(mb.info(`processing message ${n.messageId}:${e.hashStr}`),this.messageChannel.pushIncomingMessage(n,r),this.missingMessageRetriever?.removeMissingMessage(n.messageId),n.content&&n.content.length>0){const{payload:s,...i}=e,o=Object.assign(i,{payload:n.content,hash:e.hash,hashStr:e.hashStr,version:e.version,contentTopic:e.contentTopic,pubsubTopic:e.pubsubTopic,timestamp:e.timestamp,rateLimitProof:e.rateLimitProof,ephemeral:e.ephemeral,meta:e.meta});this.safeSendEvent(Il.InMessageReceived,{detail:o})}await this.messageChannel.processTasks()}async processIncomingMessages(e){for(const n of e)await this.processIncomingMessage(n);this.messageChannel.sweepIncomingBuffer()}async start(){return this.isStarted?!0:(this.isStarted=!0,this.setupEventListeners(),this.restartSync(),this._retrieve&&(this.missingMessageRetriever?.start(),this.queryOnConnect?.start()),this.subscribe())}stop(){this.isStarted&&(this.isStarted=!1,this.stopSync(),this.missingMessageRetriever?.stop(),this.queryOnConnect?.stop())}assertStarted(){if(!this.isStarted)throw Error("Message Channel must be started")}restartSync(e=1){if(this.syncTimeout&&clearTimeout(this.syncTimeout),this.syncMinIntervalMs){const n=this.random()*this.syncMinIntervalMs*e;this.syncTimeout=setTimeout(()=>{this.sendSyncMessage(),this.restartSync(2)},n)}}stopSync(){this.syncTimeout&&clearTimeout(this.syncTimeout)}random(){return Math.random()}safeSendEvent(e,n){try{this.dispatchEvent(new CustomEvent(e,n))}catch(r){mb.error(`Failed to dispatch event ${e}:`,r)}}async sendSyncMessage(){this.assertStarted(),await this.messageChannel.pushOutgoingSyncMessage(async e=>{const r={payload:e.encode()},s=await this._send(this.encoder,r);return s.failures.length>0?(mb.error("Error sending sync message: ",s),!1):!0}),await this.messageChannel.processTasks(),this.messageChannel.sweepOutgoingBuffer()}setupEventListeners(){this.messageChannel.addEventListener(Ps.OutMessageSent,e=>{if(e.detail.content){const n=Mm.getMessageId(e.detail.content);this.safeSendEvent(Il.OutMessageSent,{detail:n})}}),this.messageChannel.addEventListener(Ps.OutMessageAcknowledged,e=>{e.detail&&(this.safeSendEvent(Il.OutMessageAcknowledged,{detail:e.detail}),this.retryManager?.stopRetries(e.detail))}),this.messageChannel.addEventListener(Ps.OutMessagePossiblyAcknowledged,e=>{e.detail&&this.safeSendEvent(Il.OutMessagePossiblyAcknowledged,{detail:{messageId:e.detail.messageId,possibleAckCount:e.detail.count}})}),this.messageChannel.addEventListener(Ps.InSyncReceived,e=>{this.restartSync()}),this.messageChannel.addEventListener(Ps.InMessageReceived,e=>{ph(e.detail)&&this.restartSync(.5)}),this.messageChannel.addEventListener(Ps.OutMessageSent,e=>{ph(e.detail)&&this.restartSync()}),this.messageChannel.addEventListener(Ps.InMessageMissing,e=>{for(const{messageId:n,retrievalHint:r}of e.detail)r&&this.missingMessageRetriever&&this.missingMessageRetriever.addMissingMessage(n,r)}),this.queryOnConnect&&this.queryOnConnect.addEventListener(P4.MessagesRetrieved,e=>{this.processIncomingMessages(e.detail)})}}class nH{node=null;_isReady=!1;_currentHealth=Vs.Unhealthy;healthListeners=new Set;static async create(){const e=new nH;return await e.initialize(),e}async initialize(){this.node=await a5t({defaultBootstrap:!0,autoStart:!0}),this.setupHealthMonitoring()}setupHealthMonitoring(){this.node&&this.node.events.addEventListener(cp.Health,e=>{const n=e.detail;this._currentHealth=n;const r=this._isReady;this._isReady=n===Vs.SufficientlyHealthy||n===Vs.MinimallyHealthy,r!==this._isReady&&this.notifyHealthChange()})}notifyHealthChange(){this.healthListeners.forEach(e=>e(this._isReady,this._currentHealth))}getNode(){if(!this.node)throw new Error("Node not initialized");return this.node}async stop(){this.healthListeners.clear(),this.node&&(await this.node.stop(),this.node=null)}get isInitialized(){return this.node!==null}get isReady(){return this._isReady}get currentHealth(){return this._currentHealth}onHealthChange(e){return this.healthListeners.add(e),e(this._isReady,this._currentHealth),()=>{this.healthListeners.delete(e)}}}let aAt=class{constructor(e,n){this.reliableMessaging=e,this.nodeManager=n,this.setupMessageHandling()}messageReceivedCallbacks=new Set;setupMessageHandling(){this.reliableMessaging&&this.reliableMessaging.onMessage(async e=>{ct.setSyncing(!0);const n=await ct.updateCache(e);ct.clearPending(e.id),ct.setSyncing(!1),n&&this.messageReceivedCallbacks.forEach(r=>r(e))})}async sendMessage(e,n){if(!this.reliableMessaging)return{success:!1,error:"Reliable messaging not initialized"};if(!this.nodeManager.isReady)return{success:!1,error:"Network not ready"};try{return await ct.updateCache(e),ct.markPending(e.id),ct.setSyncing(!0),await this.reliableMessaging.sendMessage(e,{onSent:r=>{console.log(`Message ${r} sent`),n?.onSent?.(r)},onAcknowledged:r=>{console.log(`Message ${r} acknowledged`),n?.onAcknowledged?.(r),ct.clearPending(e.id),ct.updateLastSync(Date.now()),ct.setSyncing(!1)},onError:(r,s)=>{console.error(`Message ${r} failed:`,s),n?.onError?.(r,s),ct.setSyncing(!1)}}),{success:!0,message:e}}catch(r){return console.error("Error sending message:",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}onMessageReceived(e){return this.messageReceivedCallbacks.add(e),()=>this.messageReceivedCallbacks.delete(e)}updateReliableMessaging(e){this.reliableMessaging=e,this.setupMessageHandling()}get messageCache(){return ct.cache}cleanup(){this.messageReceivedCallbacks.clear(),this.reliableMessaging?.cleanup()}};const tse="/opchan-demo/1/messages/proto";class cAt{constructor(e){this.node=e,this.encoder=this.node.createEncoder({contentTopic:tse}),this.decoder=this.node.createDecoder({contentTopic:tse})}encoder;decoder;encodeMessage(e){const n=JSON.stringify(e);return new TextEncoder().encode(n)}decodeMessage(e){const n=new TextDecoder().decode(e),r=JSON.parse(n);switch(r.type){case os.CELL:return r;case os.POST:return r;case os.COMMENT:return r;case os.VOTE:return r;case os.MODERATE:return r;case os.USER_PROFILE_UPDATE:return r;default:throw new Error("Unknown message type: ",r)}}getEncoder(){return this.encoder}getDecoder(){return this.decoder}getAllDecoders(){return[this.decoder]}getDecoders(e){return[this.decoder]}}class lAt{channel=null;messageCallbacks=new Map;incomingMessageCallbacks=new Set;codecManager;constructor(e){this.codecManager=new cAt(e),this.initializeChannel(e)}async initializeChannel(e){const n=this.codecManager.getEncoder(),r=this.codecManager.getDecoder(),s=m4e(),i="opchan-messages";try{this.channel=await Mm.create(e,i,s,n,r),this.setupChannelListeners(this.channel)}catch(o){console.error("Failed to create reliable channel:",o)}}setupChannelListeners(e){e.addEventListener(Il.InMessageReceived,n=>{try{const r=n.detail;if(r.payload){const s=this.codecManager.decodeMessage(r.payload);this.incomingMessageCallbacks.forEach(i=>i(s))}}catch(r){console.error("Failed to process incoming message:",r)}}),e.addEventListener(Il.OutMessageSent,n=>{const r=n.detail;this.messageCallbacks.get(r)?.onSent?.(r)}),e.addEventListener(Il.OutMessageAcknowledged,n=>{const r=n.detail;this.messageCallbacks.get(r)?.onAcknowledged?.(r)}),e.addEventListener(Il.OutMessageIrrecoverableError,n=>{const r=n.detail.messageId,s=n.detail.error,i=this.messageCallbacks.get(r);i?.onError&&i.onError(r,s?.toString()||"Unknown error"),this.messageCallbacks.delete(r)})}async sendMessage(e,n){if(!this.channel)throw new Error("Reliable channel not initialized");const r=this.codecManager.encodeMessage(e),s=Mm.getMessageId(r);n&&this.messageCallbacks.set(s,n);try{return this.channel.send(r)}catch(i){throw this.messageCallbacks.delete(s),i}}onMessage(e){return this.incomingMessageCallbacks.add(e),()=>this.incomingMessageCallbacks.delete(e)}cleanup(){this.messageCallbacks.clear(),this.incomingMessageCallbacks.clear(),this.channel=null}}class rH{nodeManager=null;messageService=null;reliableMessaging=null;constructor(){}static async create(){const e=new rH;return await e.initialize(),e}async initialize(){try{this.nodeManager=await nH.create(),this.messageService=new aAt(this.reliableMessaging,this.nodeManager),this.nodeManager.onHealthChange(e=>{e&&!this.reliableMessaging?this.initializeReliableMessaging():!e&&this.reliableMessaging&&this.cleanupReliableMessaging()})}catch(e){throw console.error("Failed to initialize MessageManager:",e),e}}async initializeReliableMessaging(){if(!(!this.nodeManager||this.reliableMessaging))try{console.log("Initializing reliable messaging..."),this.reliableMessaging=new lAt(this.nodeManager.getNode()),this.messageService?.updateReliableMessaging(this.reliableMessaging),console.log("Reliable messaging initialized successfully")}catch(e){console.error("Failed to initialize reliable messaging:",e)}}cleanupReliableMessaging(){this.reliableMessaging&&(console.log("Cleaning up reliable messaging due to health status"),this.reliableMessaging.cleanup(),this.reliableMessaging=null,this.messageService?.updateReliableMessaging(null))}async stop(){this.cleanupReliableMessaging(),this.messageService?.cleanup(),await this.nodeManager?.stop()}get isReady(){return this.nodeManager?.isReady??!1}get currentHealth(){return this.nodeManager?.currentHealth??Vs.Unhealthy}onHealthChange(e){if(!this.nodeManager)throw new Error("Node manager not initialized");return this.nodeManager.onHealthChange(e)}async sendMessage(e,n){if(!this.messageService)throw new Error("MessageManager not fully initialized");this.messageService.sendMessage(e,n)}onMessageReceived(e){if(!this.messageService)throw new Error("MessageManager not fully initialized");return this.messageService.onMessageReceived(e)}get messageCache(){if(!this.messageService)throw new Error("MessageManager not fully initialized");return this.messageService.messageCache}}const _n=await rH.create();class bo{static BASE_SCORES={POST:10,COMMENT:5,CELL:15};static ENGAGEMENT_SCORES={UPVOTE:1,COMMENT:.5};static VERIFICATION_BONUS=1.25;static BASIC_VERIFICATION_BONUS=1.1;static VERIFIED_UPVOTE_BONUS=.1;static VERIFIED_COMMENTER_BONUS=.05;static DECAY_RATE=.1;static MODERATION_PENALTY=.5;calculatePostScore(e,n,r,s){let i=this.applyBaseScore("POST");const o=i,a=n.filter(_=>_.value===1),c=this.applyEngagementScore(a,r);i+=c;const{bonus:l,isVerified:u}=this.applyAuthorVerificationBonus(i,e.authorAddress,s);i+=l;const{bonus:d,verifiedUpvotes:f}=this.applyVerifiedUpvoteBonus(a,s);i+=d;const{bonus:p,verifiedCommenters:m}=this.applyVerifiedCommenterBonus(r,s);i+=p;const{decayedScore:y,multiplier:b,daysOld:v}=this.applyTimeDecay(i,e.timestamp);i=y;const{penalizedScore:x,penalty:E}=this.applyModerationPenalty(i,e.moderated||!1);i=x;const A=Math.max(0,i);return{score:A,details:{baseScore:o,engagementScore:c,authorVerificationBonus:l,verifiedUpvoteBonus:d,verifiedCommenterBonus:p,timeDecayMultiplier:b,moderationPenalty:E,finalScore:A,isVerified:u,upvotes:a.length,comments:r.length,verifiedUpvotes:f,verifiedCommenters:m,daysOld:v,isModerated:e.moderated||!1}}}calculateCommentScore(e,n,r){let s=this.applyBaseScore("COMMENT");const i=s,o=n.filter(x=>x.value===1),a=this.applyEngagementScore(o,[]);s+=a;const{bonus:c,isVerified:l}=this.applyAuthorVerificationBonus(s,e.authorAddress,r);s+=c;const{bonus:u,verifiedUpvotes:d}=this.applyVerifiedUpvoteBonus(o,r);s+=u;const{decayedScore:f,multiplier:p,daysOld:m}=this.applyTimeDecay(s,e.timestamp);s=f;const{penalizedScore:y,penalty:b}=this.applyModerationPenalty(s,e.moderated||!1);s=y;const v=Math.max(0,s);return{score:v,details:{baseScore:i,engagementScore:a,authorVerificationBonus:c,verifiedUpvoteBonus:u,verifiedCommenterBonus:0,timeDecayMultiplier:p,moderationPenalty:b,finalScore:v,isVerified:l,upvotes:o.length,comments:0,verifiedUpvotes:d,verifiedCommenters:0,daysOld:m,isModerated:e.moderated||!1}}}calculateCellScore(e,n){let r=this.applyBaseScore("CELL");const s=r,i=n.filter(y=>y.cellId===e.id),o=i.reduce((y,b)=>y+(b.upvotes?.length||0),0),a=i.length*bo.ENGAGEMENT_SCORES.COMMENT,c=o*.1,l=a+c;r+=l;const u=i.reduce((y,b)=>b.timestamp>y.timestamp?b:y,{timestamp:Date.now()}),{decayedScore:d,multiplier:f,daysOld:p}=this.applyTimeDecay(r,u.timestamp);r=d;const m=Math.max(0,r);return{score:m,details:{baseScore:s,engagementScore:l,authorVerificationBonus:0,verifiedUpvoteBonus:0,verifiedCommenterBonus:0,timeDecayMultiplier:f,moderationPenalty:1,finalScore:m,isVerified:!1,upvotes:o,comments:i.length,verifiedUpvotes:0,verifiedCommenters:0,daysOld:p,isModerated:!1}}}isUserVerified(e){return!!(e.ensDetails||e.ordinalDetails||e.verificationStatus===Ct.WALLET_CONNECTED)}buildUserVerificationStatus(e){const n={};return e.forEach(r=>{n[r.address]={isVerified:this.isUserVerified(r),hasENS:!!r.ensDetails,hasOrdinal:!!r.ordinalDetails,ensName:r.ensDetails?.ensName,verificationStatus:r.verificationStatus}}),n}applyBaseScore(e){return bo.BASE_SCORES[e]}applyEngagementScore(e,n=[]){const r=e.length*bo.ENGAGEMENT_SCORES.UPVOTE,s=n.length*bo.ENGAGEMENT_SCORES.COMMENT;return r+s}applyAuthorVerificationBonus(e,n,r){const s=r[n];if(!(s?.isVerified||!1))return{bonus:0,isVerified:!1};let o=0;return s?.hasENS||s?.hasOrdinal?o=e*(bo.VERIFICATION_BONUS-1):s?.isVerified&&(o=e*(bo.BASIC_VERIFICATION_BONUS-1)),{bonus:o,isVerified:!0}}applyVerifiedUpvoteBonus(e,n){const r=e.filter(i=>n[i.author]?.isVerified);return{bonus:r.length*bo.VERIFIED_UPVOTE_BONUS,verifiedUpvotes:r.length}}applyVerifiedCommenterBonus(e,n){const r=new Set;return e.forEach(i=>{n[i.authorAddress]?.isVerified&&r.add(i.authorAddress)}),{bonus:r.size*bo.VERIFIED_COMMENTER_BONUS,verifiedCommenters:r.size}}applyTimeDecay(e,n){const r=(Date.now()-n)/864e5,s=Math.exp(-bo.DECAY_RATE*r);return{decayedScore:e*s,multiplier:s,daysOld:r}}applyModerationPenalty(e,n){return n?{penalizedScore:e*bo.MODERATION_PENALTY,penalty:bo.MODERATION_PENALTY}:{penalizedScore:e,penalty:1}}}const Cbe=async(t,e,n,r)=>{const s={id:t.id,type:t.type,author:t.author,name:t.name,description:t.description,icon:t.icon||"",timestamp:t.timestamp,signature:t.signature,browserPubKey:t.browserPubKey,delegationProof:t.delegationProof};if(n&&r){const o=new bo().calculateCellScore(s,r),a=r.filter(l=>l.cellId===t.id),c=new Set;return a.forEach(l=>{c.add(l.authorAddress)}),{...s,relevanceScore:o.score,activeMemberCount:c.size,relevanceDetails:o.details}}return s},_be=async(t,e,n)=>{const s=Object.values(_n.messageCache.votes).filter(f=>f.targetId===t.id),i=s.filter(f=>f!==null&&f.value===1),o=s.filter(f=>f!==null&&f.value===-1),a=_n.messageCache.moderations[t.id],c=!!a&&a.targetType==="post"&&a.action===Ou.MODERATE,l=Object.values(_n.messageCache.moderations).find(f=>f.targetType==="user"&&f.cellId===t.cellId&&f.targetId===t.author),u=!!l&&l.action===Ou.MODERATE,d={id:t.id,type:t.type,author:t.author,cellId:t.cellId,authorAddress:t.author,title:t.title,content:t.content,timestamp:t.timestamp,signature:t.signature,browserPubKey:t.browserPubKey,delegationProof:t.delegationProof,upvotes:i,downvotes:o,moderated:c||u,moderatedBy:c?a.author:u?l.author:void 0,moderationReason:c?a.reason:u?l.reason:void 0,moderationTimestamp:c?a.timestamp:u?l.timestamp:void 0};if(n){const f=new bo,m=(await Promise.all(Object.values(_n.messageCache.comments).map(E=>sH(E,void 0,n))).then(E=>E.filter(A=>A!==null))).filter(E=>E.postId===t.id),y=f.calculatePostScore(d,s,m,n),b=y.score,v=i.filter(E=>n[E.author]?.isVerified).length,x=new Set;return m.forEach(E=>{n[E.authorAddress]?.isVerified&&x.add(E.authorAddress)}),{...d,relevanceScore:b,verifiedUpvotes:v,verifiedCommenters:Array.from(x),relevanceDetails:y.details}}return d},sH=async(t,e,n)=>{const s=Object.values(_n.messageCache.votes).filter(p=>p.targetId===t.id),i=s.filter(p=>p!==null&&p.value===1),o=s.filter(p=>p!==null&&p.value===-1),a=_n.messageCache.moderations[t.id],c=!!a&&a.targetType==="comment"&&a.action===Ou.MODERATE,l=Object.values(_n.messageCache.posts).find(p=>p.id===t.postId),u=Object.values(_n.messageCache.moderations).find(p=>p.targetType==="user"&&p.cellId===l?.cellId&&p.targetId===t.author),d=!!u&&u.action===Ou.MODERATE,f={id:t.id,type:t.type,author:t.author,postId:t.postId,authorAddress:t.author,content:t.content,timestamp:t.timestamp,signature:t.signature,browserPubKey:t.browserPubKey,delegationProof:t.delegationProof,upvotes:i,downvotes:o,moderated:c||d,moderatedBy:c?a.author:d?u.author:void 0,moderationReason:c?a.reason:d?u.reason:void 0,moderationTimestamp:c?a.timestamp:d?u.timestamp:void 0};if(n){const m=new bo().calculateCommentScore(f,s.filter(y=>y!==null),n);return{...f,relevanceScore:m.score,relevanceDetails:m.details}}return f},uAt=async(t,e)=>{const n=await Promise.all(Object.values(_n.messageCache.posts).map(i=>_be(i,void 0,e))).then(i=>i.filter(o=>o!==null)),r=await Promise.all(Object.values(_n.messageCache.comments).map(i=>sH(i,void 0,e))).then(i=>i.filter(o=>o!==null));return{cells:await Promise.all(Object.values(_n.messageCache.cells).map(i=>Cbe(i,void 0,e,n))).then(i=>i.filter(o=>o!==null)),posts:n,comments:r}};class dAt{delegationManager;constructor(e){this.delegationManager=e||new vh}validatePermission(e,n,r){const s=n?.verificationStatus||Ct.WALLET_UNCONNECTED;switch(e){case"createCell":if(s!==Ct.ENS_ORDINAL_VERIFIED)return{valid:!1,error:"Only ENS or Logos ordinal owners can create cells"};break;case"createPost":case"createComment":case"vote":if(s===Ct.WALLET_UNCONNECTED)return{valid:!1,error:"Connect your wallet to perform this action"};break}return{valid:!0}}async createPost(e,n){const{cellId:r,title:s,content:i,currentUser:o,isAuthenticated:a}=e,c=this.validatePermission("createPost",o,a);if(!c.valid)return{success:!1,error:c.error};try{const l=kd(),u={type:os.POST,id:l,cellId:r,title:s,content:i,timestamp:Date.now(),author:o.address},d=await this.delegationManager.signMessage(u);if(!d)return{success:!1,error:(await this.delegationManager.getStatus(o.address,o.walletType)).isValid?"Key delegation required. Please delegate a signing key from your profile menu.":"Key delegation expired. Please re-delegate your key through the profile menu."};await ct.updateCache(d),ct.markPending(d.id),ct.setSyncing(!0),n(),_n.sendMessage(d).catch(p=>console.error("Background send failed:",p)).finally(()=>ct.setSyncing(!1));const f=await _be(d);return f?{success:!0,data:f}:{success:!1,error:"Failed to transform post data."}}catch(l){return console.error("Error creating post:",l),{success:!1,error:"Failed to create post. Please try again."}}}async createComment(e,n){const{postId:r,content:s,currentUser:i,isAuthenticated:o}=e,a=this.validatePermission("createComment",i,o);if(!a.valid)return{success:!1,error:a.error};try{const c=kd(),l={type:os.COMMENT,id:c,postId:r,content:s,timestamp:Date.now(),author:i.address},u=await this.delegationManager.signMessage(l);if(!u)return{success:!1,error:(await this.delegationManager.getStatus(i.address,i.walletType)).isValid?"Key delegation required. Please delegate a signing key from your profile menu.":"Key delegation expired. Please re-delegate your key through the profile menu."};await ct.updateCache(u),ct.markPending(u.id),ct.setSyncing(!0),n(),_n.sendMessage(u).catch(f=>console.error("Background send failed:",f)).finally(()=>ct.setSyncing(!1));const d=await sH(u);return d?{success:!0,data:d}:{success:!1,error:"Failed to transform comment data."}}catch(c){return console.error("Error creating comment:",c),{success:!1,error:"Failed to add comment. Please try again."}}}async createCell(e,n){const{name:r,description:s,icon:i,currentUser:o,isAuthenticated:a}=e,c=this.validatePermission("createCell",o,a);if(!c.valid)return{success:!1,error:c.error};try{const l=kd(),u={type:os.CELL,id:l,name:r,description:s,...i&&{icon:i},timestamp:Date.now(),author:o.address},d=await this.delegationManager.signMessage(u);if(!d)return{success:!1,error:(await this.delegationManager.getStatus(o.address,o.walletType)).isValid?"Key delegation required. Please delegate a signing key from your profile menu.":"Key delegation expired. Please re-delegate your key through the profile menu."};await ct.updateCache(d),ct.markPending(d.id),ct.setSyncing(!0),n(),_n.sendMessage(d).catch(p=>console.error("Background send failed:",p)).finally(()=>ct.setSyncing(!1));const f=await Cbe(d);return f?{success:!0,data:f}:{success:!1,error:"Failed to transform cell data."}}catch(l){return console.error("Error creating cell:",l),{success:!1,error:"Failed to create cell. Please try again."}}}async vote(e,n){const{targetId:r,isUpvote:s,currentUser:i,isAuthenticated:o}=e,a=this.validatePermission("vote",i,o);if(!a.valid)return{success:!1,error:a.error};try{const c=kd(),l={type:os.VOTE,id:c,targetId:r,value:s?1:-1,timestamp:Date.now(),author:i.address},u=await this.delegationManager.signMessage(l);return u?(await ct.updateCache(u),ct.markPending(u.id),ct.setSyncing(!0),n(),_n.sendMessage(u).catch(d=>console.error("Background send failed:",d)).finally(()=>ct.setSyncing(!1)),{success:!0,data:!0}):{success:!1,error:(await this.delegationManager.getStatus(i.address,i.walletType)).isValid?"Key delegation required. Please delegate a signing key from your profile menu.":"Key delegation expired. Please re-delegate your key through the profile menu."}}catch(c){return console.error("Error voting:",c),{success:!1,error:"Failed to register your vote. Please try again."}}}async moderatePost(e,n){const{cellId:r,postId:s,reason:i,currentUser:o,isAuthenticated:a,cellOwner:c}=e;if(!a||!o)return{success:!1,error:"Authentication required. You need to verify Ordinal ownership to moderate posts."};if(o.address!==c)return{success:!1,error:"Not authorized. Only the cell admin can moderate posts."};try{const l={type:os.MODERATE,id:kd(),cellId:r,targetType:"post",targetId:s,reason:i,action:Ou.MODERATE,timestamp:Date.now(),author:o.address},u=await this.delegationManager.signMessage(l);return u?(await ct.updateCache(u),ct.markPending(u.id),ct.setSyncing(!0),n(),_n.sendMessage(u).catch(d=>console.error("Background send failed:",d)).finally(()=>ct.setSyncing(!1)),{success:!0,data:!0}):{success:!1,error:(await this.delegationManager.getStatus(o.address,o.walletType)).isValid?"Key delegation required. Please delegate a signing key from your profile menu.":"Key delegation expired. Please re-delegate your key through the profile menu."}}catch(l){return console.error("Error moderating post:",l),{success:!1,error:"Failed to moderate post. Please try again."}}}async moderateComment(e,n){const{cellId:r,commentId:s,reason:i,currentUser:o,isAuthenticated:a,cellOwner:c}=e;if(!a||!o)return{success:!1,error:"Authentication required. You need to verify Ordinal ownership to moderate comments."};if(o.address!==c)return{success:!1,error:"Not authorized. Only the cell admin can moderate comments."};try{const l={type:os.MODERATE,id:kd(),cellId:r,targetType:"comment",targetId:s,reason:i,action:Ou.MODERATE,timestamp:Date.now(),author:o.address},u=await this.delegationManager.signMessage(l);return u?(await ct.updateCache(u),ct.markPending(u.id),ct.setSyncing(!0),n(),_n.sendMessage(u).catch(d=>console.error("Background send failed:",d)).finally(()=>ct.setSyncing(!1)),{success:!0,data:!0}):{success:!1,error:(await this.delegationManager.getStatus(o.address,o.walletType)).isValid?"Key delegation required. Please delegate a signing key from your profile menu.":"Key delegation expired. Please re-delegate your key through the profile menu."}}catch(l){return console.error("Error moderating comment:",l),{success:!1,error:"Failed to moderate comment. Please try again."}}}async moderateUser(e,n){const{cellId:r,userAddress:s,reason:i,currentUser:o,isAuthenticated:a,cellOwner:c}=e;if(!a||!o)return{success:!1,error:"Authentication required. You need to verify Ordinal ownership to moderate users."};if(o.address!==c)return{success:!1,error:"Not authorized. Only the cell admin can moderate users."};try{const l={type:os.MODERATE,id:kd(),cellId:r,targetType:"user",targetId:s,reason:i,action:Ou.MODERATE,author:o.address,timestamp:Date.now()},u=await this.delegationManager.signMessage(l);return u?(await ct.updateCache(u),ct.markPending(u.id),ct.setSyncing(!0),n(),_n.sendMessage(u).catch(d=>console.error("Background send failed:",d)).finally(()=>ct.setSyncing(!1)),{success:!0,data:!0}):{success:!1,error:(await this.delegationManager.getStatus(o.address,o.walletType)).isValid?"Key delegation required. Please delegate a signing key from your profile menu.":"Key delegation expired. Please re-delegate your key through the profile menu."}}catch(l){return console.error("Error moderating user:",l),{success:!1,error:"Failed to moderate user. Please try again."}}}async unmoderatePost(e,n){const{cellId:r,postId:s,reason:i,currentUser:o,isAuthenticated:a,cellOwner:c}=e;if(!a||!o)return{success:!1,error:"Authentication required. You need to verify Ordinal ownership to unmoderate posts."};if(o.address!==c)return{success:!1,error:"Not authorized. Only the cell admin can unmoderate posts."};try{const l={type:os.MODERATE,id:kd(),cellId:r,targetType:"post",targetId:s,reason:i,action:Ou.UNMODERATE,timestamp:Date.now(),author:o.address},u=await this.delegationManager.signMessage(l);return u?(await ct.updateCache(u),ct.markPending(u.id),ct.setSyncing(!0),n(),_n.sendMessage(u).catch(d=>console.error("Background send failed:",d)).finally(()=>ct.setSyncing(!1)),{success:!0,data:!0}):{success:!1,error:(await this.delegationManager.getStatus(o.address,o.walletType)).isValid?"Key delegation required. Please delegate a signing key from your profile menu.":"Key delegation expired. Please re-delegate your key through the profile menu."}}catch(l){return console.error("Error unmoderating post:",l),{success:!1,error:"Failed to unmoderate post. Please try again."}}}async unmoderateComment(e,n){const{cellId:r,commentId:s,reason:i,currentUser:o,isAuthenticated:a,cellOwner:c}=e;if(!a||!o)return{success:!1,error:"Authentication required. You need to verify Ordinal ownership to unmoderate comments."};if(o.address!==c)return{success:!1,error:"Not authorized. Only the cell admin can unmoderate comments."};try{const l={type:os.MODERATE,id:kd(),cellId:r,targetType:"comment",targetId:s,reason:i,action:Ou.UNMODERATE,timestamp:Date.now(),author:o.address},u=await this.delegationManager.signMessage(l);return u?(await ct.updateCache(u),ct.markPending(u.id),ct.setSyncing(!0),n(),_n.sendMessage(u).catch(d=>console.error("Background send failed:",d)).finally(()=>ct.setSyncing(!1)),{success:!0,data:!0}):{success:!1,error:(await this.delegationManager.getStatus(o.address,o.walletType)).isValid?"Key delegation required. Please delegate a signing key from your profile menu.":"Key delegation expired. Please re-delegate your key through the profile menu."}}catch(l){return console.error("Error unmoderating comment:",l),{success:!1,error:"Failed to unmoderate comment. Please try again."}}}async unmoderateUser(e,n){const{cellId:r,userAddress:s,reason:i,currentUser:o,isAuthenticated:a,cellOwner:c}=e;if(!a||!o)return{success:!1,error:"Authentication required. You need to verify Ordinal ownership to unmoderate users."};if(o.address!==c)return{success:!1,error:"Not authorized. Only the cell admin can unmoderate users."};try{const l={type:os.MODERATE,id:kd(),cellId:r,targetType:"user",targetId:s,reason:i,action:Ou.UNMODERATE,author:o.address,timestamp:Date.now()},u=await this.delegationManager.signMessage(l);return u?(await ct.updateCache(u),ct.markPending(u.id),ct.setSyncing(!0),n(),_n.sendMessage(u).catch(d=>console.error("Background send failed:",d)).finally(()=>ct.setSyncing(!1)),{success:!0,data:!0}):{success:!1,error:(await this.delegationManager.getStatus(o.address,o.walletType)).isValid?"Key delegation required. Please delegate a signing key from your profile menu.":"Key delegation expired. Please re-delegate your key through the profile menu."}}catch(l){return console.error("Error unmoderating user:",l),{success:!1,error:"Failed to unmoderate user. Please try again."}}}}const nse=async(t,e)=>{try{t({title:"Loading data",description:"Connecting to the Waku network..."}),_n.isReady?t({title:"Connected",description:"Successfully connected to Waku network."}):t({title:"Connecting...",description:"Establishing network connection. You can view cached data while we connect.",variant:"default"})}catch(n){console.error("Error loading forum data:",n),e("Failed to load forum data. Please try again later."),t({title:"Load error",description:"Failed to load forum data. Please try refreshing.",variant:"destructive"})}},fAt=(t,e)=>(t(_n.isReady),{unsubscribe:_n.onHealthChange((r,s)=>{t(r),s===Vs.SufficientlyHealthy?e({title:"Network connected",description:"Connected to the Waku network with excellent connectivity"}):s===Vs.MinimallyHealthy?e({title:"Network connected",description:"Connected to Waku network. Some features may be limited.",variant:"default"}):e({title:"Network disconnected",description:"Lost connection to the Waku network",variant:"destructive"})})});class hAt{messageService;userIdentityCache={};refreshListeners=new Set;constructor(e){this.messageService=e}async getUserIdentity(e){if(this.userIdentityCache[e]){const i=this.userIdentityCache[e];if(!i.ensName&&e.startsWith("0x")){const o=await this.resolveENSName(e);o&&(i.ensName=o)}return{address:e,ensName:i.ensName,ordinalDetails:i.ordinalDetails,callSign:i.callSign,displayPreference:i.displayPreference,lastUpdated:i.lastUpdated,verificationStatus:this.mapVerificationStatus(i.verificationStatus)}}const n=ct.cache.userIdentities[e];if(n){this.userIdentityCache[e]={ensName:n.ensName,ordinalDetails:n.ordinalDetails,callSign:n.callSign,displayPreference:n.displayPreference,lastUpdated:n.lastUpdated,verificationStatus:n.verificationStatus};const i={address:e,ensName:n.ensName,ordinalDetails:n.ordinalDetails,callSign:n.callSign,displayPreference:n.displayPreference,lastUpdated:n.lastUpdated,verificationStatus:this.mapVerificationStatus(n.verificationStatus)};if(!i.ensName&&e.startsWith("0x")){const o=await this.resolveENSName(e);o&&(i.ensName=o,this.userIdentityCache[e].ensName=o)}return i}const r=_n.messageCache.userIdentities[e];if(r){this.userIdentityCache[e]={ensName:r.ensName,ordinalDetails:r.ordinalDetails,callSign:r.callSign,displayPreference:r.displayPreference,lastUpdated:r.lastUpdated,verificationStatus:r.verificationStatus};const i={address:e,ensName:r.ensName,ordinalDetails:r.ordinalDetails,callSign:r.callSign,displayPreference:r.displayPreference,lastUpdated:r.lastUpdated,verificationStatus:this.mapVerificationStatus(r.verificationStatus)};if(!i.ensName&&e.startsWith("0x")){const o=await this.resolveENSName(e);o&&(i.ensName=o,this.userIdentityCache[e].ensName=o)}return i}const s=await this.resolveUserIdentity(e);return s&&(this.userIdentityCache[e]={ensName:s.ensName,ordinalDetails:s.ordinalDetails,callSign:s.callSign,displayPreference:s.displayPreference,lastUpdated:s.lastUpdated,verificationStatus:s.verificationStatus}),s}getAllUserIdentities(){return Object.entries(this.userIdentityCache).map(([e,n])=>({address:e,ensName:n.ensName,ordinalDetails:n.ordinalDetails,callSign:n.callSign,displayPreference:n.displayPreference,lastUpdated:n.lastUpdated,verificationStatus:this.mapVerificationStatus(n.verificationStatus)}))}async updateUserProfile(e,n,r){try{const s=Date.now(),i={id:crypto.randomUUID(),type:os.USER_PROFILE_UPDATE,timestamp:s,author:e,displayPreference:r};n&&n.trim()&&(i.callSign=n.trim());const o=await this.messageService.signAndBroadcastMessage(i);if(o&&(this.updateUserIdentityFromMessage(o),this.userIdentityCache[e])){const a={...this.userIdentityCache[e],callSign:n&&n.trim()?n.trim():this.userIdentityCache[e].callSign,displayPreference:r,lastUpdated:s};ct.cache.userIdentities[e]=a;const c={id:i.id,type:os.USER_PROFILE_UPDATE,timestamp:s,author:e,displayPreference:r,signature:o.signature,browserPubKey:o.browserPubKey,delegationProof:o.delegationProof};n&&n.trim()&&(c.callSign=n.trim()),await ct.applyMessage(c),this.notifyRefreshListeners(e)}return!!o}catch(s){return console.error("Failed to update user profile:",s),!1}}async resolveUserIdentity(e){try{const[n,r]=await Promise.all([this.resolveENSName(e),this.resolveOrdinalDetails(e)]),s=_l.WALLET_ADDRESS;let i=Ct.WALLET_UNCONNECTED;return(n||r)&&(i=Ct.ENS_ORDINAL_VERIFIED),{address:e,ensName:n||void 0,ordinalDetails:r||void 0,callSign:void 0,displayPreference:s,lastUpdated:Date.now(),verificationStatus:i}}catch(n){return console.error("Failed to resolve user identity:",n),null}}async resolveENSName(e){if(!e.startsWith("0x"))return null;try{const{getEnsName:n}=await et(async()=>{const{getEnsName:i}=await Promise.resolve().then(()=>$7e);return{getEnsName:i}},void 0),{config:r}=await et(async()=>{const{config:i}=await Promise.resolve().then(()=>Vlt);return{config:i}},void 0);return await n(r,{address:e})||null}catch(n){return console.error("Failed to resolve ENS name:",n),null}}async resolveOrdinalDetails(e){try{return console.log("resolveOrdinalDetails",e),null}catch(n){return console.error("Failed to resolve Ordinal details:",n),null}}updateUserIdentityFromMessage(e){const{author:n,callSign:r,displayPreference:s,timestamp:i}=e;this.userIdentityCache[n]||(this.userIdentityCache[n]={ensName:void 0,ordinalDetails:void 0,callSign:void 0,displayPreference:s,lastUpdated:i,verificationStatus:Ct.WALLET_UNCONNECTED}),i>this.userIdentityCache[n].lastUpdated&&(this.userIdentityCache[n]={...this.userIdentityCache[n],callSign:r,displayPreference:s,lastUpdated:i},this.notifyRefreshListeners(n))}mapVerificationStatus(e){switch(e){case"verified-basic":return Ct.WALLET_CONNECTED;case"verified-owner":return Ct.ENS_ORDINAL_VERIFIED;case"verifying":return Ct.WALLET_CONNECTED;default:return Ct.WALLET_UNCONNECTED}}async refreshUserIdentity(e){delete this.userIdentityCache[e],await this.getUserIdentity(e)}clearUserIdentityCache(){this.userIdentityCache={}}addRefreshListener(e){return this.refreshListeners.add(e),()=>this.refreshListeners.delete(e)}notifyRefreshListeners(e){this.refreshListeners.forEach(n=>n(e))}getDisplayName(e){const n=this.userIdentityCache[e];return n?n.displayPreference===_l.CALL_SIGN&&n.callSign?n.callSign:n.ensName?n.ensName:`${e.slice(0,6)}...${e.slice(-4)}`:`${e.slice(0,6)}...${e.slice(-4)}`}}class pAt{delegationManager;constructor(e){this.delegationManager=e}async sendMessage(e){try{const n=await this.delegationManager.signMessage(e);return n?(await _n.sendMessage(n),{success:!0,message:n}):{success:!1,error:!(await this.delegationManager.getStatus()).isValid?"Key delegation expired. Please re-delegate your key through the profile menu.":"Key delegation required. Please delegate a signing key from your profile menu to post without wallet approval for each action."}}catch(n){console.error("Error signing and sending message:",n);let r="Failed to sign and send message. Please try again.";return n instanceof Error&&(n.message.includes("timeout")||n.message.includes("network")?r="Network issue detected. Please check your connection and try again.":n.message.includes("rejected")||n.message.includes("denied")?r="Wallet signature request was rejected. Please approve signing to continue.":r=n.message),{success:!1,error:r}}}async signAndBroadcastMessage(e){try{const n=await this.delegationManager.signMessage(e);return n?(await _n.sendMessage(n),n):(console.error("Failed to sign message"),null)}catch(n){return console.error("Error signing and broadcasting message:",n),null}}async verifyMessage(e){return await this.delegationManager.verify(e)}}const Qc=()=>{const t=I.useContext(WW);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t},Sbe=I.createContext(void 0);function gAt({children:t}){const[e,n]=I.useState([]),[r,s]=I.useState([]),[i,o]=I.useState([]),[a,c]=I.useState(!0),[{lastSync:l,isSyncing:u},d]=I.useState({lastSync:null,isSyncing:!1}),[f,p]=I.useState(!1),[m,y]=I.useState(!1),[b,v]=I.useState(!1),[x,E]=I.useState(!1),[A,_]=I.useState(!1),[k,B]=I.useState(!1),[W,S]=I.useState(null),[$,R]=I.useState({}),{toast:M}=xf(),{currentUser:j,isAuthenticated:z}=Qc(),N=I.useMemo(()=>new vh,[]),T=I.useMemo(()=>new pAt(N),[N]),U=I.useMemo(()=>new hAt(T),[T]),L=I.useMemo(()=>new dAt(N),[N]),P=I.useCallback(async()=>{const be=new bo,pe=[],J=new Set;Object.values(_n.messageCache.posts).forEach(Je=>{J.add(Je.author)}),Object.values(_n.messageCache.comments).forEach(Je=>{J.add(Je.author)}),Object.values(_n.messageCache.votes).forEach(Je=>{J.add(Je.author)});const ie=Array.from(J).map(async Je=>{if(j&&j.address===Je)return{address:Je,walletType:j.walletType,verificationStatus:j.verificationStatus,displayPreference:j.displayPreference,ensDetails:j.ensDetails,ordinalDetails:j.ordinalDetails,lastChecked:j.lastChecked};{const ft=await U.getUserIdentity(Je);return ft?{address:Je,walletType:Je.startsWith("0x")?"ethereum":"bitcoin",verificationStatus:ft.verificationStatus,displayPreference:ft.displayPreference,ensDetails:ft.ensName?{ensName:ft.ensName}:void 0,ordinalDetails:ft.ordinalDetails,lastChecked:ft.lastUpdated}:{address:Je,walletType:Je.startsWith("0x")?"ethereum":"bitcoin",verificationStatus:Ct.WALLET_UNCONNECTED,displayPreference:_l.WALLET_ADDRESS}}}),ae=await Promise.all(ie);pe.push(...ae);const Pe=be.buildUserVerificationStatus(pe),{cells:$e,posts:Re,comments:ut}=await uAt(void 0,Pe);n($e),s(Re),o(ut),R(Pe),d(ct.getSyncState())},[j,U]),H=async()=>{_(!0);try{await P();const{lastSync:be,isSyncing:pe}=ct.getSyncState();M({title:"Data Refreshed",description:be?`Your view has been updated. Last sync: ${new Date(be).toLocaleTimeString()}${pe?" (syncing...)":""}`:"Your view has been updated."})}catch(be){console.error("Error refreshing data:",be),M({title:"Refresh Failed",description:"Could not update the view. Please try again.",variant:"destructive"})}finally{_(!1)}};I.useEffect(()=>{const{unsubscribe:be}=fAt(B,M);return be},[M]);const Y=I.useRef(!1);I.useEffect(()=>Y.current?void 0:(Y.current=!0,(async()=>{c(!0);try{await ct.open();const pe=ct.cache;Object.assign(_n.messageCache.cells,pe.cells),Object.assign(_n.messageCache.posts,pe.posts),Object.assign(_n.messageCache.comments,pe.comments),Object.assign(_n.messageCache.votes,pe.votes),Object.assign(_n.messageCache.moderations,pe.moderations),Object.assign(_n.messageCache.userIdentities,pe.userIdentities);const J=Object.keys(pe.cells).length>0||Object.keys(pe.posts).length>0||Object.keys(pe.comments).length>0||Object.keys(pe.votes).length>0;if(await P(),await nse(M,S),J)c(!1);else{const ie=_n.onHealthChange(ae=>{ae&&(c(!1),ie())})}}catch(pe){console.warn("LocalDatabase warm-start failed, continuing cold:",pe),await nse(M,S);const J=_n.onHealthChange(ie=>{ie&&(c(!1),J())})}})(),()=>{}),[M,P]),I.useEffect(()=>_n.onMessageReceived(()=>{ct.setSyncing(!0),P().finally(()=>ct.setSyncing(!1))}),[P]),I.useEffect(()=>{if(!k)return;const be=setInterval(()=>{_n.isReady&&(ct.setSyncing(!0),P().finally(()=>ct.setSyncing(!1)))},15e3);return()=>clearInterval(be)},[k,P]);const re=be=>e.find(pe=>pe.id===be),de=be=>r.filter(pe=>pe.cellId===be).sort((pe,J)=>J.timestamp-pe.timestamp),fe=be=>i.filter(pe=>pe.postId===be).sort((pe,J)=>pe.timestamp-J.timestamp),ve=async(be,pe,J)=>{y(!0),M({title:"Creating post",description:"Sending your post to the network..."});const ie=await L.createPost({cellId:be,title:pe,content:J,currentUser:j,isAuthenticated:z},P);return y(!1),ie.success?(M({title:"Post Created",description:"Your post has been published successfully."}),ie.data||null):(M({title:"Post Failed",description:ie.error||"Failed to create post. Please try again.",variant:"destructive"}),null)},Ee=async(be,pe)=>{v(!0),M({title:"Posting comment",description:"Sending your comment to the network..."});const J=await L.createComment({postId:be,content:pe,currentUser:j,isAuthenticated:z},P);return v(!1),J.success?(M({title:"Comment Added",description:"Your comment has been published."}),J.data||null):(M({title:"Comment Failed",description:J.error||"Failed to add comment. Please try again.",variant:"destructive"}),null)},oe=async(be,pe)=>{E(!0);const J=pe?"upvote":"downvote";M({title:`Sending ${J}`,description:"Recording your vote on the network..."});const ie=await L.vote({targetId:be,isUpvote:pe,currentUser:j,isAuthenticated:z},P);return E(!1),ie.success?(M({title:"Vote Recorded",description:`Your ${J} has been registered.`}),ie.data||!1):(M({title:"Vote Failed",description:ie.error||"Failed to register your vote. Please try again.",variant:"destructive"}),!1)},Oe=async(be,pe)=>{E(!0);const J=pe?"upvote":"downvote";M({title:`Sending ${J}`,description:"Recording your vote on the network..."});const ie=await L.vote({targetId:be,isUpvote:pe,currentUser:j,isAuthenticated:z},P);return E(!1),ie.success?(M({title:"Vote Recorded",description:`Your ${J} has been registered.`}),ie.data||!1):(M({title:"Vote Failed",description:ie.error||"Failed to register your vote. Please try again.",variant:"destructive"}),!1)},je=async(be,pe,J)=>{p(!0),M({title:"Creating cell",description:"Sending your cell to the network..."});const ie=await L.createCell({name:be,description:pe,icon:J,currentUser:j,isAuthenticated:z},P);return p(!1),ie.success?(M({title:"Cell Created",description:"Your cell has been published."}),ie.data||null):(M({title:"Cell Failed",description:ie.error||"Failed to create cell. Please try again.",variant:"destructive"}),null)},V=async(be,pe,J,ie)=>{M({title:"Moderating Post",description:"Sending moderation message to the network..."});const ae=await L.moderatePost({cellId:be,postId:pe,reason:J,currentUser:j,isAuthenticated:z,cellOwner:ie},P);return ae.success?(M({title:"Post Moderated",description:"The post has been marked as moderated."}),ae.data||!1):(M({title:"Moderation Failed",description:ae.error||"Failed to moderate post. Please try again.",variant:"destructive"}),!1)},we=async(be,pe,J,ie)=>{M({title:"Unmoderating Post",description:"Sending unmoderation message to the network..."});const ae=await L.unmoderatePost({cellId:be,postId:pe,reason:J,currentUser:j,isAuthenticated:z,cellOwner:ie},P);return ae.success?(M({title:"Post Unmoderated",description:"The post is now visible again."}),ae.data||!1):(M({title:"Unmoderation Failed",description:ae.error||"Failed to unmoderate post. Please try again.",variant:"destructive"}),!1)},Ae=async(be,pe,J,ie)=>{M({title:"Moderating Comment",description:"Sending moderation message to the network..."});const ae=await L.moderateComment({cellId:be,commentId:pe,reason:J,currentUser:j,isAuthenticated:z,cellOwner:ie},P);return ae.success?(M({title:"Comment Moderated",description:"The comment has been marked as moderated."}),ae.data||!1):(M({title:"Moderation Failed",description:ae.error||"Failed to moderate comment. Please try again.",variant:"destructive"}),!1)},Ie=async(be,pe,J,ie)=>{M({title:"Unmoderating Comment",description:"Sending unmoderation message to the network..."});const ae=await L.unmoderateComment({cellId:be,commentId:pe,reason:J,currentUser:j,isAuthenticated:z,cellOwner:ie},P);return ae.success?(M({title:"Comment Unmoderated",description:"The comment is now visible again."}),ae.data||!1):(M({title:"Unmoderation Failed",description:ae.error||"Failed to unmoderate comment. Please try again.",variant:"destructive"}),!1)},ge=async(be,pe,J,ie)=>{const ae=await L.moderateUser({cellId:be,userAddress:pe,reason:J,currentUser:j,isAuthenticated:z,cellOwner:ie},P);return ae.success?(M({title:"User Moderated",description:`User ${pe} has been moderated in this cell.`}),ae.data||!1):(M({title:"Moderation Failed",description:ae.error||"Failed to moderate user. Please try again.",variant:"destructive"}),!1)},Me=async(be,pe,J,ie)=>{const ae=await L.unmoderateUser({cellId:be,userAddress:pe,reason:J,currentUser:j,isAuthenticated:z,cellOwner:ie},P);return ae.success?(M({title:"User Unmoderated",description:`User ${pe} has been unmoderated in this cell.`}),ae.data||!1):(M({title:"Unmoderation Failed",description:ae.error||"Failed to unmoderate user. Please try again.",variant:"destructive"}),!1)};return w.jsx(Sbe.Provider,{value:{cells:e,posts:r,comments:i,userVerificationStatus:$,userIdentityService:U,isInitialLoading:a,lastSync:l,isSyncing:u,isPostingCell:f,isPostingPost:m,isPostingComment:b,isVoting:x,isRefreshing:A,isNetworkConnected:k,error:W,getCellById:re,getPostsByCell:de,getCommentsByPost:fe,createPost:ve,createComment:Ee,votePost:oe,voteComment:Oe,createCell:je,refreshData:H,moderatePost:V,unmoderatePost:we,moderateComment:Ae,unmoderateComment:Ie,moderateUser:ge,unmoderateUser:Me},children:t})}const Abe=I.createContext(void 0);function mAt({children:t}){const[e,n]=I.useState(!1),[r,s]=I.useState(!1);I.useEffect(()=>{(async()=>{try{const a=await ct.loadUIState("show-moderated");n(a===!0)}catch(a){console.warn("Failed to load moderation preference from IndexedDB:",a),n(!1)}finally{s(!0)}})()},[]),I.useEffect(()=>{if(!r)return;(async()=>{try{await ct.storeUIState("show-moderated",e)}catch(a){console.warn("Failed to save moderation preference to IndexedDB:",a)}})()},[e,r]);const i=()=>{n(o=>!o)};return w.jsx(Abe.Provider,{value:{showModerated:e,setShowModerated:n,toggleShowModerated:i},children:t})}function A8(){const t=I.useContext(Abe);if(t===void 0)throw new Error("useModeration must be used within a ModerationProvider");return t}const xw=()=>{const t=I.useContext(Sbe);if(t===void 0)throw new Error("useForum must be used within a ForumProvider");return t};function wd(){const{cells:t,posts:e,comments:n,userVerificationStatus:r,isInitialLoading:s,isRefreshing:i,isNetworkConnected:o,error:a}=xw(),{currentUser:c}=Qc(),{showModerated:l}=A8(),u=I.useMemo(()=>t.map(S=>{const $=e.filter(j=>j.cellId===S.id),R=$.filter(j=>Date.now()-j.timestamp<7*24*60*60*1e3),M=new Set($.map(j=>j.author));return{...S,postCount:$.length,activeUsers:M.size,recentActivity:R.length}}),[t,e]),d=I.useMemo(()=>c?c.verificationStatus===Ct.ENS_ORDINAL_VERIFIED||c.verificationStatus===Ct.WALLET_CONNECTED||!!c.ensDetails||!!c.ordinalDetails:!1,[c]),f=I.useMemo(()=>{const S={};return c&&t.forEach($=>{S[$.id]=c.address===$.signature}),S},[c,t]),p=I.useMemo(()=>e.map(S=>{const $=c?S.upvotes.some(z=>z.author===c.address):!1,R=c?S.downvotes.some(z=>z.author===c.address):!1,M=S.upvotes.length-S.downvotes.length,j=f[S.cellId]||!1;return{...S,userUpvoted:$,userDownvoted:R,voteScore:M,canVote:d,canModerate:j}}),[e,c,d,f]),m=I.useMemo(()=>n.map(S=>{const $=c?S.upvotes.some(N=>N.author===c.address):!1,R=c?S.downvotes.some(N=>N.author===c.address):!1,M=S.upvotes.length-S.downvotes.length,j=e.find(N=>N.id===S.postId),z=j&&f[j.cellId]||!1;return{...S,userUpvoted:$,userDownvoted:R,voteScore:M,canVote:d,canModerate:z}}),[n,c,d,f,e]),y=I.useMemo(()=>{const S={};return p.forEach($=>{S[$.cellId]||(S[$.cellId]=[]);const R=S[$.cellId];R&&R.push($)}),Object.keys(S).forEach($=>{const R=S[$];R&&R.sort((M,j)=>M.relevanceScore!==void 0&&j.relevanceScore!==void 0?j.relevanceScore-M.relevanceScore:j.timestamp-M.timestamp)}),S},[p]),b=I.useMemo(()=>{const S={};return m.forEach($=>{S[$.postId]||(S[$.postId]=[]);const R=S[$.postId];R&&R.push($)}),Object.keys(S).forEach($=>{const R=S[$];R&&R.sort((M,j)=>M.timestamp-j.timestamp)}),S},[m]),v=I.useMemo(()=>{const S=new Set;return c&&p.forEach($=>{($.userUpvoted||$.userDownvoted)&&S.add($.id)}),S},[p,c]),x=I.useMemo(()=>{const S=new Set;return c&&m.forEach($=>{($.userUpvoted||$.userDownvoted)&&S.add($.id)}),S},[m,c]),E=I.useMemo(()=>{const S=new Set;return c&&e.forEach($=>{$.author===c.address&&S.add($.id)}),S},[e,c]),A=I.useMemo(()=>{const S=new Set;return c&&n.forEach($=>{$.author===c.address&&S.add($.id)}),S},[n,c]),_=I.useMemo(()=>l?p:p.filter(S=>!S.moderated),[p,l]),k=I.useMemo(()=>{if(l)return m;const S=new Set(p.filter($=>$.moderated).map($=>$.id));return m.filter($=>!$.moderated&&!S.has($.postId))},[m,p,l]),B=I.useMemo(()=>t.map(S=>{const $=_.filter(j=>j.cellId===S.id),R=$.filter(j=>Date.now()-j.timestamp<7*24*60*60*1e3),M=new Set($.map(j=>j.author));return{...S,postCount:$.length,activeUsers:M.size,recentActivity:R.length}}),[t,_]),W=I.useMemo(()=>{const S={};return k.forEach($=>{S[$.postId]||(S[$.postId]=[]),S[$.postId].push($)}),S},[k]);return{cells:t,posts:e,comments:n,userVerificationStatus:r,isInitialLoading:s,isRefreshing:i,isNetworkConnected:o,error:a,cellsWithStats:u,postsWithVoteStatus:p,commentsWithVoteStatus:m,filteredPosts:_,filteredComments:k,filteredCellsWithStats:B,filteredCommentsByPost:W,postsByCell:y,commentsByPost:b,userVotedPosts:v,userVotedComments:x,userCreatedPosts:E,userCreatedComments:A}}function _i(){const{currentUser:t,isAuthenticated:e,isAuthenticating:n,verificationStatus:r}=Qc(),{userIdentityService:s}=xw();return{currentUser:t,isAuthenticated:e,isAuthenticating:n,verificationStatus:r,getDisplayName:()=>{if(!t)return"Anonymous";if(s)return s.getDisplayName(t.address);const a=t.address;return`${a.slice(0,6)}...${a.slice(-4)}`},getVerificationBadge:()=>{switch(r){case Ct.ENS_ORDINAL_VERIFIED:return"🔑";case Ct.WALLET_CONNECTED:return"✅";default:return null}}}}function H3(t){const{userIdentityService:e,userVerificationStatus:n}=xw(),[r,s]=I.useState({displayName:`${t.slice(0,6)}...${t.slice(-4)}`,callSign:null,ensName:null,ordinalDetails:null,verificationLevel:Ct.WALLET_UNCONNECTED,displayPreference:null,isLoading:!0,error:null}),[i,o]=I.useState(0),a=I.useMemo(()=>n[t]||{isVerified:!1,ensName:null,verificationStatus:Ct.WALLET_UNCONNECTED},[n,t]);return I.useEffect(()=>!e||!t?void 0:e.addRefreshListener(l=>{l===t&&o(u=>u+1)}),[e,t]),I.useEffect(()=>{(async()=>{if(!t){s(l=>({...l,isLoading:!1,error:"No address provided"}));return}if(!e){console.log("useEnhancedUserDisplay: No service available, using fallback",{address:t}),s({displayName:`${t.slice(0,6)}...${t.slice(-4)}`,callSign:null,ensName:a.ensName||null,ordinalDetails:null,verificationLevel:a.verificationStatus||Ct.WALLET_UNCONNECTED,displayPreference:null,isLoading:!1,error:null});return}try{const l=await e.getUserIdentity(t);if(l){const u=e.getDisplayName(t);s({displayName:u,callSign:l.callSign||null,ensName:l.ensName||null,ordinalDetails:l.ordinalDetails?l.ordinalDetails.ordinalDetails:null,verificationLevel:l.verificationStatus,displayPreference:l.displayPreference||null,isLoading:!1,error:null})}else s({displayName:e.getDisplayName(t),callSign:null,ensName:a.ensName||null,ordinalDetails:null,verificationLevel:a.verificationStatus||Ct.WALLET_UNCONNECTED,displayPreference:null,isLoading:!1,error:null})}catch(l){console.error("useEnhancedUserDisplay: Failed to get user display info:",l),s({displayName:`${t.slice(0,6)}...${t.slice(-4)}`,callSign:null,ensName:null,ordinalDetails:null,verificationLevel:Ct.WALLET_UNCONNECTED,displayPreference:null,isLoading:!1,error:l instanceof Error?l.message:"Unknown error"})}})()},[t,e,a,i]),I.useEffect(()=>{!r.isLoading&&a&&s(c=>({...c,ensName:a.ensName||c.ensName,verificationLevel:a.verificationStatus||c.verificationLevel}))},[a.ensName,a.verificationStatus,r.isLoading,a]),r}var Dc=(t=>(t.POST="post",t.COMMENT="comment",t))(Dc||{});class bl{static async bookmarkPost(e,n,r){const s={id:`post:${e.id}`,type:Dc.POST,targetId:e.id,userId:n,createdAt:Date.now(),title:e.title,author:e.author,cellId:r||e.cellId};return await ct.addBookmark(s),s}static async bookmarkComment(e,n,r){const s=e.content.length>100?e.content.substring(0,100)+"...":e.content,i={id:`comment:${e.id}`,type:Dc.COMMENT,targetId:e.id,userId:n,createdAt:Date.now(),title:s,author:e.author,postId:r||e.postId};return await ct.addBookmark(i),i}static async removeBookmark(e,n){const r=`${e}:${n}`;await ct.removeBookmark(r)}static async togglePostBookmark(e,n,r){return ct.isBookmarked(n,"post",e.id)?(await this.removeBookmark(Dc.POST,e.id),!1):(await this.bookmarkPost(e,n,r),!0)}static async toggleCommentBookmark(e,n,r){return ct.isBookmarked(n,"comment",e.id)?(await this.removeBookmark(Dc.COMMENT,e.id),!1):(await this.bookmarkComment(e,n,r),!0)}static isPostBookmarked(e,n){return ct.isBookmarked(e,"post",n)}static isCommentBookmarked(e,n){return ct.isBookmarked(e,"comment",n)}static async getUserBookmarks(e){return ct.getUserBookmarks(e)}static async getUserBookmarksByType(e,n){return ct.getUserBookmarksByType(e,n)}static getBookmark(e){return ct.getBookmark(e)}static getAllBookmarks(){return ct.getAllBookmarks()}static async clearUserBookmarks(e){const n=await this.getUserBookmarks(e);await Promise.all(n.map(r=>ct.removeBookmark(r.id)))}}function yAt(){const{currentUser:t}=Qc(),[e,n]=I.useState([]),[r,s]=I.useState(!1),[i,o]=I.useState(null),a=I.useCallback(async()=>{if(t?.address){s(!0),o(null);try{const y=await bl.getUserBookmarks(t.address);n(y)}catch(y){o(y instanceof Error?y.message:"Failed to load bookmarks")}finally{s(!1)}}},[t?.address]);I.useEffect(()=>{t?.address?a():n([])},[t?.address,a]);const c=I.useCallback(async(y,b)=>{if(!t?.address)return!1;try{const v=await bl.togglePostBookmark(y,t.address,b);return await a(),v}catch(v){return o(v instanceof Error?v.message:"Failed to bookmark post"),!1}},[t?.address,a]),l=I.useCallback(async(y,b)=>{if(!t?.address)return!1;try{const v=await bl.toggleCommentBookmark(y,t.address,b);return await a(),v}catch(v){return o(v instanceof Error?v.message:"Failed to bookmark comment"),!1}},[t?.address,a]),u=I.useCallback(async y=>{try{const b=bl.getBookmark(y);b&&(await bl.removeBookmark(b.type,b.targetId),await a())}catch(b){o(b instanceof Error?b.message:"Failed to remove bookmark")}},[a]),d=I.useCallback(y=>t?.address?bl.isPostBookmarked(t.address,y):!1,[t?.address]),f=I.useCallback(y=>t?.address?bl.isCommentBookmarked(t.address,y):!1,[t?.address]),p=I.useCallback(y=>e.filter(b=>b.type===y),[e]),m=I.useCallback(async()=>{if(t?.address)try{await bl.clearUserBookmarks(t.address),n([])}catch(y){o(y instanceof Error?y.message:"Failed to clear bookmarks")}},[t?.address]);return{bookmarks:e,loading:r,error:i,bookmarkPost:c,bookmarkComment:l,removeBookmark:u,isPostBookmarked:d,isCommentBookmarked:f,getBookmarksByType:p,clearAllBookmarks:m,refreshBookmarks:a}}function Ibe(t,e){const{currentUser:n}=Qc(),[r,s]=I.useState(!1),[i,o]=I.useState(!1);I.useEffect(()=>{if(n?.address&&t?.id){const c=bl.isPostBookmarked(n.address,t.id);s(c)}else s(!1)},[n?.address,t?.id]);const a=I.useCallback(async()=>{if(!n?.address||!t)return!1;o(!0);try{const c=await bl.togglePostBookmark(t,n.address,e);return s(c),c}catch(c){return console.error("Failed to toggle post bookmark:",c),!1}finally{o(!1)}},[n?.address,t,e]);return{isBookmarked:r,loading:i,toggleBookmark:a}}function wAt(t,e){const{currentUser:n}=Qc(),[r,s]=I.useState(!1),[i,o]=I.useState(!1);I.useEffect(()=>{if(n?.address){const c=bl.isCommentBookmarked(n.address,t.id);s(c)}else s(!1)},[n?.address,t.id]);const a=I.useCallback(async()=>{if(!n?.address)return!1;o(!0);try{const c=await bl.toggleCommentBookmark(t,n.address,e);return s(c),c}catch(c){return console.error("Failed to toggle comment bookmark:",c),!1}finally{o(!1)}},[n?.address,t,e]);return{isBookmarked:r,loading:i,toggleBookmark:a}}function bAt(t){const{cellsWithStats:e,postsByCell:n,commentsByPost:r}=wd(),{currentUser:s}=_i();return I.useMemo(()=>{if(!t)return null;const i=e.find(d=>d.id===t);if(!i)return null;const a=(n[t]||[]).map(d=>({id:d.id,title:d.title,content:d.content,author:d.author,timestamp:d.timestamp,voteScore:d.voteScore,commentCount:(r[d.id]||[]).length})),c=s?s.address===i.signature:!1,l=c,u=s?s.verificationStatus===Ct.ENS_ORDINAL_VERIFIED||s.verificationStatus===Ct.WALLET_CONNECTED||!!s.ensDetails||!!s.ordinalDetails:!1;return{...i,posts:a,isUserAdmin:c,canModerate:l,canPost:u}},[t,e,n,r,s])}function vAt(t){const{postsWithVoteStatus:e,commentsByPost:n,cellsWithStats:r}=wd(),{currentUser:s}=_i();return I.useMemo(()=>{if(!t)return null;const i=e.find(u=>u.id===t);if(!i)return null;const o=r.find(u=>u.id===i.cellId)||null,a=n[t]||[],c=a.length,l=s?s.address===i.author:!1;return{...i,cell:o?{id:o.id,name:o.name,description:o.description}:null,comments:a,commentCount:c,isUserAuthor:l}},[t,e,n,r,s])}function xAt(t,e={}){const{postsByCell:n,isInitialLoading:r,cellsWithStats:s}=wd(),{currentUser:i}=_i(),{showModerated:o}=A8(),{includeModerated:a=o,sortBy:c="relevance",limit:l}=e;return I.useMemo(()=>{if(!t)return{posts:[],totalCount:0,hasMore:!1,isLoading:r};let u=n[t]||[];if(!a){const m=s.find(b=>b.id===t);i&&m&&i.address===m.signature||(u=u.filter(b=>!b.moderated))}const d=[...u].sort((m,y)=>{switch(c){case"relevance":return m.relevanceScore!==void 0&&y.relevanceScore!==void 0?y.relevanceScore-m.relevanceScore:y.timestamp-m.timestamp;case"votes":return y.voteScore-m.voteScore;case"timestamp":default:return y.timestamp-m.timestamp}}),f=l?d.slice(0,l):d,p=l?d.length>l:!1;return{posts:f,totalCount:d.length,hasMore:p,isLoading:r}},[t,n,r,i,s,a,c,l])}function EAt(t,e={}){const{commentsByPost:n,isInitialLoading:r,postsWithVoteStatus:s,cellsWithStats:i}=wd(),{currentUser:o}=_i(),{showModerated:a}=A8(),{includeModerated:c=a,sortBy:l="timestamp",limit:u}=e;return I.useMemo(()=>{if(!t)return{comments:[],totalCount:0,hasMore:!1,isLoading:r};let d=n[t]||[];if(!c){const y=s.find(x=>x.id===t),b=y?i.find(x=>x.id===y.cellId):null;o&&b&&o.address===b.signature||(d=d.filter(x=>!x.moderated))}const f=[...d].sort((y,b)=>{switch(l){case"votes":return b.voteScore-y.voteScore;case"timestamp":default:return y.timestamp-b.timestamp}}),p=u?f.slice(0,u):f,m=u?f.length>u:!1;return{comments:p,totalCount:f.length,hasMore:m,isLoading:r}},[t,n,r,o,s,i,c,l,u])}function I8(t){const{postsWithVoteStatus:e,commentsWithVoteStatus:n}=wd(),{currentUser:r}=_i(),s=r?.address;return I.useMemo(()=>{if(!s)return{hasVotedOnPost:()=>!1,hasVotedOnComment:()=>!1,getPostVoteType:()=>null,getCommentVoteType:()=>null,votedPosts:new Set,votedComments:new Set,upvotedPosts:new Set,downvotedPosts:new Set,upvotedComments:new Set,downvotedComments:new Set,totalVotes:0,upvoteRatio:0};const i=new Set,o=new Set,a=new Set,c=new Set,l=new Set,u=new Set;e.forEach(x=>{const E=x.upvotes.some(_=>_.author===s),A=x.downvotes.some(_=>_.author===s);E&&(i.add(x.id),a.add(x.id)),A&&(i.add(x.id),c.add(x.id))}),n.forEach(x=>{const E=x.upvotes.some(_=>_.author===s),A=x.downvotes.some(_=>_.author===s);E&&(o.add(x.id),l.add(x.id)),A&&(o.add(x.id),u.add(x.id))});const d=i.size+o.size,f=a.size+l.size,p=d>0?f/d:0;return{hasVotedOnPost:x=>i.has(x),hasVotedOnComment:x=>o.has(x),getPostVoteType:x=>a.has(x)?"upvote":c.has(x)?"downvote":null,getCommentVoteType:x=>l.has(x)?"upvote":u.has(x)?"downvote":null,votedPosts:i,votedComments:o,upvotedPosts:a,downvotedPosts:c,upvotedComments:l,downvotedComments:u,totalVotes:d,upvoteRatio:p}},[e,n,s])}function Cp(){const{currentUser:t,verificationStatus:e}=_i(),{cellsWithStats:n}=wd(),r=I.useMemo(()=>{const o=e===Ct.WALLET_CONNECTED,a=e===Ct.ENS_ORDINAL_VERIFIED;return{canPost:o||a,canComment:o||a,canVote:o||a,canCreateCell:a,canModerate:c=>{if(!t||!c)return!1;const l=n.find(u=>u.id===c);return l?l.author===t.address:!1},canDelegate:o||a,canUpdateProfile:!!t}},[t,e,n]),s=I.useMemo(()=>t?{voteReason:r.canVote?"You can vote":"Verify ENS or Logos ordinal to vote",postReason:r.canPost?"You can post":"Verify ENS or Logos ordinal to post",commentReason:r.canComment?"You can comment":"Verify ENS or Logos ordinal to comment",createCellReason:r.canCreateCell?"You can create cells":"Verify ENS or Logos ordinal to create cells",moderateReason:o=>o?r.canModerate(o)?"You can moderate this cell":"Only cell creators can moderate":"Cell ID required"}:{voteReason:"Connect your wallet to vote",postReason:"Connect your wallet to post",commentReason:"Connect your wallet to comment",createCellReason:"Connect your wallet to create cells",moderateReason:()=>"Connect your wallet to moderate"},[t,e,r]),i=I.useMemo(()=>(o,a)=>{let c=!1,l="";switch(o){case"canVote":c=r.canVote,l=s.voteReason;break;case"canPost":c=r.canPost,l=s.postReason;break;case"canComment":c=r.canComment,l=s.commentReason;break;case"canCreateCell":c=r.canCreateCell,l=s.createCellReason;break;case"canModerate":c=a?r.canModerate(a):!1,l=a?s.moderateReason(a):"Cell ID required";break;case"canDelegate":c=r.canDelegate,l=c?"You can delegate keys":"Connect your wallet to delegate keys";break;case"canUpdateProfile":c=r.canUpdateProfile,l=c?"You can update your profile":"Connect your wallet to update profile";break;default:c=!1,l="Unknown permission"}return{allowed:c,reason:l}},[r,s]);return{...r,...s,checkPermission:i}}function _p(){const{createCell:t,createPost:e,createComment:n,votePost:r,voteComment:s,moderatePost:i,unmoderatePost:o,moderateComment:a,unmoderateComment:c,moderateUser:l,unmoderateUser:u,refreshData:d,isPostingCell:f,isPostingPost:p,isPostingComment:m,isVoting:y,getCellById:b}=xw(),{currentUser:v}=_i(),x=Cp(),{toast:E}=xf(),A=I.useCallback(async(T,U,L)=>{if(!x.canCreateCell)return E({title:"Permission Denied",description:x.createCellReason,variant:"destructive"}),null;if(!T.trim()||!U.trim())return E({title:"Invalid Input",description:"Please provide both a name and description for the cell.",variant:"destructive"}),null;try{const P=await t(T,U,L);return P&&E({title:"Cell Created",description:`Successfully created "${T}" cell.`}),P}catch{return E({title:"Creation Failed",description:"Failed to create cell. Please try again.",variant:"destructive"}),null}},[x.canCreateCell,t,E]),_=I.useCallback(async(T,U,L)=>{if(!x.canPost)return E({title:"Permission Denied",description:"You need to verify Ordinal ownership to create posts.",variant:"destructive"}),null;if(!U.trim()||!L.trim())return E({title:"Invalid Input",description:"Please provide both a title and content for the post.",variant:"destructive"}),null;try{const P=await e(T,U,L);return P&&E({title:"Post Created",description:`Successfully created "${U}".`}),P}catch{return E({title:"Creation Failed",description:"Failed to create post. Please try again.",variant:"destructive"}),null}},[x.canPost,e,E]),k=I.useCallback(async(T,U)=>{if(!x.canComment)return E({title:"Permission Denied",description:x.commentReason,variant:"destructive"}),null;if(!U.trim())return E({title:"Invalid Input",description:"Please provide content for the comment.",variant:"destructive"}),null;try{const L=await n(T,U);return L&&E({title:"Comment Created",description:"Successfully posted your comment."}),L}catch{return E({title:"Creation Failed",description:"Failed to create comment. Please try again.",variant:"destructive"}),null}},[x.canComment,n,E]),B=I.useCallback(async(T,U)=>{if(!x.canVote)return E({title:"Permission Denied",description:x.voteReason,variant:"destructive"}),!1;try{const L=await r(T,U);return L&&E({title:"Vote Recorded",description:`Your ${U?"upvote":"downvote"} has been registered.`}),L}catch{return E({title:"Vote Failed",description:"Failed to record your vote. Please try again.",variant:"destructive"}),!1}},[x.canVote,r,E]),W=I.useCallback(async(T,U)=>{if(!x.canVote)return E({title:"Permission Denied",description:x.voteReason,variant:"destructive"}),!1;try{const L=await s(T,U);return L&&E({title:"Vote Recorded",description:`Your ${U?"upvote":"downvote"} has been registered.`}),L}catch{return E({title:"Vote Failed",description:"Failed to record your vote. Please try again.",variant:"destructive"}),!1}},[x.canVote,s,E]),S=I.useCallback(async(T,U,L)=>{const P=b(T);if(!(x.canModerate(T)&&P&&v?.address===P.author))return E({title:"Permission Denied",description:"You must be the cell owner to moderate content.",variant:"destructive"}),!1;try{const Y=await i(T,U,L,P.author);return Y&&E({title:"Post Moderated",description:"The post has been moderated successfully."}),Y}catch{return E({title:"Moderation Failed",description:"Failed to moderate post. Please try again.",variant:"destructive"}),!1}},[x,v,b,i,E]),$=I.useCallback(async(T,U,L)=>{const P=b(T);if(!(x.canModerate(T)&&P&&v?.address===P.author))return E({title:"Permission Denied",description:"You must be the cell owner to unmoderate content.",variant:"destructive"}),!1;try{const Y=await o(T,U,L,P.author);return Y&&E({title:"Post Unmoderated",description:"The post is now visible again."}),Y}catch{return E({title:"Unmoderation Failed",description:"Failed to unmoderate post. Please try again.",variant:"destructive"}),!1}},[x,v,b,o,E]),R=I.useCallback(async(T,U,L)=>{const P=b(T);if(!(x.canModerate(T)&&P&&v?.address===P.author))return E({title:"Permission Denied",description:"You must be the cell owner to moderate content.",variant:"destructive"}),!1;try{const Y=await a(T,U,L,P.author);return Y&&E({title:"Comment Moderated",description:"The comment has been moderated successfully."}),Y}catch{return E({title:"Moderation Failed",description:"Failed to moderate comment. Please try again.",variant:"destructive"}),!1}},[x,v,b,a,E]),M=I.useCallback(async(T,U,L)=>{const P=b(T);if(!(x.canModerate(T)&&P&&v?.address===P.author))return E({title:"Permission Denied",description:"You must be the cell owner to unmoderate content.",variant:"destructive"}),!1;try{const Y=await c(T,U,L,P.author);return Y&&E({title:"Comment Unmoderated",description:"The comment is now visible again."}),Y}catch{return E({title:"Unmoderation Failed",description:"Failed to unmoderate comment. Please try again.",variant:"destructive"}),!1}},[x,v,b,c,E]),j=I.useCallback(async(T,U,L)=>{const P=b(T);if(!(x.canModerate(T)&&P&&v?.address===P.author))return E({title:"Permission Denied",description:"You must be the cell owner to moderate users.",variant:"destructive"}),!1;if(U===v?.address)return E({title:"Invalid Action",description:"You cannot moderate yourself.",variant:"destructive"}),!1;try{const Y=await l(T,U,L,P.author);return Y&&E({title:"User Moderated",description:"The user has been moderated successfully."}),Y}catch{return E({title:"Moderation Failed",description:"Failed to moderate user. Please try again.",variant:"destructive"}),!1}},[x,v,b,l,E]),z=I.useCallback(async(T,U,L)=>{const P=b(T);if(!(x.canModerate(T)&&P&&v?.address===P.author))return E({title:"Permission Denied",description:"You must be the cell owner to unmoderate users.",variant:"destructive"}),!1;if(U===v?.address)return E({title:"Invalid Action",description:"You cannot unmoderate yourself.",variant:"destructive"}),!1;try{const Y=await u(T,U,L,P.author);return Y&&E({title:"User Unmoderated",description:"The user is now unmoderated in this cell."}),Y}catch{return E({title:"Unmoderation Failed",description:"Failed to unmoderate user. Please try again.",variant:"destructive"}),!1}},[x,v,b,u,E]),N=I.useCallback(async()=>{try{await d(),E({title:"Data Refreshed",description:"Forum data has been updated."})}catch{E({title:"Refresh Failed",description:"Failed to refresh data. Please try again.",variant:"destructive"})}},[d,E]);return{isCreatingCell:f,isCreatingPost:p,isCreatingComment:m,isVoting:y,isModerating:!1,createCell:A,createPost:_,createComment:k,votePost:B,voteComment:W,moderatePost:S,unmoderatePost:$,moderateComment:R,unmoderateComment:M,moderateUser:j,unmoderateUser:z,refreshData:N}}function CAt(){const{userIdentityService:t}=xw(),{currentUser:e}=_i(),n=Cp(),{toast:r}=xf(),[s,i]=I.useState(!1),[o,a]=I.useState(!1),[c,l]=I.useState(!1),u=I.useCallback(async m=>{if(!n.canUpdateProfile)return r({title:"Permission Denied",description:"You need to connect your wallet to update your profile.",variant:"destructive"}),!1;if(!t||!e)return r({title:"Service Unavailable",description:"User identity service is not available.",variant:"destructive"}),!1;if(!m.trim())return r({title:"Invalid Input",description:"Call sign cannot be empty.",variant:"destructive"}),!1;if(m.length<3||m.length>20)return r({title:"Invalid Call Sign",description:"Call sign must be between 3 and 20 characters.",variant:"destructive"}),!1;if(!/^[a-zA-Z0-9_-]+$/.test(m))return r({title:"Invalid Call Sign",description:"Call sign can only contain letters, numbers, underscores, and hyphens.",variant:"destructive"}),!1;a(!0);try{return await t.updateUserProfile(e.address,m,e.displayPreference)?(r({title:"Call Sign Updated",description:`Your call sign has been set to "${m}".`}),!0):(r({title:"Update Failed",description:"Failed to update call sign. Please try again.",variant:"destructive"}),!1)}catch(y){return console.error("Failed to update call sign:",y),r({title:"Update Failed",description:"An error occurred while updating your call sign.",variant:"destructive"}),!1}finally{a(!1)}},[n.canUpdateProfile,t,e,r]),d=I.useCallback(async m=>{if(!n.canUpdateProfile)return r({title:"Permission Denied",description:"You need to connect your wallet to update your profile.",variant:"destructive"}),!1;if(!t||!e)return r({title:"Service Unavailable",description:"User identity service is not available.",variant:"destructive"}),!1;l(!0);try{if(await t.updateUserProfile(e.address,e.callSign||"",m)){const b=m===_l.CALL_SIGN?"Call Sign":"Wallet Address";return r({title:"Display Preference Updated",description:`Your display preference has been set to "${b}".`}),!0}else return r({title:"Update Failed",description:"Failed to update display preference. Please try again.",variant:"destructive"}),!1}catch(y){return console.error("Failed to update display preference:",y),r({title:"Update Failed",description:"An error occurred while updating your display preference.",variant:"destructive"}),!1}finally{l(!1)}},[n.canUpdateProfile,t,e,r]),f=I.useCallback(async m=>{if(!n.canUpdateProfile)return r({title:"Permission Denied",description:"You need to connect your wallet to update your profile.",variant:"destructive"}),!1;if(!t||!e)return r({title:"Service Unavailable",description:"User identity service is not available.",variant:"destructive"}),!1;i(!0);try{let y=!0;if(m.callSign!==void 0||m.displayPreference!==void 0){const b=m.callSign,v=m.displayPreference??e.displayPreference;y=await t.updateUserProfile(e.address,b,v)}return y?(r({title:"Profile Updated",description:"Your profile has been updated successfully."}),!0):(r({title:"Update Failed",description:"Some profile updates failed. Please try again.",variant:"destructive"}),!1)}catch(y){return console.error("Failed to update profile:",y),r({title:"Update Failed",description:"An error occurred while updating your profile.",variant:"destructive"}),!1}finally{i(!1)}},[n.canUpdateProfile,t,e,r]),p=I.useCallback(async()=>u(""),[u]);return{isUpdatingProfile:s,isUpdatingCallSign:o,isUpdatingDisplayPreference:c,updateCallSign:u,updateDisplayPreference:d,updateProfile:f,clearCallSign:p}}function Tbe(){const{isAuthenticated:t,isAuthenticating:e,verificationStatus:n}=_i(),{verifyOwnership:r,delegateKey:s,getDelegationStatus:i}=Qc(),{toast:o}=xf(),[a,c]=I.useState(!1),[l,u]=I.useState(!1),[d,f]=I.useState(!1),[p,m]=I.useState(!1),y=I.useCallback(async()=>{if(t)return o({title:"Already Connected",description:"Your wallet is already connected."}),!0;c(!0);try{return o({title:"Connecting...",description:"Please approve the connection in your wallet."}),await new Promise(k=>setTimeout(k,2e3)),t?(o({title:"Wallet Connected",description:"Your wallet has been connected successfully."}),!0):(o({title:"Connection Failed",description:"Failed to connect wallet. Please try again.",variant:"destructive"}),!1)}catch(k){return console.error("Failed to connect wallet:",k),o({title:"Connection Error",description:"An error occurred while connecting your wallet.",variant:"destructive"}),!1}finally{c(!1)}},[t,o]),b=I.useCallback(async()=>{if(!t)return o({title:"Not Connected",description:"No wallet is currently connected."}),!0;m(!0);try{return o({title:"Wallet Disconnected",description:"Your wallet has been disconnected."}),!0}catch(k){return console.error("Failed to disconnect wallet:",k),o({title:"Disconnection Error",description:"An error occurred while disconnecting your wallet.",variant:"destructive"}),!1}finally{m(!1)}},[t,o]),v=I.useCallback(async()=>{if(!t)return o({title:"Wallet Not Connected",description:"Please connect your wallet first.",variant:"destructive"}),!1;if(n!==Ct.WALLET_UNCONNECTED)return o({title:"Already Verified",description:"Your wallet is already verified."}),!0;u(!0);try{const k=await r();return o(k?{title:"Verification Complete",description:"Your wallet has been verified successfully."}:{title:"Verification Failed",description:"Failed to verify wallet ownership. Please try again.",variant:"destructive"}),k}catch(k){return console.error("Failed to verify wallet:",k),o({title:"Verification Failed",description:"Failed to verify wallet. Please try again.",variant:"destructive"}),!1}finally{u(!1)}},[t,n,r,o]),x=I.useCallback(async k=>{if(!t)return o({title:"Wallet Not Connected",description:"Please connect your wallet first.",variant:"destructive"}),!1;if(n===Ct.WALLET_UNCONNECTED)return o({title:"Verification Required",description:"Please verify your wallet before delegating keys.",variant:"destructive"}),!1;f(!0);try{const B=await s(k);return o(B?{title:"Key Delegated",description:`Your signing key has been delegated for ${k==="7days"?"1 week":"30 days"}.`}:{title:"Delegation Failed",description:"Failed to delegate signing key. Please try again.",variant:"destructive"}),B}catch(B){return console.error("Failed to delegate key:",B),o({title:"Delegation Failed",description:"Failed to delegate signing key. Please try again.",variant:"destructive"}),!1}finally{f(!1)}},[t,n,s,o]),E=I.useCallback(async()=>{if(!(await i()).isValid)return o({title:"No Active Delegation",description:"There is no active key delegation to clear."}),!0;try{return o({title:"Delegation Cleared",description:"Your key delegation has been cleared."}),!0}catch(B){return console.error("Failed to clear delegation:",B),o({title:"Clear Failed",description:"Failed to clear delegation. Please try again.",variant:"destructive"}),!1}},[i,o]),A=I.useCallback(async k=>await E()?x(k):!1,[E,x]),_=I.useCallback(async()=>{if(t)try{o({title:"Status Updated",description:"Verification status has been refreshed."})}catch(k){console.error("Failed to check verification status:",k),o({title:"Status Check Failed",description:"Failed to refresh verification status.",variant:"destructive"})}},[t,o]);return{isConnecting:a,isVerifying:l||e,isDelegating:d,isDisconnecting:p,connectWallet:y,disconnectWallet:b,verifyWallet:v,delegateKey:x,clearDelegation:E,renewDelegation:A,checkVerificationStatus:_}}function _At(){const{isNetworkConnected:t,isInitialLoading:e,isRefreshing:n,error:r}=xw(),{isAuthenticated:s,currentUser:i}=_i(),{getDelegationStatus:o}=Qc(),[a,c]=I.useState(null);I.useEffect(()=>{o().then(c).catch(console.error)},[o]);const l=I.useMemo(()=>{const x=[];t||x.push("Waku network disconnected"),r&&x.push(`Forum error: ${r}`),s&&!a?.isValid&&x.push("Key delegation expired");const E=x.length===0,A=Date.now(),_=A?SAt(A):null;return{isConnected:t,isHealthy:E,lastSync:A,syncAge:_,issues:x}},[t,r,s,a?.isValid]),u=I.useMemo(()=>{const x=Date.now()-3e4,E=x+6e4;return{isInitialLoading:e,isRefreshing:n,isSyncing:e||n,lastRefresh:x,nextRefresh:E,autoRefreshEnabled:!0}},[e,n]),d=I.useMemo(()=>({waku:{connected:t,peers:t?3:0,status:t?"connected":"disconnected"},wallet:{connected:s,network:i?.walletType==="bitcoin"?"Bitcoin":"Ethereum",status:s?"connected":"disconnected"},delegation:{active:a?.isValid||!1,expires:a?.timeRemaining||null,status:a?.isValid?"active":"expired"}}),[t,s,i,a]),f=!n&&!e,p=t&&!n,m=!l.isHealthy||!a?.isValid,y=I.useMemo(()=>()=>e?"Loading forum data...":n?"Refreshing data...":t?r?`Error: ${r}`:l.issues.length>0?l.issues[0]||"Unknown issue":"All systems operational":"Network disconnected",[e,n,t,r,l.issues]),b=I.useMemo(()=>()=>!t||r?"red":l.issues.length>0||!a?.isValid?"yellow":"green",[t,r,l.issues.length,a?.isValid]),v=I.useMemo(()=>()=>{const x=[];return t||(x.push("Check your internet connection"),x.push("Try refreshing the page")),s||x.push("Connect your wallet"),a?.isValid||x.push("Renew key delegation"),a?.isValid&&a?.timeRemaining&&a.timeRemaining<3600&&x.push("Consider renewing key delegation soon"),r&&x.push("Try refreshing forum data"),x.length===0&&x.push("All systems are working normally"),x},[t,s,a,r]);return{health:l,sync:u,connections:d,canRefresh:f,canSync:p,needsAttention:m,getStatusMessage:y,getHealthColor:b,getRecommendedActions:v}}function SAt(t){const n=Date.now()-t,r=Math.floor(n/1e3),s=Math.floor(r/60),i=Math.floor(s/60),o=Math.floor(i/24);return o>0?`${o}d ago`:i>0?`${i}h ago`:s>0?`${s}m ago`:`${r}s ago`}function AAt(){const[t,e]=I.useState(!1),[n,r]=I.useState(Vs.Unhealthy),[s,i]=I.useState(!1),[o,a]=I.useState("connecting"),c=I.useCallback((l,u)=>{e(l),r(u),l?a("connected"):u===Vs.Unhealthy?a("disconnected"):a("connecting")},[]);return I.useEffect(()=>{try{const l=_n.currentHealth,u=_n.isReady;return i(!0),c(u,l),_n.onHealthChange(c)}catch(l){console.error("Failed to initialize Waku health monitoring:",l),a("error"),i(!1);return}},[c]),{isReady:t,health:n,isInitialized:s,connectionStatus:o}}function Nbe(){const{isReady:t,health:e,connectionStatus:n}=AAt(),r=I.useCallback(()=>{switch(e){case Vs.SufficientlyHealthy:return"Network is healthy and fully operational";case Vs.MinimallyHealthy:return"Network is minimally healthy and functional";case Vs.Unhealthy:return"Network is unhealthy or disconnected";default:return"Network status unknown"}},[e]),s=I.useCallback(()=>t?"green":e===Vs.Unhealthy?"red":"yellow",[t,e]),i=I.useCallback(()=>{switch(n){case"connecting":return"Connecting to Waku network...";case"connected":return"Connected to Waku network";case"disconnected":return"Disconnected from Waku network";case"error":return"Error connecting to Waku network";default:return"Unknown connection status"}},[n]);return{isReady:t,health:e,connectionStatus:n,description:r(),statusColor:s(),statusMessage:i()}}const Pbe=()=>{const t=I.useContext(WW);if(!t)throw new Error("useDelegation must be used within an AuthProvider");const{delegateKey:e,getDelegationStatus:n,clearDelegation:r,isAuthenticating:s}=t,i=I.useCallback(async u=>e(u),[e]),o=I.useCallback(()=>{r()},[r]),[a,c]=I.useState({hasDelegation:!1,isValid:!1});I.useEffect(()=>{n().then(u=>{c({hasDelegation:u.hasDelegation,isValid:u.isValid,timeRemaining:u.timeRemaining,expiresAt:u.timeRemaining?new Date(Date.now()+u.timeRemaining):void 0,publicKey:u.publicKey,address:u.address,walletType:u.walletType})}).catch(console.error)},[n]);const l=I.useCallback(u=>{const d=Math.floor(u/36e5),f=Math.floor(u%(1e3*60*60)/(1e3*60));if(d>24){const p=Math.floor(d/24);return`${p} day${p===1?"":"s"}`}else return d>0?`${d}h ${f}m`:`${f}m`},[]);return{delegationStatus:a,isCreatingDelegation:s,createDelegation:i,clearDelegation:o,formatTimeRemaining:l}},iH=pP("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),fn=I.forwardRef(({className:t,variant:e,size:n,asChild:r=!1,...s},i)=>{const o=r?Fh:"button";return w.jsx(o,{className:Dt(iH({variant:e,size:n,className:t})),ref:i,...s})});fn.displayName="Button";const IAt=pP("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}}),Ao=I.forwardRef(({className:t,variant:e,...n},r)=>w.jsx("div",{className:Dt(IAt({variant:e}),t),ref:r,...n}));Ao.displayName="Badge";var TAt=I.createContext(void 0);function T8(t){const e=I.useContext(TAt);return t||e||"ltr"}var L9=0;function oH(){I.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??rse()),document.body.insertAdjacentElement("beforeend",t[1]??rse()),L9++,()=>{L9===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),L9--}},[])}function rse(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var B9="focusScope.autoFocusOnMount",U9="focusScope.autoFocusOnUnmount",sse={bubbles:!1,cancelable:!0},NAt="FocusScope",N8=I.forwardRef((t,e)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:i,...o}=t,[a,c]=I.useState(null),l=To(s),u=To(i),d=I.useRef(null),f=ir(e,y=>c(y)),p=I.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;I.useEffect(()=>{if(r){let y=function(E){if(p.paused||!a)return;const A=E.target;a.contains(A)?d.current=A:cg(d.current,{select:!0})},b=function(E){if(p.paused||!a)return;const A=E.relatedTarget;A!==null&&(a.contains(A)||cg(d.current,{select:!0}))},v=function(E){if(document.activeElement===document.body)for(const _ of E)_.removedNodes.length>0&&cg(a)};document.addEventListener("focusin",y),document.addEventListener("focusout",b);const x=new MutationObserver(v);return a&&x.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",b),x.disconnect()}}},[r,a,p.paused]),I.useEffect(()=>{if(a){ose.add(p);const y=document.activeElement;if(!a.contains(y)){const v=new CustomEvent(B9,sse);a.addEventListener(B9,l),a.dispatchEvent(v),v.defaultPrevented||(PAt(DAt(kbe(a)),{select:!0}),document.activeElement===y&&cg(a))}return()=>{a.removeEventListener(B9,l),setTimeout(()=>{const v=new CustomEvent(U9,sse);a.addEventListener(U9,u),a.dispatchEvent(v),v.defaultPrevented||cg(y??document.body,{select:!0}),a.removeEventListener(U9,u),ose.remove(p)},0)}}},[a,l,u,p]);const m=I.useCallback(y=>{if(!n&&!r||p.paused)return;const b=y.key==="Tab"&&!y.altKey&&!y.ctrlKey&&!y.metaKey,v=document.activeElement;if(b&&v){const x=y.currentTarget,[E,A]=kAt(x);E&&A?!y.shiftKey&&v===A?(y.preventDefault(),n&&cg(E,{select:!0})):y.shiftKey&&v===E&&(y.preventDefault(),n&&cg(A,{select:!0})):v===x&&y.preventDefault()}},[n,r,p.paused]);return w.jsx(gn.div,{tabIndex:-1,...o,ref:f,onKeyDown:m})});N8.displayName=NAt;function PAt(t,{select:e=!1}={}){const n=document.activeElement;for(const r of t)if(cg(r,{select:e}),document.activeElement!==n)return}function kAt(t){const e=kbe(t),n=ise(e,t),r=ise(e.reverse(),t);return[n,r]}function kbe(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function ise(t,e){for(const n of t)if(!RAt(n,{upTo:e}))return n}function RAt(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function OAt(t){return t instanceof HTMLInputElement&&"select"in t}function cg(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&OAt(t)&&e&&t.select()}}var ose=$At();function $At(){let t=[];return{add(e){const n=t[0];e!==n&&n?.pause(),t=ase(t,e),t.unshift(e)},remove(e){t=ase(t,e),t[0]?.resume()}}}function ase(t,e){const n=[...t],r=n.indexOf(e);return r!==-1&&n.splice(r,1),n}function DAt(t){return t.filter(e=>e.tagName!=="A")}function MAt(t,e=[]){let n=[];function r(i,o){const a=I.createContext(o),c=n.length;n=[...n,o];function l(d){const{scope:f,children:p,...m}=d,y=f?.[t][c]||a,b=I.useMemo(()=>m,Object.values(m));return w.jsx(y.Provider,{value:b,children:p})}function u(d,f){const p=f?.[t][c]||a,m=I.useContext(p);if(m)return m;if(o!==void 0)return o;throw new Error(`\`${d}\` must be used within \`${i}\``)}return l.displayName=i+"Provider",[l,u]}const s=()=>{const i=n.map(o=>I.createContext(o));return function(a){const c=a?.[t]||i;return I.useMemo(()=>({[`__scope${t}`]:{...a,[t]:c}}),[a,c])}};return s.scopeName=t,[r,LAt(s,...e)]}function LAt(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(i){const o=r.reduce((a,{useScope:c,scopeName:l})=>{const d=c(i)[`__scope${l}`];return{...a,...d}},{});return I.useMemo(()=>({[`__scope${e.scopeName}`]:o}),[o])}};return n.scopeName=e.scopeName,n}var F9="rovingFocusGroup.onEntryFocus",BAt={bubbles:!1,cancelable:!0},P8="RovingFocusGroup",[kU,Rbe,UAt]=dP(P8),[FAt,k8]=MAt(P8,[UAt]),[jAt,zAt]=FAt(P8),Obe=I.forwardRef((t,e)=>w.jsx(kU.Provider,{scope:t.__scopeRovingFocusGroup,children:w.jsx(kU.Slot,{scope:t.__scopeRovingFocusGroup,children:w.jsx(WAt,{...t,ref:e})})}));Obe.displayName=P8;var WAt=I.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:s=!1,dir:i,currentTabStopId:o,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:c,onEntryFocus:l,preventScrollOnEntryFocus:u=!1,...d}=t,f=I.useRef(null),p=ir(e,f),m=T8(i),[y=null,b]=jh({prop:o,defaultProp:a,onChange:c}),[v,x]=I.useState(!1),E=To(l),A=Rbe(n),_=I.useRef(!1),[k,B]=I.useState(0);return I.useEffect(()=>{const W=f.current;if(W)return W.addEventListener(F9,E),()=>W.removeEventListener(F9,E)},[E]),w.jsx(jAt,{scope:n,orientation:r,dir:m,loop:s,currentTabStopId:y,onItemFocus:I.useCallback(W=>b(W),[b]),onItemShiftTab:I.useCallback(()=>x(!0),[]),onFocusableItemAdd:I.useCallback(()=>B(W=>W+1),[]),onFocusableItemRemove:I.useCallback(()=>B(W=>W-1),[]),children:w.jsx(gn.div,{tabIndex:v||k===0?-1:0,"data-orientation":r,...d,ref:p,style:{outline:"none",...t.style},onMouseDown:vt(t.onMouseDown,()=>{_.current=!0}),onFocus:vt(t.onFocus,W=>{const S=!_.current;if(W.target===W.currentTarget&&S&&!v){const $=new CustomEvent(F9,BAt);if(W.currentTarget.dispatchEvent($),!$.defaultPrevented){const R=A().filter(T=>T.focusable),M=R.find(T=>T.active),j=R.find(T=>T.id===y),N=[M,j,...R].filter(Boolean).map(T=>T.ref.current);Mbe(N,u)}}_.current=!1}),onBlur:vt(t.onBlur,()=>x(!1))})})}),$be="RovingFocusGroupItem",Dbe=I.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:s=!1,tabStopId:i,...o}=t,a=Wu(),c=i||a,l=zAt($be,n),u=l.currentTabStopId===c,d=Rbe(n),{onFocusableItemAdd:f,onFocusableItemRemove:p}=l;return I.useEffect(()=>{if(r)return f(),()=>p()},[r,f,p]),w.jsx(kU.ItemSlot,{scope:n,id:c,focusable:r,active:s,children:w.jsx(gn.span,{tabIndex:u?0:-1,"data-orientation":l.orientation,...o,ref:e,onMouseDown:vt(t.onMouseDown,m=>{r?l.onItemFocus(c):m.preventDefault()}),onFocus:vt(t.onFocus,()=>l.onItemFocus(c)),onKeyDown:vt(t.onKeyDown,m=>{if(m.key==="Tab"&&m.shiftKey){l.onItemShiftTab();return}if(m.target!==m.currentTarget)return;const y=qAt(m,l.orientation,l.dir);if(y!==void 0){if(m.metaKey||m.ctrlKey||m.altKey||m.shiftKey)return;m.preventDefault();let v=d().filter(x=>x.focusable).map(x=>x.ref.current);if(y==="last")v.reverse();else if(y==="prev"||y==="next"){y==="prev"&&v.reverse();const x=v.indexOf(m.currentTarget);v=l.loop?KAt(v,x+1):v.slice(x+1)}setTimeout(()=>Mbe(v))}})})})});Dbe.displayName=$be;var VAt={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function HAt(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function qAt(t,e,n){const r=HAt(t.key,n);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return VAt[r]}function Mbe(t,e=!1){const n=document.activeElement;for(const r of t)if(r===n||(r.focus({preventScroll:e}),document.activeElement!==n))return}function KAt(t,e){return t.map((n,r)=>t[(e+r)%t.length])}var Lbe=Obe,Bbe=Dbe,GAt=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},yb=new WeakMap,gI=new WeakMap,mI={},j9=0,Ube=function(t){return t&&(t.host||Ube(t.parentNode))},ZAt=function(t,e){return e.map(function(n){if(t.contains(n))return n;var r=Ube(n);return r&&t.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},YAt=function(t,e,n,r){var s=ZAt(e,Array.isArray(t)?t:[t]);mI[n]||(mI[n]=new WeakMap);var i=mI[n],o=[],a=new Set,c=new Set(s),l=function(d){!d||a.has(d)||(a.add(d),l(d.parentNode))};s.forEach(l);var u=function(d){!d||c.has(d)||Array.prototype.forEach.call(d.children,function(f){if(a.has(f))u(f);else try{var p=f.getAttribute(r),m=p!==null&&p!=="false",y=(yb.get(f)||0)+1,b=(i.get(f)||0)+1;yb.set(f,y),i.set(f,b),o.push(f),y===1&&m&&gI.set(f,!0),b===1&&f.setAttribute(n,"true"),m||f.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",f,v)}})};return u(e),a.clear(),j9++,function(){o.forEach(function(d){var f=yb.get(d)-1,p=i.get(d)-1;yb.set(d,f),i.set(d,p),f||(gI.has(d)||d.removeAttribute(r),gI.delete(d)),p||d.removeAttribute(n)}),j9--,j9||(yb=new WeakMap,yb=new WeakMap,gI=new WeakMap,mI={})}},aH=function(t,e,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(t)?t:[t]),s=GAt(t);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live]"))),YAt(r,s,n,"aria-hidden")):function(){return null}},RU=function(t,e){return RU=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},RU(t,e)};function Fbe(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");RU(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var Nl=function(){return Nl=Object.assign||function(e){for(var n,r=1,s=arguments.length;r=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i}function zbe(t,e){return function(n,r){e(n,r,t)}}function Wbe(t,e,n,r,s,i){function o(v){if(v!==void 0&&typeof v!="function")throw new TypeError("Function expected");return v}for(var a=r.kind,c=a==="getter"?"get":a==="setter"?"set":"value",l=!e&&t?r.static?t:t.prototype:null,u=e||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var y in r)m[y]=y==="access"?{}:r[y];for(var y in r.access)m.access[y]=r.access[y];m.addInitializer=function(v){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(v||null))};var b=(0,n[p])(a==="accessor"?{get:u.get,set:u.set}:u[c],m);if(a==="accessor"){if(b===void 0)continue;if(b===null||typeof b!="object")throw new TypeError("Object expected");(d=o(b.get))&&(u.get=d),(d=o(b.set))&&(u.set=d),(d=o(b.init))&&s.unshift(d)}else(d=o(b))&&(a==="field"?s.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0}function Vbe(t,e,n){for(var r=arguments.length>2,s=0;s0&&i[i.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function cH(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i}function Xbe(){for(var t=[],e=0;e1||c(p,y)})},m&&(s[p]=m(s[p])))}function c(p,m){try{l(r[p](m))}catch(y){f(i[0][3],y)}}function l(p){p.value instanceof D1?Promise.resolve(p.value.v).then(u,d):f(i[0][2],p)}function u(p){c("next",p)}function d(p){c("throw",p)}function f(p,m){p(m),i.shift(),i.length&&c(i[0][0],i[0][1])}}function eve(t){var e,n;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,i){e[s]=t[s]?function(o){return(n=!n)?{value:D1(t[s](o)),done:!1}:i?i(o):o}:i}}function tve(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof k4=="function"?k4(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=t[i]&&function(o){return new Promise(function(a,c){o=t[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(l){i({value:l,done:a})},o)}}function nve(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}var XAt=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e};function rve(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&O8(e,t,n);return XAt(e,t),e}function sve(t){return t&&t.__esModule?t:{default:t}}function ive(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}function ove(t,e,n,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(t,n):s?s.value=n:e.set(t,n),n}function ave(t,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof t=="function"?e===t:t.has(e)}function cve(t,e,n){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,s;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],n&&(s=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(i){return Promise.reject(i)}}),t.stack.push({value:e,dispose:r,async:n})}else n&&t.stack.push({async:!0});return e}var QAt=typeof SuppressedError=="function"?SuppressedError:function(t,e,n){var r=new Error(n);return r.name="SuppressedError",r.error=t,r.suppressed=e,r};function lve(t){function e(i){t.error=t.hasError?new QAt(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var n,r=0;function s(){for(;n=t.stack.pop();)try{if(!n.async&&r===1)return r=0,t.stack.push(n),Promise.resolve().then(s);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(i).then(s,function(o){return e(o),s()})}else r|=1}catch(o){e(o)}if(r===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return s()}function uve(t,e){return typeof t=="string"&&/^\.\.?\//.test(t)?t.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(n,r,s,i,o){return r?e?".jsx":".js":s&&(!i||!o)?n:s+i+"."+o.toLowerCase()+"js"}):t}const JAt={__extends:Fbe,__assign:Nl,__rest:R8,__decorate:jbe,__param:zbe,__esDecorate:Wbe,__runInitializers:Vbe,__propKey:Hbe,__setFunctionName:qbe,__metadata:Kbe,__awaiter:Gbe,__generator:Zbe,__createBinding:O8,__exportStar:Ybe,__values:k4,__read:cH,__spread:Xbe,__spreadArrays:Qbe,__spreadArray:lH,__await:D1,__asyncGenerator:Jbe,__asyncDelegator:eve,__asyncValues:tve,__makeTemplateObject:nve,__importStar:rve,__importDefault:sve,__classPrivateFieldGet:ive,__classPrivateFieldSet:ove,__classPrivateFieldIn:ave,__addDisposableResource:cve,__disposeResources:lve,__rewriteRelativeImportExtension:uve},GDt=Object.freeze(Object.defineProperty({__proto__:null,__addDisposableResource:cve,get __assign(){return Nl},__asyncDelegator:eve,__asyncGenerator:Jbe,__asyncValues:tve,__await:D1,__awaiter:Gbe,__classPrivateFieldGet:ive,__classPrivateFieldIn:ave,__classPrivateFieldSet:ove,__createBinding:O8,__decorate:jbe,__disposeResources:lve,__esDecorate:Wbe,__exportStar:Ybe,__extends:Fbe,__generator:Zbe,__importDefault:sve,__importStar:rve,__makeTemplateObject:nve,__metadata:Kbe,__param:zbe,__propKey:Hbe,__read:cH,__rest:R8,__rewriteRelativeImportExtension:uve,__runInitializers:Vbe,__setFunctionName:qbe,__spread:Xbe,__spreadArray:lH,__spreadArrays:Qbe,__values:k4,default:JAt},Symbol.toStringTag,{value:"Module"}));var h6="right-scroll-bar-position",p6="width-before-scroll-bar",eIt="with-scroll-bars-hidden",tIt="--removed-body-scroll-bar-size";function z9(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function nIt(t,e){var n=I.useState(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(r){var s=n.value;s!==r&&(n.value=r,n.callback(r,s))}}}})[0];return n.callback=e,n.facade}var rIt=typeof window<"u"?I.useLayoutEffect:I.useEffect,cse=new WeakMap;function sIt(t,e){var n=nIt(null,function(r){return t.forEach(function(s){return z9(s,r)})});return rIt(function(){var r=cse.get(n);if(r){var s=new Set(r),i=new Set(t),o=n.current;s.forEach(function(a){i.has(a)||z9(a,null)}),i.forEach(function(a){s.has(a)||z9(a,o)})}cse.set(n,t)},[t]),n}function iIt(t){return t}function oIt(t,e){e===void 0&&(e=iIt);var n=[],r=!1,s={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(i){var o=e(i,r);return n.push(o),function(){n=n.filter(function(a){return a!==o})}},assignSyncMedium:function(i){for(r=!0;n.length;){var o=n;n=[],o.forEach(i)}n={push:function(a){return i(a)},filter:function(){return n}}},assignMedium:function(i){r=!0;var o=[];if(n.length){var a=n;n=[],a.forEach(i),o=n}var c=function(){var u=o;o=[],u.forEach(i)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(u){o.push(u),l()},filter:function(u){return o=o.filter(u),n}}}};return s}function aIt(t){t===void 0&&(t={});var e=oIt(null);return e.options=Nl({async:!0,ssr:!1},t),e}var dve=function(t){var e=t.sideCar,n=R8(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=e.read();if(!r)throw new Error("Sidecar medium not found");return I.createElement(r,Nl({},n))};dve.isSideCarExport=!0;function cIt(t,e){return t.useMedium(e),dve}var fve=aIt(),W9=function(){},$8=I.forwardRef(function(t,e){var n=I.useRef(null),r=I.useState({onScrollCapture:W9,onWheelCapture:W9,onTouchMoveCapture:W9}),s=r[0],i=r[1],o=t.forwardProps,a=t.children,c=t.className,l=t.removeScrollBar,u=t.enabled,d=t.shards,f=t.sideCar,p=t.noIsolation,m=t.inert,y=t.allowPinchZoom,b=t.as,v=b===void 0?"div":b,x=t.gapMode,E=R8(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noIsolation","inert","allowPinchZoom","as","gapMode"]),A=f,_=sIt([n,e]),k=Nl(Nl({},E),s);return I.createElement(I.Fragment,null,u&&I.createElement(A,{sideCar:fve,removeScrollBar:l,shards:d,noIsolation:p,inert:m,setCallbacks:i,allowPinchZoom:!!y,lockRef:n,gapMode:x}),o?I.cloneElement(I.Children.only(a),Nl(Nl({},k),{ref:_})):I.createElement(v,Nl({},k,{className:c,ref:_}),a))});$8.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};$8.classNames={fullWidth:p6,zeroRight:h6};var lIt=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function uIt(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=lIt();return e&&t.setAttribute("nonce",e),t}function dIt(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function fIt(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var hIt=function(){var t=0,e=null;return{add:function(n){t==0&&(e=uIt())&&(dIt(e,n),fIt(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},pIt=function(){var t=hIt();return function(e,n){I.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&n])}},hve=function(){var t=pIt(),e=function(n){var r=n.styles,s=n.dynamic;return t(r,s),null};return e},gIt={left:0,top:0,right:0,gap:0},V9=function(t){return parseInt(t||"",10)||0},mIt=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],r=e[t==="padding"?"paddingTop":"marginTop"],s=e[t==="padding"?"paddingRight":"marginRight"];return[V9(n),V9(r),V9(s)]},yIt=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return gIt;var e=mIt(t),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,r-n+e[2]-e[0])}},wIt=hve(),vv="data-scroll-locked",bIt=function(t,e,n,r){var s=t.left,i=t.top,o=t.right,a=t.gap;return n===void 0&&(n="margin"),` + .`.concat(eIt,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(a,"px ").concat(r,`; + } + body[`).concat(vv,`] { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([e&&"position: relative ".concat(r,";"),n==="margin"&&` + padding-left: `.concat(s,`px; + padding-top: `).concat(i,`px; + padding-right: `).concat(o,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(a,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(a,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(h6,` { + right: `).concat(a,"px ").concat(r,`; + } + + .`).concat(p6,` { + margin-right: `).concat(a,"px ").concat(r,`; + } + + .`).concat(h6," .").concat(h6,` { + right: 0 `).concat(r,`; + } + + .`).concat(p6," .").concat(p6,` { + margin-right: 0 `).concat(r,`; + } + + body[`).concat(vv,`] { + `).concat(tIt,": ").concat(a,`px; + } +`)},lse=function(){var t=parseInt(document.body.getAttribute(vv)||"0",10);return isFinite(t)?t:0},vIt=function(){I.useEffect(function(){return document.body.setAttribute(vv,(lse()+1).toString()),function(){var t=lse()-1;t<=0?document.body.removeAttribute(vv):document.body.setAttribute(vv,t.toString())}},[])},xIt=function(t){var e=t.noRelative,n=t.noImportant,r=t.gapMode,s=r===void 0?"margin":r;vIt();var i=I.useMemo(function(){return yIt(s)},[s]);return I.createElement(wIt,{styles:bIt(i,!e,s,n?"":"!important")})},OU=!1;if(typeof window<"u")try{var yI=Object.defineProperty({},"passive",{get:function(){return OU=!0,!0}});window.addEventListener("test",yI,yI),window.removeEventListener("test",yI,yI)}catch{OU=!1}var wb=OU?{passive:!1}:!1,EIt=function(t){return t.tagName==="TEXTAREA"},pve=function(t,e){if(!(t instanceof Element))return!1;var n=window.getComputedStyle(t);return n[e]!=="hidden"&&!(n.overflowY===n.overflowX&&!EIt(t)&&n[e]==="visible")},CIt=function(t){return pve(t,"overflowY")},_It=function(t){return pve(t,"overflowX")},use=function(t,e){var n=e.ownerDocument,r=e;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=gve(t,r);if(s){var i=mve(t,r),o=i[1],a=i[2];if(o>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},SIt=function(t){var e=t.scrollTop,n=t.scrollHeight,r=t.clientHeight;return[e,n,r]},AIt=function(t){var e=t.scrollLeft,n=t.scrollWidth,r=t.clientWidth;return[e,n,r]},gve=function(t,e){return t==="v"?CIt(e):_It(e)},mve=function(t,e){return t==="v"?SIt(e):AIt(e)},IIt=function(t,e){return t==="h"&&e==="rtl"?-1:1},TIt=function(t,e,n,r,s){var i=IIt(t,window.getComputedStyle(e).direction),o=i*r,a=n.target,c=e.contains(a),l=!1,u=o>0,d=0,f=0;do{var p=mve(t,a),m=p[0],y=p[1],b=p[2],v=y-b-i*m;(m||v)&&gve(t,a)&&(d+=v,f+=m),a instanceof ShadowRoot?a=a.host:a=a.parentNode}while(!c&&a!==document.body||c&&(e.contains(a)||e===a));return(u&&(Math.abs(d)<1||!s)||!u&&(Math.abs(f)<1||!s))&&(l=!0),l},wI=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},dse=function(t){return[t.deltaX,t.deltaY]},fse=function(t){return t&&"current"in t?t.current:t},NIt=function(t,e){return t[0]===e[0]&&t[1]===e[1]},PIt=function(t){return` + .block-interactivity-`.concat(t,` {pointer-events: none;} + .allow-interactivity-`).concat(t,` {pointer-events: all;} +`)},kIt=0,bb=[];function RIt(t){var e=I.useRef([]),n=I.useRef([0,0]),r=I.useRef(),s=I.useState(kIt++)[0],i=I.useState(hve)[0],o=I.useRef(t);I.useEffect(function(){o.current=t},[t]),I.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(s));var y=lH([t.lockRef.current],(t.shards||[]).map(fse),!0).filter(Boolean);return y.forEach(function(b){return b.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),y.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(s))})}}},[t.inert,t.lockRef.current,t.shards]);var a=I.useCallback(function(y,b){if("touches"in y&&y.touches.length===2||y.type==="wheel"&&y.ctrlKey)return!o.current.allowPinchZoom;var v=wI(y),x=n.current,E="deltaX"in y?y.deltaX:x[0]-v[0],A="deltaY"in y?y.deltaY:x[1]-v[1],_,k=y.target,B=Math.abs(E)>Math.abs(A)?"h":"v";if("touches"in y&&B==="h"&&k.type==="range")return!1;var W=use(B,k);if(!W)return!0;if(W?_=B:(_=B==="v"?"h":"v",W=use(B,k)),!W)return!1;if(!r.current&&"changedTouches"in y&&(E||A)&&(r.current=_),!_)return!0;var S=r.current||_;return TIt(S,b,y,S==="h"?E:A,!0)},[]),c=I.useCallback(function(y){var b=y;if(!(!bb.length||bb[bb.length-1]!==i)){var v="deltaY"in b?dse(b):wI(b),x=e.current.filter(function(_){return _.name===b.type&&(_.target===b.target||b.target===_.shadowParent)&&NIt(_.delta,v)})[0];if(x&&x.should){b.cancelable&&b.preventDefault();return}if(!x){var E=(o.current.shards||[]).map(fse).filter(Boolean).filter(function(_){return _.contains(b.target)}),A=E.length>0?a(b,E[0]):!o.current.noIsolation;A&&b.cancelable&&b.preventDefault()}}},[]),l=I.useCallback(function(y,b,v,x){var E={name:y,delta:b,target:v,should:x,shadowParent:OIt(v)};e.current.push(E),setTimeout(function(){e.current=e.current.filter(function(A){return A!==E})},1)},[]),u=I.useCallback(function(y){n.current=wI(y),r.current=void 0},[]),d=I.useCallback(function(y){l(y.type,dse(y),y.target,a(y,t.lockRef.current))},[]),f=I.useCallback(function(y){l(y.type,wI(y),y.target,a(y,t.lockRef.current))},[]);I.useEffect(function(){return bb.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",c,wb),document.addEventListener("touchmove",c,wb),document.addEventListener("touchstart",u,wb),function(){bb=bb.filter(function(y){return y!==i}),document.removeEventListener("wheel",c,wb),document.removeEventListener("touchmove",c,wb),document.removeEventListener("touchstart",u,wb)}},[]);var p=t.removeScrollBar,m=t.inert;return I.createElement(I.Fragment,null,m?I.createElement(i,{styles:PIt(s)}):null,p?I.createElement(xIt,{gapMode:t.gapMode}):null)}function OIt(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const $It=cIt(fve,RIt);var D8=I.forwardRef(function(t,e){return I.createElement($8,Nl({},t,{ref:e,sideCar:$It}))});D8.classNames=$8.classNames;var $U=["Enter"," "],DIt=["ArrowDown","PageUp","Home"],yve=["ArrowUp","PageDown","End"],MIt=[...DIt,...yve],LIt={ltr:[...$U,"ArrowRight"],rtl:[...$U,"ArrowLeft"]},BIt={ltr:["ArrowLeft"],rtl:["ArrowRight"]},q3="Menu",[dS,UIt,FIt]=dP(q3),[Ew,wve]=pp(q3,[FIt,K1,k8]),M8=K1(),bve=k8(),[jIt,Cw]=Ew(q3),[zIt,K3]=Ew(q3),vve=t=>{const{__scopeMenu:e,open:n=!1,children:r,dir:s,onOpenChange:i,modal:o=!0}=t,a=M8(e),[c,l]=I.useState(null),u=I.useRef(!1),d=To(i),f=T8(s);return I.useEffect(()=>{const p=()=>{u.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),w.jsx(tj,{...a,children:w.jsx(jIt,{scope:e,open:n,onOpenChange:d,content:c,onContentChange:l,children:w.jsx(zIt,{scope:e,onClose:I.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:u,dir:f,modal:o,children:r})})})};vve.displayName=q3;var WIt="MenuAnchor",uH=I.forwardRef((t,e)=>{const{__scopeMenu:n,...r}=t,s=M8(n);return w.jsx(nj,{...s,...r,ref:e})});uH.displayName=WIt;var dH="MenuPortal",[VIt,xve]=Ew(dH,{forceMount:void 0}),Eve=t=>{const{__scopeMenu:e,forceMount:n,children:r,container:s}=t,i=Cw(dH,e);return w.jsx(VIt,{scope:e,forceMount:n,children:w.jsx(ud,{present:n||i.open,children:w.jsx(OS,{asChild:!0,container:s,children:r})})})};Eve.displayName=dH;var Bl="MenuContent",[HIt,fH]=Ew(Bl),Cve=I.forwardRef((t,e)=>{const n=xve(Bl,t.__scopeMenu),{forceMount:r=n.forceMount,...s}=t,i=Cw(Bl,t.__scopeMenu),o=K3(Bl,t.__scopeMenu);return w.jsx(dS.Provider,{scope:t.__scopeMenu,children:w.jsx(ud,{present:r||i.open,children:w.jsx(dS.Slot,{scope:t.__scopeMenu,children:o.modal?w.jsx(qIt,{...s,ref:e}):w.jsx(KIt,{...s,ref:e})})})})}),qIt=I.forwardRef((t,e)=>{const n=Cw(Bl,t.__scopeMenu),r=I.useRef(null),s=ir(e,r);return I.useEffect(()=>{const i=r.current;if(i)return aH(i)},[]),w.jsx(hH,{...t,ref:s,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:vt(t.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),KIt=I.forwardRef((t,e)=>{const n=Cw(Bl,t.__scopeMenu);return w.jsx(hH,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),hH=I.forwardRef((t,e)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:s,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEntryFocus:c,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,disableOutsideScroll:m,...y}=t,b=Cw(Bl,n),v=K3(Bl,n),x=M8(n),E=bve(n),A=UIt(n),[_,k]=I.useState(null),B=I.useRef(null),W=ir(e,B,b.onContentChange),S=I.useRef(0),$=I.useRef(""),R=I.useRef(0),M=I.useRef(null),j=I.useRef("right"),z=I.useRef(0),N=m?D8:I.Fragment,T=m?{as:Fh,allowPinchZoom:!0}:void 0,U=P=>{const H=$.current+P,Y=A().filter(oe=>!oe.disabled),re=document.activeElement,de=Y.find(oe=>oe.ref.current===re)?.textValue,fe=Y.map(oe=>oe.textValue),ve=i6t(fe,H,de),Ee=Y.find(oe=>oe.textValue===ve)?.ref.current;(function oe(Oe){$.current=Oe,window.clearTimeout(S.current),Oe!==""&&(S.current=window.setTimeout(()=>oe(""),1e3))})(H),Ee&&setTimeout(()=>Ee.focus())};I.useEffect(()=>()=>window.clearTimeout(S.current),[]),oH();const L=I.useCallback(P=>j.current===M.current?.side&&a6t(P,M.current?.area),[]);return w.jsx(HIt,{scope:n,searchRef:$,onItemEnter:I.useCallback(P=>{L(P)&&P.preventDefault()},[L]),onItemLeave:I.useCallback(P=>{L(P)||(B.current?.focus(),k(null))},[L]),onTriggerLeave:I.useCallback(P=>{L(P)&&P.preventDefault()},[L]),pointerGraceTimerRef:R,onPointerGraceIntentChange:I.useCallback(P=>{M.current=P},[]),children:w.jsx(N,{...T,children:w.jsx(N8,{asChild:!0,trapped:s,onMountAutoFocus:vt(i,P=>{P.preventDefault(),B.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:w.jsx(z1,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,children:w.jsx(Lbe,{asChild:!0,...E,dir:v.dir,orientation:"vertical",loop:r,currentTabStopId:_,onCurrentTabStopIdChange:k,onEntryFocus:vt(c,P=>{v.isUsingKeyboardRef.current||P.preventDefault()}),preventScrollOnEntryFocus:!0,children:w.jsx(rj,{role:"menu","aria-orientation":"vertical","data-state":Uve(b.open),"data-radix-menu-content":"",dir:v.dir,...x,...y,ref:W,style:{outline:"none",...y.style},onKeyDown:vt(y.onKeyDown,P=>{const Y=P.target.closest("[data-radix-menu-content]")===P.currentTarget,re=P.ctrlKey||P.altKey||P.metaKey,de=P.key.length===1;Y&&(P.key==="Tab"&&P.preventDefault(),!re&&de&&U(P.key));const fe=B.current;if(P.target!==fe||!MIt.includes(P.key))return;P.preventDefault();const Ee=A().filter(oe=>!oe.disabled).map(oe=>oe.ref.current);yve.includes(P.key)&&Ee.reverse(),r6t(Ee)}),onBlur:vt(t.onBlur,P=>{P.currentTarget.contains(P.target)||(window.clearTimeout(S.current),$.current="")}),onPointerMove:vt(t.onPointerMove,fS(P=>{const H=P.target,Y=z.current!==P.clientX;if(P.currentTarget.contains(H)&&Y){const re=P.clientX>z.current?"right":"left";j.current=re,z.current=P.clientX}}))})})})})})})});Cve.displayName=Bl;var GIt="MenuGroup",pH=I.forwardRef((t,e)=>{const{__scopeMenu:n,...r}=t;return w.jsx(gn.div,{role:"group",...r,ref:e})});pH.displayName=GIt;var ZIt="MenuLabel",_ve=I.forwardRef((t,e)=>{const{__scopeMenu:n,...r}=t;return w.jsx(gn.div,{...r,ref:e})});_ve.displayName=ZIt;var R4="MenuItem",hse="menu.itemSelect",L8=I.forwardRef((t,e)=>{const{disabled:n=!1,onSelect:r,...s}=t,i=I.useRef(null),o=K3(R4,t.__scopeMenu),a=fH(R4,t.__scopeMenu),c=ir(e,i),l=I.useRef(!1),u=()=>{const d=i.current;if(!n&&d){const f=new CustomEvent(hse,{bubbles:!0,cancelable:!0});d.addEventListener(hse,p=>r?.(p),{once:!0}),jF(d,f),f.defaultPrevented?l.current=!1:o.onClose()}};return w.jsx(Sve,{...s,ref:c,disabled:n,onClick:vt(t.onClick,u),onPointerDown:d=>{t.onPointerDown?.(d),l.current=!0},onPointerUp:vt(t.onPointerUp,d=>{l.current||d.currentTarget?.click()}),onKeyDown:vt(t.onKeyDown,d=>{const f=a.searchRef.current!=="";n||f&&d.key===" "||$U.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});L8.displayName=R4;var Sve=I.forwardRef((t,e)=>{const{__scopeMenu:n,disabled:r=!1,textValue:s,...i}=t,o=fH(R4,n),a=bve(n),c=I.useRef(null),l=ir(e,c),[u,d]=I.useState(!1),[f,p]=I.useState("");return I.useEffect(()=>{const m=c.current;m&&p((m.textContent??"").trim())},[i.children]),w.jsx(dS.ItemSlot,{scope:n,disabled:r,textValue:s??f,children:w.jsx(Bbe,{asChild:!0,...a,focusable:!r,children:w.jsx(gn.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:l,onPointerMove:vt(t.onPointerMove,fS(m=>{r?o.onItemLeave(m):(o.onItemEnter(m),m.defaultPrevented||m.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:vt(t.onPointerLeave,fS(m=>o.onItemLeave(m))),onFocus:vt(t.onFocus,()=>d(!0)),onBlur:vt(t.onBlur,()=>d(!1))})})})}),YIt="MenuCheckboxItem",Ave=I.forwardRef((t,e)=>{const{checked:n=!1,onCheckedChange:r,...s}=t;return w.jsx(kve,{scope:t.__scopeMenu,checked:n,children:w.jsx(L8,{role:"menuitemcheckbox","aria-checked":O4(n)?"mixed":n,...s,ref:e,"data-state":mH(n),onSelect:vt(s.onSelect,()=>r?.(O4(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Ave.displayName=YIt;var Ive="MenuRadioGroup",[XIt,QIt]=Ew(Ive,{value:void 0,onValueChange:()=>{}}),Tve=I.forwardRef((t,e)=>{const{value:n,onValueChange:r,...s}=t,i=To(r);return w.jsx(XIt,{scope:t.__scopeMenu,value:n,onValueChange:i,children:w.jsx(pH,{...s,ref:e})})});Tve.displayName=Ive;var Nve="MenuRadioItem",Pve=I.forwardRef((t,e)=>{const{value:n,...r}=t,s=QIt(Nve,t.__scopeMenu),i=n===s.value;return w.jsx(kve,{scope:t.__scopeMenu,checked:i,children:w.jsx(L8,{role:"menuitemradio","aria-checked":i,...r,ref:e,"data-state":mH(i),onSelect:vt(r.onSelect,()=>s.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});Pve.displayName=Nve;var gH="MenuItemIndicator",[kve,JIt]=Ew(gH,{checked:!1}),Rve=I.forwardRef((t,e)=>{const{__scopeMenu:n,forceMount:r,...s}=t,i=JIt(gH,n);return w.jsx(ud,{present:r||O4(i.checked)||i.checked===!0,children:w.jsx(gn.span,{...s,ref:e,"data-state":mH(i.checked)})})});Rve.displayName=gH;var e6t="MenuSeparator",Ove=I.forwardRef((t,e)=>{const{__scopeMenu:n,...r}=t;return w.jsx(gn.div,{role:"separator","aria-orientation":"horizontal",...r,ref:e})});Ove.displayName=e6t;var t6t="MenuArrow",$ve=I.forwardRef((t,e)=>{const{__scopeMenu:n,...r}=t,s=M8(n);return w.jsx(sj,{...s,...r,ref:e})});$ve.displayName=t6t;var n6t="MenuSub",[ZDt,Dve]=Ew(n6t),eE="MenuSubTrigger",Mve=I.forwardRef((t,e)=>{const n=Cw(eE,t.__scopeMenu),r=K3(eE,t.__scopeMenu),s=Dve(eE,t.__scopeMenu),i=fH(eE,t.__scopeMenu),o=I.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:c}=i,l={__scopeMenu:t.__scopeMenu},u=I.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return I.useEffect(()=>u,[u]),I.useEffect(()=>{const d=a.current;return()=>{window.clearTimeout(d),c(null)}},[a,c]),w.jsx(uH,{asChild:!0,...l,children:w.jsx(Sve,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":s.contentId,"data-state":Uve(n.open),...t,ref:uP(e,s.onTriggerChange),onClick:d=>{t.onClick?.(d),!(t.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:vt(t.onPointerMove,fS(d=>{i.onItemEnter(d),!d.defaultPrevented&&!t.disabled&&!n.open&&!o.current&&(i.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:vt(t.onPointerLeave,fS(d=>{u();const f=n.content?.getBoundingClientRect();if(f){const p=n.content?.dataset.side,m=p==="right",y=m?-5:5,b=f[m?"left":"right"],v=f[m?"right":"left"];i.onPointerGraceIntentChange({area:[{x:d.clientX+y,y:d.clientY},{x:b,y:f.top},{x:v,y:f.top},{x:v,y:f.bottom},{x:b,y:f.bottom}],side:p}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(d),d.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:vt(t.onKeyDown,d=>{const f=i.searchRef.current!=="";t.disabled||f&&d.key===" "||LIt[r.dir].includes(d.key)&&(n.onOpenChange(!0),n.content?.focus(),d.preventDefault())})})})});Mve.displayName=eE;var Lve="MenuSubContent",Bve=I.forwardRef((t,e)=>{const n=xve(Bl,t.__scopeMenu),{forceMount:r=n.forceMount,...s}=t,i=Cw(Bl,t.__scopeMenu),o=K3(Bl,t.__scopeMenu),a=Dve(Lve,t.__scopeMenu),c=I.useRef(null),l=ir(e,c);return w.jsx(dS.Provider,{scope:t.__scopeMenu,children:w.jsx(ud,{present:r||i.open,children:w.jsx(dS.Slot,{scope:t.__scopeMenu,children:w.jsx(hH,{id:a.contentId,"aria-labelledby":a.triggerId,...s,ref:l,align:"start",side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{o.isUsingKeyboardRef.current&&c.current?.focus(),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:vt(t.onFocusOutside,u=>{u.target!==a.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:vt(t.onEscapeKeyDown,u=>{o.onClose(),u.preventDefault()}),onKeyDown:vt(t.onKeyDown,u=>{const d=u.currentTarget.contains(u.target),f=BIt[o.dir].includes(u.key);d&&f&&(i.onOpenChange(!1),a.trigger?.focus(),u.preventDefault())})})})})})});Bve.displayName=Lve;function Uve(t){return t?"open":"closed"}function O4(t){return t==="indeterminate"}function mH(t){return O4(t)?"indeterminate":t?"checked":"unchecked"}function r6t(t){const e=document.activeElement;for(const n of t)if(n===e||(n.focus(),document.activeElement!==e))return}function s6t(t,e){return t.map((n,r)=>t[(e+r)%t.length])}function i6t(t,e,n){const s=e.length>1&&Array.from(e).every(l=>l===e[0])?e[0]:e,i=n?t.indexOf(n):-1;let o=s6t(t,Math.max(i,0));s.length===1&&(o=o.filter(l=>l!==n));const c=o.find(l=>l.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function o6t(t,e){const{x:n,y:r}=t;let s=!1;for(let i=0,o=e.length-1;ir!=u>r&&n<(l-a)*(r-c)/(u-c)+a&&(s=!s)}return s}function a6t(t,e){if(!e)return!1;const n={x:t.clientX,y:t.clientY};return o6t(n,e)}function fS(t){return e=>e.pointerType==="mouse"?t(e):void 0}var c6t=vve,l6t=uH,u6t=Eve,d6t=Cve,f6t=pH,h6t=_ve,p6t=L8,g6t=Ave,m6t=Tve,y6t=Pve,w6t=Rve,b6t=Ove,v6t=$ve,x6t=Mve,E6t=Bve,yH="DropdownMenu",[C6t,YDt]=pp(yH,[wve]),fa=wve(),[_6t,Fve]=C6t(yH),jve=t=>{const{__scopeDropdownMenu:e,children:n,dir:r,open:s,defaultOpen:i,onOpenChange:o,modal:a=!0}=t,c=fa(e),l=I.useRef(null),[u=!1,d]=jh({prop:s,defaultProp:i,onChange:o});return w.jsx(_6t,{scope:e,triggerId:Wu(),triggerRef:l,contentId:Wu(),open:u,onOpenChange:d,onOpenToggle:I.useCallback(()=>d(f=>!f),[d]),modal:a,children:w.jsx(c6t,{...c,open:u,onOpenChange:d,dir:r,modal:a,children:n})})};jve.displayName=yH;var zve="DropdownMenuTrigger",Wve=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...s}=t,i=Fve(zve,n),o=fa(n);return w.jsx(l6t,{asChild:!0,...o,children:w.jsx(gn.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...s,ref:uP(e,i.triggerRef),onPointerDown:vt(t.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(i.onOpenToggle(),i.open||a.preventDefault())}),onKeyDown:vt(t.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&i.onOpenToggle(),a.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});Wve.displayName=zve;var S6t="DropdownMenuPortal",Vve=t=>{const{__scopeDropdownMenu:e,...n}=t,r=fa(e);return w.jsx(u6t,{...r,...n})};Vve.displayName=S6t;var Hve="DropdownMenuContent",qve=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=Fve(Hve,n),i=fa(n),o=I.useRef(!1);return w.jsx(d6t,{id:s.contentId,"aria-labelledby":s.triggerId,...i,...r,ref:e,onCloseAutoFocus:vt(t.onCloseAutoFocus,a=>{o.current||s.triggerRef.current?.focus(),o.current=!1,a.preventDefault()}),onInteractOutside:vt(t.onInteractOutside,a=>{const c=a.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0,u=c.button===2||l;(!s.modal||u)&&(o.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});qve.displayName=Hve;var A6t="DropdownMenuGroup",I6t=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(f6t,{...s,...r,ref:e})});I6t.displayName=A6t;var T6t="DropdownMenuLabel",Kve=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(h6t,{...s,...r,ref:e})});Kve.displayName=T6t;var N6t="DropdownMenuItem",Gve=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(p6t,{...s,...r,ref:e})});Gve.displayName=N6t;var P6t="DropdownMenuCheckboxItem",Zve=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(g6t,{...s,...r,ref:e})});Zve.displayName=P6t;var k6t="DropdownMenuRadioGroup",R6t=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(m6t,{...s,...r,ref:e})});R6t.displayName=k6t;var O6t="DropdownMenuRadioItem",Yve=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(y6t,{...s,...r,ref:e})});Yve.displayName=O6t;var $6t="DropdownMenuItemIndicator",Xve=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(w6t,{...s,...r,ref:e})});Xve.displayName=$6t;var D6t="DropdownMenuSeparator",Qve=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(b6t,{...s,...r,ref:e})});Qve.displayName=D6t;var M6t="DropdownMenuArrow",L6t=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(v6t,{...s,...r,ref:e})});L6t.displayName=M6t;var B6t="DropdownMenuSubTrigger",Jve=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(x6t,{...s,...r,ref:e})});Jve.displayName=B6t;var U6t="DropdownMenuSubContent",e1e=I.forwardRef((t,e)=>{const{__scopeDropdownMenu:n,...r}=t,s=fa(n);return w.jsx(E6t,{...s,...r,ref:e,style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});e1e.displayName=U6t;var F6t=jve,j6t=Wve,z6t=Vve,t1e=qve,n1e=Kve,r1e=Gve,s1e=Zve,i1e=Yve,o1e=Xve,a1e=Qve,c1e=Jve,l1e=e1e;const W6t=F6t,V6t=j6t,H6t=I.forwardRef(({className:t,inset:e,children:n,...r},s)=>w.jsxs(c1e,{ref:s,className:Dt("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",e&&"pl-8",t),...r,children:[n,w.jsx(bNe,{className:"ml-auto h-4 w-4"})]}));H6t.displayName=c1e.displayName;const q6t=I.forwardRef(({className:t,...e},n)=>w.jsx(l1e,{ref:n,className:Dt("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...e}));q6t.displayName=l1e.displayName;const u1e=I.forwardRef(({className:t,sideOffset:e=4,...n},r)=>w.jsx(z6t,{children:w.jsx(t1e,{ref:r,sideOffset:e,className:Dt("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...n})}));u1e.displayName=t1e.displayName;const tE=I.forwardRef(({className:t,inset:e,...n},r)=>w.jsx(r1e,{ref:r,className:Dt("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e&&"pl-8",t),...n}));tE.displayName=r1e.displayName;const K6t=I.forwardRef(({className:t,children:e,checked:n,...r},s)=>w.jsxs(s1e,{ref:s,className:Dt("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...r,children:[w.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:w.jsx(o1e,{children:w.jsx(yae,{className:"h-4 w-4"})})}),e]}));K6t.displayName=s1e.displayName;const G6t=I.forwardRef(({className:t,children:e,...n},r)=>w.jsxs(i1e,{ref:r,className:Dt("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[w.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:w.jsx(o1e,{children:w.jsx(bae,{className:"h-2 w-2 fill-current"})})}),e]}));G6t.displayName=i1e.displayName;const Z6t=I.forwardRef(({className:t,inset:e,...n},r)=>w.jsx(n1e,{ref:r,className:Dt("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",t),...n}));Z6t.displayName=n1e.displayName;const d1e=I.forwardRef(({className:t,...e},n)=>w.jsx(a1e,{ref:n,className:Dt("-mx-1 my-1 h-px bg-muted",t),...e}));d1e.displayName=a1e.displayName;var wH="Dialog",[f1e,h1e]=pp(wH),[Y6t,bd]=f1e(wH),p1e=t=>{const{__scopeDialog:e,children:n,open:r,defaultOpen:s,onOpenChange:i,modal:o=!0}=t,a=I.useRef(null),c=I.useRef(null),[l=!1,u]=jh({prop:r,defaultProp:s,onChange:i});return w.jsx(Y6t,{scope:e,triggerRef:a,contentRef:c,contentId:Wu(),titleId:Wu(),descriptionId:Wu(),open:l,onOpenChange:u,onOpenToggle:I.useCallback(()=>u(d=>!d),[u]),modal:o,children:n})};p1e.displayName=wH;var g1e="DialogTrigger",m1e=I.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,s=bd(g1e,n),i=ir(e,s.triggerRef);return w.jsx(gn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":xH(s.open),...r,ref:i,onClick:vt(t.onClick,s.onOpenToggle)})});m1e.displayName=g1e;var bH="DialogPortal",[X6t,y1e]=f1e(bH,{forceMount:void 0}),w1e=t=>{const{__scopeDialog:e,forceMount:n,children:r,container:s}=t,i=bd(bH,e);return w.jsx(X6t,{scope:e,forceMount:n,children:I.Children.map(r,o=>w.jsx(ud,{present:n||i.open,children:w.jsx(OS,{asChild:!0,container:s,children:o})}))})};w1e.displayName=bH;var $4="DialogOverlay",b1e=I.forwardRef((t,e)=>{const n=y1e($4,t.__scopeDialog),{forceMount:r=n.forceMount,...s}=t,i=bd($4,t.__scopeDialog);return i.modal?w.jsx(ud,{present:r||i.open,children:w.jsx(Q6t,{...s,ref:e})}):null});b1e.displayName=$4;var Q6t=I.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,s=bd($4,n);return w.jsx(D8,{as:Fh,allowPinchZoom:!0,shards:[s.contentRef],children:w.jsx(gn.div,{"data-state":xH(s.open),...r,ref:e,style:{pointerEvents:"auto",...r.style}})})}),Hy="DialogContent",v1e=I.forwardRef((t,e)=>{const n=y1e(Hy,t.__scopeDialog),{forceMount:r=n.forceMount,...s}=t,i=bd(Hy,t.__scopeDialog);return w.jsx(ud,{present:r||i.open,children:i.modal?w.jsx(J6t,{...s,ref:e}):w.jsx(eTt,{...s,ref:e})})});v1e.displayName=Hy;var J6t=I.forwardRef((t,e)=>{const n=bd(Hy,t.__scopeDialog),r=I.useRef(null),s=ir(e,n.contentRef,r);return I.useEffect(()=>{const i=r.current;if(i)return aH(i)},[]),w.jsx(x1e,{...t,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:vt(t.onCloseAutoFocus,i=>{i.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:vt(t.onPointerDownOutside,i=>{const o=i.detail.originalEvent,a=o.button===0&&o.ctrlKey===!0;(o.button===2||a)&&i.preventDefault()}),onFocusOutside:vt(t.onFocusOutside,i=>i.preventDefault())})}),eTt=I.forwardRef((t,e)=>{const n=bd(Hy,t.__scopeDialog),r=I.useRef(!1),s=I.useRef(!1);return w.jsx(x1e,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{t.onCloseAutoFocus?.(i),i.defaultPrevented||(r.current||n.triggerRef.current?.focus(),i.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:i=>{t.onInteractOutside?.(i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const o=i.target;n.triggerRef.current?.contains(o)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&s.current&&i.preventDefault()}})}),x1e=I.forwardRef((t,e)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:i,...o}=t,a=bd(Hy,n),c=I.useRef(null),l=ir(e,c);return oH(),w.jsxs(w.Fragment,{children:[w.jsx(N8,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:i,children:w.jsx(z1,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":xH(a.open),...o,ref:l,onDismiss:()=>a.onOpenChange(!1)})}),w.jsxs(w.Fragment,{children:[w.jsx(nTt,{titleId:a.titleId}),w.jsx(sTt,{contentRef:c,descriptionId:a.descriptionId})]})]})}),vH="DialogTitle",E1e=I.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,s=bd(vH,n);return w.jsx(gn.h2,{id:s.titleId,...r,ref:e})});E1e.displayName=vH;var C1e="DialogDescription",_1e=I.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,s=bd(C1e,n);return w.jsx(gn.p,{id:s.descriptionId,...r,ref:e})});_1e.displayName=C1e;var S1e="DialogClose",A1e=I.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,s=bd(S1e,n);return w.jsx(gn.button,{type:"button",...r,ref:e,onClick:vt(t.onClick,()=>s.onOpenChange(!1))})});A1e.displayName=S1e;function xH(t){return t?"open":"closed"}var I1e="DialogTitleWarning",[tTt,T1e]=RTe(I1e,{contentName:Hy,titleName:vH,docsSlug:"dialog"}),nTt=({titleId:t})=>{const e=T1e(I1e),n=`\`${e.contentName}\` requires a \`${e.titleName}\` for the component to be accessible for screen reader users. + +If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component. + +For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return I.useEffect(()=>{t&&(document.getElementById(t)||console.error(n))},[n,t]),null},rTt="DialogDescriptionWarning",sTt=({contentRef:t,descriptionId:e})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${T1e(rTt).contentName}}.`;return I.useEffect(()=>{const s=t.current?.getAttribute("aria-describedby");e&&s&&(document.getElementById(e)||console.warn(r))},[r,t,e]),null},N1e=p1e,P1e=m1e,k1e=w1e,EH=b1e,CH=v1e,_H=E1e,SH=_1e,AH=A1e,R1e="AlertDialog",[iTt,XDt]=pp(R1e,[h1e]),Sp=h1e(),O1e=t=>{const{__scopeAlertDialog:e,...n}=t,r=Sp(e);return w.jsx(N1e,{...r,...n,modal:!0})};O1e.displayName=R1e;var oTt="AlertDialogTrigger",$1e=I.forwardRef((t,e)=>{const{__scopeAlertDialog:n,...r}=t,s=Sp(n);return w.jsx(P1e,{...s,...r,ref:e})});$1e.displayName=oTt;var aTt="AlertDialogPortal",D1e=t=>{const{__scopeAlertDialog:e,...n}=t,r=Sp(e);return w.jsx(k1e,{...r,...n})};D1e.displayName=aTt;var cTt="AlertDialogOverlay",M1e=I.forwardRef((t,e)=>{const{__scopeAlertDialog:n,...r}=t,s=Sp(n);return w.jsx(EH,{...s,...r,ref:e})});M1e.displayName=cTt;var xv="AlertDialogContent",[lTt,uTt]=iTt(xv),L1e=I.forwardRef((t,e)=>{const{__scopeAlertDialog:n,children:r,...s}=t,i=Sp(n),o=I.useRef(null),a=ir(e,o),c=I.useRef(null);return w.jsx(tTt,{contentName:xv,titleName:B1e,docsSlug:"alert-dialog",children:w.jsx(lTt,{scope:n,cancelRef:c,children:w.jsxs(CH,{role:"alertdialog",...i,...s,ref:a,onOpenAutoFocus:vt(s.onOpenAutoFocus,l=>{l.preventDefault(),c.current?.focus({preventScroll:!0})}),onPointerDownOutside:l=>l.preventDefault(),onInteractOutside:l=>l.preventDefault(),children:[w.jsx(FF,{children:r}),w.jsx(fTt,{contentRef:o})]})})})});L1e.displayName=xv;var B1e="AlertDialogTitle",U1e=I.forwardRef((t,e)=>{const{__scopeAlertDialog:n,...r}=t,s=Sp(n);return w.jsx(_H,{...s,...r,ref:e})});U1e.displayName=B1e;var F1e="AlertDialogDescription",j1e=I.forwardRef((t,e)=>{const{__scopeAlertDialog:n,...r}=t,s=Sp(n);return w.jsx(SH,{...s,...r,ref:e})});j1e.displayName=F1e;var dTt="AlertDialogAction",z1e=I.forwardRef((t,e)=>{const{__scopeAlertDialog:n,...r}=t,s=Sp(n);return w.jsx(AH,{...s,...r,ref:e})});z1e.displayName=dTt;var W1e="AlertDialogCancel",V1e=I.forwardRef((t,e)=>{const{__scopeAlertDialog:n,...r}=t,{cancelRef:s}=uTt(W1e,n),i=Sp(n),o=ir(e,s);return w.jsx(AH,{...i,...r,ref:o})});V1e.displayName=W1e;var fTt=({contentRef:t})=>{const e=`\`${xv}\` requires a description for the component to be accessible for screen reader users. + +You can add a description to the \`${xv}\` by passing a \`${F1e}\` component as a child, which also benefits sighted users by adding visible context to the dialog. + +Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${xv}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component. + +For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return I.useEffect(()=>{document.getElementById(t.current?.getAttribute("aria-describedby"))||console.warn(e)},[e,t]),null},hTt=O1e,pTt=$1e,gTt=D1e,H1e=M1e,q1e=L1e,K1e=z1e,G1e=V1e,Z1e=U1e,Y1e=j1e;const X1e=hTt,Q1e=pTt,mTt=gTt,J1e=I.forwardRef(({className:t,...e},n)=>w.jsx(H1e,{className:Dt("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e,ref:n}));J1e.displayName=H1e.displayName;const IH=I.forwardRef(({className:t,...e},n)=>w.jsxs(mTt,{children:[w.jsx(J1e,{}),w.jsx(q1e,{ref:n,className:Dt("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...e})]}));IH.displayName=q1e.displayName;const TH=({className:t,...e})=>w.jsx("div",{className:Dt("flex flex-col space-y-2 text-center sm:text-left",t),...e});TH.displayName="AlertDialogHeader";const NH=({className:t,...e})=>w.jsx("div",{className:Dt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});NH.displayName="AlertDialogFooter";const PH=I.forwardRef(({className:t,...e},n)=>w.jsx(Z1e,{ref:n,className:Dt("text-lg font-semibold",t),...e}));PH.displayName=Z1e.displayName;const kH=I.forwardRef(({className:t,...e},n)=>w.jsx(Y1e,{ref:n,className:Dt("text-sm text-muted-foreground",t),...e}));kH.displayName=Y1e.displayName;const RH=I.forwardRef(({className:t,...e},n)=>w.jsx(K1e,{ref:n,className:Dt(iH(),t),...e}));RH.displayName=K1e.displayName;const OH=I.forwardRef(({className:t,...e},n)=>w.jsx(G1e,{ref:n,className:Dt(iH({variant:"outline"}),"mt-2 sm:mt-0",t),...e}));OH.displayName=G1e.displayName;const $H=N1e,DU=P1e,yTt=k1e,exe=I.forwardRef(({className:t,...e},n)=>w.jsx(EH,{ref:n,className:Dt("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e}));exe.displayName=EH.displayName;const B8=I.forwardRef(({className:t,children:e,...n},r)=>w.jsxs(yTt,{children:[w.jsx(exe,{}),w.jsxs(CH,{ref:r,className:Dt("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...n,children:[e,w.jsxs(AH,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[w.jsx(wP,{className:"h-4 w-4"}),w.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));B8.displayName=CH.displayName;const U8=({className:t,...e})=>w.jsx("div",{className:Dt("flex flex-col space-y-1.5 text-center sm:text-left",t),...e});U8.displayName="DialogHeader";const F8=I.forwardRef(({className:t,...e},n)=>w.jsx(_H,{ref:n,className:Dt("text-lg font-semibold leading-none tracking-tight",t),...e}));F8.displayName=_H.displayName;const txe=I.forwardRef(({className:t,...e},n)=>w.jsx(SH,{ref:n,className:Dt("text-sm text-muted-foreground",t),...e}));txe.displayName=SH.displayName;function wTt({onComplete:t,isLoading:e,setIsLoading:n}){const{initialized:r}=Cut(),s=Eut(),i=g0({namespace:"bip122"}),o=g0({namespace:"eip155"}),a=i.isConnected,c=o.isConnected,l=a||c,d=(a?i:o).address,f=a?"Bitcoin":"Ethereum",p=async()=>{if(!r||!s){console.error("AppKit not initialized");return}n(!0);try{await s.open({view:"Connect",namespace:"bip122"})}catch(b){console.error("Error connecting Bitcoin wallet:",b)}finally{n(!1)}},m=async()=>{if(!r||!s){console.error("AppKit not initialized");return}n(!0);try{await s.open({view:"Connect",namespace:"eip155"})}catch(b){console.error("Error connecting Ethereum wallet:",b)}finally{n(!1)}},y=()=>{t()};return r?l?w.jsxs("div",{className:"flex flex-col h-full",children:[w.jsx("div",{className:"flex-1 space-y-4",children:w.jsxs("div",{className:"p-4 bg-green-900/20 border border-green-500/30 rounded-lg",children:[w.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[w.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),w.jsx("span",{className:"text-green-400 font-medium",children:"Wallet Connected"})]}),w.jsxs("p",{className:"text-sm text-neutral-300 mb-2",children:["Connected to ",f," with ",d?.slice(0,6),"...",d?.slice(-4)]})]})}),w.jsx("div",{className:"mt-auto",children:w.jsx(fn,{onClick:y,className:"w-full bg-blue-600 hover:bg-blue-700 text-white",disabled:e,children:"Next"})})]}):w.jsx("div",{className:"flex flex-col h-full",children:w.jsxs("div",{className:"flex-1 space-y-4",children:[w.jsx("p",{className:"text-sm text-neutral-400 text-center",children:"Choose a network and wallet to connect to OpChan"}),w.jsxs("div",{className:"space-y-3",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(mae,{className:"h-5 w-5 text-orange-500"}),w.jsx("h3",{className:"font-semibold text-white",children:"Bitcoin"}),w.jsx(Ao,{variant:"secondary",className:"text-xs",children:"Ordinal Verification Required"})]}),w.jsx(fn,{onClick:p,disabled:e,className:"w-full bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 text-white",style:{height:"44px",borderRadius:"8px",border:"none",fontSize:"14px",fontWeight:"600",display:"flex",alignItems:"center",justifyContent:"center",gap:"8px"},children:e?w.jsxs(w.Fragment,{children:[w.jsx(Xd,{className:"h-4 w-4 animate-spin"}),"Connecting..."]}):"Connect Bitcoin Wallet"})]}),w.jsxs("div",{className:"relative",children:[w.jsx("div",{className:"absolute inset-0 flex items-center",children:w.jsx("span",{className:"w-full border-t border-neutral-700"})}),w.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:w.jsx("span",{className:"bg-black px-2 text-neutral-500",children:"or"})})]}),w.jsxs("div",{className:"space-y-3",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(vae,{className:"h-5 w-5 text-blue-500"}),w.jsx("h3",{className:"font-semibold text-white",children:"Ethereum"}),w.jsx(Ao,{variant:"secondary",className:"text-xs",children:"ENS Ownership Required"})]}),w.jsx(fn,{onClick:m,disabled:e,className:"w-full bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 text-white",style:{height:"44px",borderRadius:"8px",border:"none",fontSize:"14px",fontWeight:"600",display:"flex",alignItems:"center",justifyContent:"center",gap:"8px"},children:e?w.jsxs(w.Fragment,{children:[w.jsx(Xd,{className:"h-4 w-4 animate-spin"}),"Connecting..."]}):"Connect Ethereum Wallet"})]}),w.jsx("div",{className:"text-xs text-neutral-500 text-center pt-2",children:"Connect your wallet to use OpChan's features"})]})}):w.jsxs("div",{className:"flex flex-col items-center justify-center h-full space-y-4",children:[w.jsx(Xd,{className:"h-8 w-8 animate-spin text-blue-500"}),w.jsx("p",{className:"text-neutral-400 text-center",children:"Initializing wallet connection..."})]})}function bTt({onComplete:t,onBack:e,isLoading:n,setIsLoading:r}){const{currentUser:s,verificationStatus:i,isAuthenticating:o}=_i(),{verifyWallet:a}=Tbe(),c=g0({namespace:"bip122"}),l=g0({namespace:"eip155"}),u=c.isConnected,d=l.isConnected,f=u?"bitcoin":d?"ethereum":void 0,[p,m]=I.useState(null);I.useEffect(()=>{if(p?.success&&p.message.includes("Checking ownership")){const _=f==="bitcoin"?!!s?.ordinalDetails:!!s?.ensDetails;m(_?{success:!0,message:f==="bitcoin"?"Ordinal ownership verified successfully!":"ENS ownership verified successfully!",details:f==="bitcoin"?s?.ordinalDetails:s?.ensDetails}:{success:!1,message:f==="bitcoin"?"No Ordinal ownership found. You can still participate in the forum with your connected wallet!":"No ENS ownership found. You can still participate in the forum with your connected wallet!"})}},[s,p,f]);const y=async()=>{if(s){r(!0),m(null);try{const _=await a();m(_?{success:!0,message:"Verification process completed. Checking ownership...",details:void 0}:{success:!1,message:f==="bitcoin"?"No Ordinal ownership found. You can still participate in the forum with your connected wallet!":"No ENS ownership found. You can still participate in the forum with your connected wallet!"})}catch(_){m({success:!1,message:`Verification failed. Please try again: ${_}`})}finally{r(!1)}}},b=()=>{t()},v=()=>f==="bitcoin"?"Bitcoin Ordinal":"Ethereum ENS",x=()=>f==="bitcoin"?mae:vae,E=()=>f==="bitcoin"?"text-orange-500":"text-blue-500",A=()=>f==="bitcoin"?"Verify your Bitcoin Ordinal ownership to unlock premium features. If you don't own any Ordinals, you can still participate in the forum with your connected wallet.":"Verify your Ethereum ENS ownership to unlock premium features. If you don't own any ENS, you can still participate in the forum with your connected wallet.";return p?w.jsxs("div",{className:"flex flex-col h-full",children:[w.jsx("div",{className:"flex-1 space-y-4",children:w.jsxs("div",{className:`p-4 rounded-lg border ${p.success?"bg-green-900/20 border-green-500/30":"bg-yellow-900/20 border-yellow-500/30"}`,children:[w.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[p.success?w.jsx(UZ,{className:"h-5 w-5 text-green-500"}):w.jsx(YM,{className:"h-5 w-5 text-yellow-500"}),w.jsx("span",{className:`font-medium ${p.success?"text-green-400":"text-yellow-400"}`,children:p.success?"Verification Complete":"Verification Result"})]}),w.jsx("p",{className:"text-sm text-neutral-300 mb-2",children:p.message}),p.details&&w.jsx("div",{className:"text-xs text-neutral-400",children:f==="bitcoin"?w.jsxs("p",{children:["Ordinal ID:"," ",typeof p.details=="object"&&"ordinalId"in p.details?p.details.ordinalId:"Verified"]}):w.jsxs("p",{children:["ENS Name:"," ",typeof p.details=="object"&&"ensName"in p.details?p.details.ensName:"Verified"]})})]})}),w.jsx("div",{className:"mt-auto",children:w.jsx(fn,{onClick:b,className:"w-full bg-blue-600 hover:bg-blue-700 text-white",disabled:n,children:"Next"})})]}):i===Ct.ENS_ORDINAL_VERIFIED?w.jsxs("div",{className:"flex flex-col h-full",children:[w.jsx("div",{className:"flex-1 space-y-4",children:w.jsxs("div",{className:"p-4 bg-green-900/20 border border-green-500/30 rounded-lg",children:[w.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[w.jsx(UZ,{className:"h-5 w-5 text-green-500"}),w.jsx("span",{className:"text-green-400 font-medium",children:"Already Verified"})]}),w.jsxs("p",{className:"text-sm text-neutral-300 mb-2",children:["Your ",v()," ownership has been verified."]}),s&&w.jsxs("div",{className:"text-xs text-neutral-400",children:[f==="bitcoin"&&w.jsx("p",{children:"Ordinal ID: Verified"}),f==="ethereum"&&w.jsx("p",{children:"ENS Name: Verified"})]})]})}),w.jsx("div",{className:"mt-auto",children:w.jsx(fn,{onClick:b,className:"w-full bg-blue-600 hover:bg-blue-700 text-white",disabled:n,children:"Next"})})]}):w.jsxs("div",{className:"flex flex-col h-full",children:[w.jsxs("div",{className:"flex-1 space-y-4",children:[w.jsxs("div",{className:"text-center space-y-2",children:[w.jsx("div",{className:"flex justify-center",children:I.createElement(x(),{className:`h-8 w-8 ${E()}`})}),w.jsxs("h3",{className:"text-lg font-semibold text-white",children:["Verify ",v()," Ownership"]}),w.jsx("p",{className:"text-sm text-neutral-400",children:A()})]}),w.jsxs("div",{className:"p-4 bg-neutral-900/50 border border-neutral-700 rounded-lg",children:[w.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[w.jsx(zh,{className:"h-4 w-4 text-blue-500"}),w.jsx("span",{className:"text-sm font-medium text-white",children:"What happens during verification?"})]}),w.jsx("ul",{className:"text-xs text-neutral-400 space-y-1",children:f==="bitcoin"?w.jsxs(w.Fragment,{children:[w.jsx("li",{children:"• We'll check your wallet for Bitcoin Ordinal ownership"}),w.jsx("li",{children:"• If found, you'll get full posting and voting access"}),w.jsx("li",{children:"• If not found, you'll have read-only access"})]}):w.jsxs(w.Fragment,{children:[w.jsx("li",{children:"• We'll check your wallet for ENS domain ownership"}),w.jsx("li",{children:"• If found, you'll get full posting and voting access"}),w.jsx("li",{children:"• If not found, you'll have read-only access"})]})})]}),w.jsx("div",{className:"text-xs text-neutral-500 text-center",children:"Verification is required to access posting and voting features"})]}),w.jsxs("div",{className:"mt-auto space-y-3",children:[w.jsx(fn,{onClick:y,disabled:n||o,className:"w-full bg-blue-600 hover:bg-blue-700 text-white",children:n||o?w.jsxs(w.Fragment,{children:[w.jsx(Xd,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):`Verify ${v()} Ownership`}),w.jsx(fn,{onClick:e,variant:"outline",className:"w-full border-neutral-600 text-neutral-400 hover:bg-neutral-800",disabled:n||o,children:"Back"})]})]})}function vTt({onComplete:t,onBack:e,isLoading:n,setIsLoading:r}){const{currentUser:s,isAuthenticating:i}=_i(),{getDelegationStatus:o}=Qc(),[a,c]=I.useState(null),{delegateKey:l,clearDelegation:u}=Tbe();I.useEffect(()=>{o().then(c).catch(console.error)},[o]);const[d,f]=qe.useState("7days"),[p,m]=qe.useState(null),y=async()=>{if(s){r(!0),m(null);try{if(await l(d)){const x=s.delegationExpiry?new Date(s.delegationExpiry).toLocaleString():`${d==="7days"?"1 week":"30 days"} from now`;m({success:!0,message:"Key delegation successful!",expiry:x})}else m({success:!1,message:"Key delegation failed."})}catch(v){m({success:!1,message:`Delegation failed. Please try again: ${v}`})}finally{r(!1)}}},b=()=>{t()};return p?w.jsxs("div",{className:"flex flex-col h-full",children:[w.jsx("div",{className:"flex-1 space-y-4",children:w.jsxs("div",{className:"text-center",children:[p.success?w.jsx(cC,{className:"h-12 w-12 text-green-500 mx-auto mb-4"}):w.jsx(YM,{className:"h-12 w-12 text-red-500 mx-auto mb-4"}),w.jsx("h3",{className:"text-lg font-semibold mb-2",children:p.success?"Success!":"Failed"}),w.jsx("p",{className:"text-sm text-neutral-400",children:p.message}),p.success&&p.expiry&&w.jsxs("p",{className:"text-xs text-neutral-500 mt-2",children:["Expires: ",p.expiry]})]})}),w.jsxs("div",{className:"mt-auto space-y-2",children:[w.jsx(fn,{onClick:b,className:"w-full bg-green-600 hover:bg-green-700 text-white",children:"Continue"}),e&&w.jsx(fn,{onClick:e,variant:"outline",className:"w-full",children:"Back"})]})]}):w.jsxs("div",{className:"flex flex-col h-full",children:[w.jsxs("div",{className:"flex-1 space-y-6",children:[w.jsxs("div",{className:"text-center space-y-2",children:[w.jsx("h3",{className:"text-lg font-semibold text-white",children:"Step 3: Key Delegation"}),w.jsx("p",{className:"text-sm text-neutral-400",children:"Delegate signing authority to your browser for convenient forum interactions"})]}),w.jsxs("div",{className:"space-y-3",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[a?.isValid?w.jsx(cC,{className:"h-4 w-4 text-green-500"}):w.jsx(YM,{className:"h-4 w-4 text-yellow-500"}),w.jsx("span",{className:`text-sm font-medium ${a?.isValid?"text-green-400":"text-yellow-400"}`,children:a?.isValid?"Delegated":"Required"}),a?.isValid&&a?.timeRemaining&&w.jsxs("span",{className:"text-xs text-neutral-400",children:[a.timeRemaining," remaining"]})]}),!a?.isValid&&w.jsxs("div",{className:"space-y-3",children:[w.jsx("label",{className:"text-sm font-medium text-neutral-300",children:"Delegation Duration:"}),w.jsxs("div",{className:"space-y-2",children:[w.jsxs("label",{className:"flex items-center space-x-2",children:[w.jsx("input",{type:"radio",name:"duration",value:"7days",checked:d==="7days",onChange:v=>f(v.target.value),className:"text-blue-500"}),w.jsx("span",{className:"text-sm text-neutral-300",children:"7 days (recommended)"})]}),w.jsxs("label",{className:"flex items-center space-x-2",children:[w.jsx("input",{type:"radio",name:"duration",value:"30days",checked:d==="30days",onChange:v=>f(v.target.value),className:"text-blue-500"}),w.jsx("span",{className:"text-sm text-neutral-300",children:"30 days"})]})]})]}),a?.isValid&&s?.browserPubKey&&w.jsx("div",{className:"text-xs text-neutral-400",children:w.jsx("div",{className:"font-mono break-all bg-neutral-800 p-2 rounded",children:s.browserPubKey})}),s&&w.jsx("div",{className:"text-xs text-neutral-400",children:w.jsx("div",{className:"font-mono break-all",children:s.address})}),a?.isValid&&w.jsx("div",{className:"flex justify-end",children:w.jsxs(fn,{onClick:u,variant:"outline",size:"sm",className:"text-red-400 border-red-400 hover:bg-red-400 hover:text-white",children:[w.jsx(yP,{className:"h-3 w-3 mr-1"}),"Clear Delegation"]})})]})]}),w.jsxs("div",{className:"mt-auto space-y-2",children:[a?.isValid?w.jsx(fn,{onClick:b,className:"w-full bg-green-600 hover:bg-green-700 text-white",disabled:n,children:"Continue"}):w.jsx(fn,{onClick:y,className:"w-full bg-blue-600 hover:bg-blue-700 text-white",disabled:n||i,children:n?"Delegating...":"Delegate Key"}),e&&w.jsx(fn,{onClick:e,variant:"outline",className:"w-full",disabled:n,children:"Back"})]})]})}function nxe({open:t,onOpenChange:e,onComplete:n}){const[r,s]=I.useState(1),[i,o]=I.useState(!1),{isAuthenticated:a,verificationStatus:c}=_i(),{delegationStatus:l}=Pbe();I.useEffect(()=>{t&&(s(1),o(!1))},[t]);const u=y=>{y<3?s(y+1):(n(),e(!1))},d=()=>{i||e(!1)},f=y=>y{const b=f(y);return b==="complete"||(x=>{switch(x){case 1:return a;case 2:return c!==Ct.WALLET_UNCONNECTED;case 3:return l.isValid;default:return!1}})(y)?w.jsx(cC,{className:"h-5 w-5 text-green-500"}):b==="current"?w.jsx(Xd,{className:"h-5 w-5 text-blue-500 animate-spin"}):w.jsx(bae,{className:"h-5 w-5 text-gray-400"})},m=y=>{switch(y){case 1:return"Connect Wallet";case 2:return"Verify Ownership";case 3:return"Delegate Key";default:return""}};return w.jsx($H,{open:t,onOpenChange:d,children:w.jsxs(B8,{className:"sm:max-w-md border-neutral-800 bg-black text-white",children:[w.jsxs(U8,{children:[w.jsx(F8,{className:"text-xl",children:"Setup Your Account"}),w.jsx(txe,{className:"text-neutral-400",children:"Complete these steps to access all OpChan features"})]}),w.jsx("div",{className:"flex items-center justify-between mb-6",children:[1,2,3].map(y=>w.jsxs("div",{className:"flex items-center",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[p(y),w.jsx("span",{className:`text-sm ${f(y)==="current"?"text-blue-500 font-medium":f(y)==="complete"||y===1&&a||y===2&&c!==Ct.WALLET_UNCONNECTED||y===3&&l.isValid?"text-green-500":"text-gray-400"}`,children:m(y)})]}),y<3&&w.jsx("div",{className:`w-8 h-px mx-2 ${f(y)==="complete"||y===1&&a||y===2&&c!==Ct.WALLET_UNCONNECTED?"bg-green-500":"bg-gray-600"}`})]},y))}),w.jsxs("div",{className:"h-[400px] flex flex-col",children:[r===1&&w.jsx(wTt,{onComplete:()=>u(1),isLoading:i,setIsLoading:o}),r===2&&w.jsx(bTt,{onComplete:()=>u(2),onBack:()=>s(1),isLoading:i,setIsLoading:o}),r===3&&w.jsx(vTt,{onComplete:()=>u(3),onBack:()=>s(2),isLoading:i,setIsLoading:o})]}),w.jsxs("div",{className:"flex justify-between items-center pt-4 border-t border-neutral-700",children:[w.jsxs("p",{className:"text-xs text-neutral-500",children:["Step ",r," of 3"]}),r>1&&w.jsx(fn,{variant:"ghost",size:"sm",onClick:()=>s(r-1),disabled:i,className:"text-neutral-400 hover:text-white",children:"Back"})]})]})})}function H9({className:t}){const{statusColor:e}=Nbe();return w.jsx("div",{className:Dt("w-2 h-2 rounded-full",e==="green"&&"bg-green-500",e==="yellow"&&"bg-yellow-500 animate-pulse",e==="red"&&"bg-red-500",t),title:`Waku network: ${e}`})}const Kd=()=>{const{verificationStatus:t}=_i(),{getDelegationStatus:e}=Qc(),[n,r]=I.useState(null),s=Nbe(),i=Z1(),{toast:o}=xf(),a=xw(),c=g0({namespace:"bip122"}),l=g0({namespace:"eip155"}),{disconnect:u}=l0e(),d=c.isConnected,f=l.isConnected,p=d||f,m=p?d?c.address:l.address:void 0,[y,b]=I.useState(!1),[v,x]=I.useState(!1),{displayName:E}=H3(m||"");qe.useEffect(()=>{e().then(r).catch(console.error)},[e]);const A=async()=>{try{return await ct.loadUIState("hasShownWalletWizard")===!0}catch{return!1}},_=async R=>{try{await ct.storeUIState("hasShownWalletWizard",R)}catch(M){console.error("Failed to store wizard state",M)}};qe.useEffect(()=>{p&&A().then(R=>{R||(b(!0),_(!0).catch(console.error))})},[p]);const k=async()=>{b(!0)},B=()=>{b(!0)},W=async()=>{await u(),await _(!1),o({title:"Wallet Disconnected",description:"Your wallet has been disconnected successfully."})},S=async()=>{try{await ct.clearAll(),o({title:"Database Cleared",description:"All local data has been cleared successfully."})}catch(R){console.error("Failed to clear database:",R),o({title:"Error",description:"Failed to clear local database. Please try again.",variant:"destructive"})}},$=()=>p?t===Ct.ENS_ORDINAL_VERIFIED&&n?.isValid?w.jsx(cC,{className:"w-4 h-4"}):t===Ct.WALLET_CONNECTED?w.jsx(G6,{className:"w-4 h-4"}):t===Ct.ENS_ORDINAL_VERIFIED?w.jsx(TNe,{className:"w-4 h-4"}):w.jsx(G6,{className:"w-4 h-4"}):w.jsx(xNe,{className:"w-4 h-4"});return w.jsxs(w.Fragment,{children:[w.jsx("header",{className:"bg-black/80 border-b border-cyber-muted/30 sticky top-0 z-50 backdrop-blur-md",children:w.jsxs("div",{className:"container mx-auto px-4",children:[w.jsxs("div",{className:"flex items-center justify-between h-16",children:[w.jsx("div",{className:"flex items-center",children:w.jsxs(ks,{to:"/",className:"flex items-center space-x-2 text-xl font-mono font-bold text-white hover:text-cyber-accent transition-colors",children:[w.jsx($Ne,{className:"w-6 h-6"}),w.jsx("span",{className:"tracking-wider",children:"opchan"})]})}),w.jsx("div",{className:"hidden lg:flex items-center space-x-3",children:w.jsxs("div",{className:"flex items-center space-x-2 px-3 py-1 bg-cyber-muted/20 rounded-full border border-cyber-muted/30",children:[w.jsx(H9,{}),w.jsx("span",{className:"text-xs font-mono text-cyber-neutral",children:s.statusMessage}),a.lastSync&&w.jsxs("div",{className:"flex items-center space-x-1 text-xs text-cyber-neutral/70",children:[w.jsx(W1,{className:"w-3 h-3"}),w.jsx("span",{children:new Date(a.lastSync).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})]})}),w.jsxs("div",{className:"flex items-center space-x-3",children:[w.jsx("div",{className:"lg:hidden",children:w.jsx(H9,{})}),p?w.jsxs("div",{className:"flex items-center space-x-2",children:[w.jsxs(Ao,{variant:"outline",className:`font-mono text-xs border-0 ${t===Ct.ENS_ORDINAL_VERIFIED&&n?.isValid?"bg-green-500/20 text-green-400 border-green-500/30":t===Ct.ENS_ORDINAL_VERIFIED?"bg-orange-500/20 text-orange-400 border-orange-500/30":"bg-yellow-500/20 text-yellow-400 border-yellow-500/30"}`,children:[$(),w.jsx("span",{className:"ml-1",children:t===Ct.ENS_ORDINAL_VERIFIED&&n?.isValid?"READY":t===Ct.ENS_ORDINAL_VERIFIED?"EXPIRED":"VERIFY"})]}),w.jsxs(W6t,{children:[w.jsx(V6t,{asChild:!0,children:w.jsxs(fn,{variant:"ghost",size:"sm",className:"flex items-center space-x-2 text-white hover:bg-cyber-muted/30",children:[w.jsx("div",{className:"text-sm font-mono",children:E}),w.jsx(JM,{className:"w-4 h-4"})]})}),w.jsxs(u1e,{align:"end",className:"w-56 bg-black/95 border-cyber-muted/30",children:[w.jsxs("div",{className:"px-3 py-2 border-b border-cyber-muted/30",children:[w.jsx("div",{className:"text-sm font-medium text-white",children:E}),w.jsxs("div",{className:"text-xs text-cyber-neutral",children:[m?.slice(0,8),"...",m?.slice(-4)]})]}),w.jsx(tE,{asChild:!0,children:w.jsxs(ks,{to:"/profile",className:"flex items-center space-x-2",children:[w.jsx(gE,{className:"w-4 h-4"}),w.jsx("span",{children:"Profile"})]})}),w.jsxs(tE,{onClick:B,className:"flex items-center space-x-2",children:[w.jsx(JM,{className:"w-4 h-4"}),w.jsx("span",{children:"Setup Wizard"})]}),w.jsx(d1e,{className:"bg-cyber-muted/30"}),w.jsxs(X1e,{children:[w.jsx(Q1e,{asChild:!0,children:w.jsxs(tE,{onSelect:R=>R.preventDefault(),className:"flex items-center space-x-2 text-orange-400 focus:text-orange-400",children:[w.jsx(yP,{className:"w-4 h-4"}),w.jsx("span",{children:"Clear Database"})]})}),w.jsxs(IH,{className:"bg-black/95 border-cyber-muted/30",children:[w.jsxs(TH,{children:[w.jsx(PH,{className:"text-white",children:"Clear Local Database"}),w.jsxs(kH,{className:"text-cyber-neutral",children:["This will permanently delete all locally stored data including:",w.jsx("br",{}),"• Posts and comments",w.jsx("br",{}),"• User identities and preferences",w.jsx("br",{}),"• Bookmarks and votes",w.jsx("br",{}),"• UI state and settings",w.jsx("br",{}),w.jsx("br",{}),w.jsx("strong",{children:"This action cannot be undone."})]})]}),w.jsxs(NH,{children:[w.jsx(OH,{className:"bg-cyber-muted/20 border-cyber-muted/30 text-white hover:bg-cyber-muted/30",children:"Cancel"}),w.jsx(RH,{onClick:S,className:"bg-red-600 hover:bg-red-700 text-white",children:"Clear Database"})]})]})]}),w.jsxs(tE,{onClick:W,className:"flex items-center space-x-2 text-red-400 focus:text-red-400",children:[w.jsx(NNe,{className:"w-4 h-4"}),w.jsx("span",{children:"Disconnect"})]})]})]})]}):w.jsx(fn,{onClick:k,className:"bg-cyber-accent hover:bg-cyber-accent/80 text-black font-mono font-medium",children:"Connect"}),w.jsx(fn,{variant:"ghost",size:"sm",onClick:()=>x(!v),className:"md:hidden text-white hover:bg-cyber-muted/30",children:v?w.jsx(wP,{className:"w-5 h-5"}):w.jsx(PNe,{className:"w-5 h-5"})})]})]}),w.jsx("div",{className:"hidden md:flex items-center justify-center border-t border-cyber-muted/20 py-2",children:w.jsxs("nav",{className:"flex items-center space-x-1",children:[w.jsxs(ks,{to:"/",className:`flex items-center space-x-2 px-4 py-2 rounded-md text-sm font-mono transition-all ${i.pathname==="/"?"bg-cyber-accent/20 text-cyber-accent border border-cyber-accent/30":"text-cyber-neutral hover:text-white hover:bg-cyber-muted/20"}`,children:[w.jsx(BZ,{className:"w-4 h-4"}),w.jsx("span",{children:"HOME"})]}),w.jsxs(ks,{to:"/cells",className:`flex items-center space-x-2 px-4 py-2 rounded-md text-sm font-mono transition-all ${i.pathname==="/cells"?"bg-cyber-accent/20 text-cyber-accent border border-cyber-accent/30":"text-cyber-neutral hover:text-white hover:bg-cyber-muted/20"}`,children:[w.jsx(QM,{className:"w-4 h-4"}),w.jsx("span",{children:"CELLS"})]}),p&&w.jsx(w.Fragment,{children:w.jsxs(ks,{to:"/bookmarks",className:`flex items-center space-x-2 px-4 py-2 rounded-md text-sm font-mono transition-all ${i.pathname==="/bookmarks"?"bg-cyber-accent/20 text-cyber-accent border border-cyber-accent/30":"text-cyber-neutral hover:text-white hover:bg-cyber-muted/20"}`,children:[w.jsx(Fm,{className:"w-4 h-4"}),w.jsx("span",{children:"BOOKMARKS"})]})})]})}),v&&w.jsxs("div",{className:"md:hidden border-t border-cyber-muted/20 py-4 space-y-2",children:[w.jsxs("nav",{className:"space-y-1",children:[w.jsxs(ks,{to:"/",className:`flex items-center space-x-3 px-4 py-3 rounded-md text-sm font-mono transition-all ${i.pathname==="/"?"bg-cyber-accent/20 text-cyber-accent border border-cyber-accent/30":"text-cyber-neutral hover:text-white hover:bg-cyber-muted/20"}`,onClick:()=>x(!1),children:[w.jsx(BZ,{className:"w-4 h-4"}),w.jsx("span",{children:"HOME"})]}),w.jsxs(ks,{to:"/cells",className:`flex items-center space-x-3 px-4 py-3 rounded-md text-sm font-mono transition-all ${i.pathname==="/cells"?"bg-cyber-accent/20 text-cyber-accent border border-cyber-accent/30":"text-cyber-neutral hover:text-white hover:bg-cyber-muted/20"}`,onClick:()=>x(!1),children:[w.jsx(QM,{className:"w-4 h-4"}),w.jsx("span",{children:"CELLS"})]}),p&&w.jsxs(w.Fragment,{children:[w.jsxs(ks,{to:"/bookmarks",className:`flex items-center space-x-3 px-4 py-3 rounded-md text-sm font-mono transition-all ${i.pathname==="/bookmarks"?"bg-cyber-accent/20 text-cyber-accent border border-cyber-accent/30":"text-cyber-neutral hover:text-white hover:bg-cyber-muted/20"}`,onClick:()=>x(!1),children:[w.jsx(Fm,{className:"w-4 h-4"}),w.jsx("span",{children:"BOOKMARKS"})]}),w.jsxs(ks,{to:"/profile",className:`flex items-center space-x-3 px-4 py-3 rounded-md text-sm font-mono transition-all ${i.pathname==="/profile"?"bg-cyber-accent/20 text-cyber-accent border border-cyber-accent/30":"text-cyber-neutral hover:text-white hover:bg-cyber-muted/20"}`,onClick:()=>x(!1),children:[w.jsx(gE,{className:"w-4 h-4"}),w.jsx("span",{children:"PROFILE"})]})]})]}),w.jsx("div",{className:"px-4 py-3 border-t border-cyber-muted/20",children:w.jsxs("div",{className:"flex items-center space-x-2 text-xs text-cyber-neutral",children:[w.jsx(H9,{}),w.jsx("span",{children:s.statusMessage}),a.lastSync&&w.jsx("span",{className:"ml-auto",children:new Date(a.lastSync).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})})]})]})}),w.jsx(nxe,{open:y,onOpenChange:b,onComplete:()=>{b(!1),o({title:"Setup Complete",description:"Your wallet is ready to use!"})}})]})},hS=I.forwardRef(({className:t,type:e,...n},r)=>w.jsx("input",{type:e,className:Dt("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:r,...n}));hS.displayName="Input";const j8=I.forwardRef(({className:t,...e},n)=>w.jsx("textarea",{className:Dt("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:n,...e}));j8.displayName="Textarea";function Li({className:t,...e}){return w.jsx("div",{className:Dt("animate-pulse rounded-md bg-muted",t),...e})}const z8=({text:t,className:e})=>{const n=/(https?:\/\/[^\s]+)/g,r=t.split(n);return w.jsx("span",{className:e,children:r.map((s,i)=>n.test(s)?w.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"text-cyber-accent hover:text-cyber-accent/80 underline transition-colors",children:s},i):s)})};function zi(t){const e=Object.prototype.toString.call(t);return t instanceof Date||typeof t=="object"&&e==="[object Date]"?new t.constructor(+t):typeof t=="number"||e==="[object Number]"||typeof t=="string"||e==="[object String]"?new Date(t):new Date(NaN)}function xTt(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}const bI=43200,pse=1440;let ETt={};function CTt(){return ETt}function gse(t){const e=zi(t),n=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return n.setUTCFullYear(e.getFullYear()),+t-+n}function g6(t,e){const n=zi(t),r=zi(e),s=n.getTime()-r.getTime();return s<0?-1:s>0?1:s}function _Tt(t){return xTt(t,Date.now())}function STt(t,e){const n=zi(t),r=zi(e),s=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return s*12+i}function ATt(t){return e=>{const r=(t?Math[t]:Math.trunc)(e);return r===0?0:r}}function ITt(t,e){return+zi(t)-+zi(e)}function TTt(t){const e=zi(t);return e.setHours(23,59,59,999),e}function NTt(t){const e=zi(t),n=e.getMonth();return e.setFullYear(e.getFullYear(),n+1,0),e.setHours(23,59,59,999),e}function PTt(t){const e=zi(t);return+TTt(e)==+NTt(e)}function kTt(t,e){const n=zi(t),r=zi(e),s=g6(n,r),i=Math.abs(STt(n,r));let o;if(i<1)o=0;else{n.getMonth()===1&&n.getDate()>27&&n.setDate(30),n.setMonth(n.getMonth()-s*i);let a=g6(n,r)===-s;PTt(zi(t))&&i===1&&g6(t,r)===1&&(a=!1),o=s*(i-Number(a))}return o===0?0:o}function RTt(t,e,n){const r=ITt(t,e)/1e3;return ATt(n?.roundingMethod)(r)}const OTt={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},$Tt=(t,e,n)=>{let r;const s=OTt[t];return typeof s=="string"?r=s:e===1?r=s.one:r=s.other.replace("{{count}}",e.toString()),n?.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function q9(t){return(e={})=>{const n=e.width?String(e.width):t.defaultWidth;return t.formats[n]||t.formats[t.defaultWidth]}}const DTt={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},MTt={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},LTt={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},BTt={date:q9({formats:DTt,defaultWidth:"full"}),time:q9({formats:MTt,defaultWidth:"full"}),dateTime:q9({formats:LTt,defaultWidth:"full"})},UTt={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},FTt=(t,e,n,r)=>UTt[t];function P2(t){return(e,n)=>{const r=n?.context?String(n.context):"standalone";let s;if(r==="formatting"&&t.formattingValues){const o=t.defaultFormattingWidth||t.defaultWidth,a=n?.width?String(n.width):o;s=t.formattingValues[a]||t.formattingValues[o]}else{const o=t.defaultWidth,a=n?.width?String(n.width):t.defaultWidth;s=t.values[a]||t.values[o]}const i=t.argumentCallback?t.argumentCallback(e):e;return s[i]}}const jTt={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},zTt={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},WTt={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},VTt={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},HTt={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},qTt={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},KTt=(t,e)=>{const n=Number(t),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},GTt={ordinalNumber:KTt,era:P2({values:jTt,defaultWidth:"wide"}),quarter:P2({values:zTt,defaultWidth:"wide",argumentCallback:t=>t-1}),month:P2({values:WTt,defaultWidth:"wide"}),day:P2({values:VTt,defaultWidth:"wide"}),dayPeriod:P2({values:HTt,defaultWidth:"wide",formattingValues:qTt,defaultFormattingWidth:"wide"})};function k2(t){return(e,n={})=>{const r=n.width,s=r&&t.matchPatterns[r]||t.matchPatterns[t.defaultMatchWidth],i=e.match(s);if(!i)return null;const o=i[0],a=r&&t.parsePatterns[r]||t.parsePatterns[t.defaultParseWidth],c=Array.isArray(a)?YTt(a,d=>d.test(o)):ZTt(a,d=>d.test(o));let l;l=t.valueCallback?t.valueCallback(c):c,l=n.valueCallback?n.valueCallback(l):l;const u=e.slice(o.length);return{value:l,rest:u}}}function ZTt(t,e){for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return n}function YTt(t,e){for(let n=0;n{const r=e.match(t.matchPattern);if(!r)return null;const s=r[0],i=e.match(t.parsePattern);if(!i)return null;let o=t.valueCallback?t.valueCallback(i[0]):i[0];o=n.valueCallback?n.valueCallback(o):o;const a=e.slice(s.length);return{value:o,rest:a}}}const QTt=/^(\d+)(th|st|nd|rd)?/i,JTt=/\d+/i,eNt={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},tNt={any:[/^b/i,/^(a|c)/i]},nNt={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},rNt={any:[/1/i,/2/i,/3/i,/4/i]},sNt={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},iNt={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},oNt={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},aNt={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},cNt={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},lNt={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},uNt={ordinalNumber:XTt({matchPattern:QTt,parsePattern:JTt,valueCallback:t=>parseInt(t,10)}),era:k2({matchPatterns:eNt,defaultMatchWidth:"wide",parsePatterns:tNt,defaultParseWidth:"any"}),quarter:k2({matchPatterns:nNt,defaultMatchWidth:"wide",parsePatterns:rNt,defaultParseWidth:"any",valueCallback:t=>t+1}),month:k2({matchPatterns:sNt,defaultMatchWidth:"wide",parsePatterns:iNt,defaultParseWidth:"any"}),day:k2({matchPatterns:oNt,defaultMatchWidth:"wide",parsePatterns:aNt,defaultParseWidth:"any"}),dayPeriod:k2({matchPatterns:cNt,defaultMatchWidth:"any",parsePatterns:lNt,defaultParseWidth:"any"})},dNt={code:"en-US",formatDistance:$Tt,formatLong:BTt,formatRelative:FTt,localize:GTt,match:uNt,options:{weekStartsOn:0,firstWeekContainsDate:1}};function fNt(t,e,n){const r=CTt(),s=n?.locale??r.locale??dNt,i=2520,o=g6(t,e);if(isNaN(o))throw new RangeError("Invalid time value");const a=Object.assign({},n,{addSuffix:n?.addSuffix,comparison:o});let c,l;o>0?(c=zi(e),l=zi(t)):(c=zi(t),l=zi(e));const u=RTt(l,c),d=(gse(l)-gse(c))/1e3,f=Math.round((u-d)/60);let p;if(f<2)return n?.includeSeconds?u<5?s.formatDistance("lessThanXSeconds",5,a):u<10?s.formatDistance("lessThanXSeconds",10,a):u<20?s.formatDistance("lessThanXSeconds",20,a):u<40?s.formatDistance("halfAMinute",0,a):u<60?s.formatDistance("lessThanXMinutes",1,a):s.formatDistance("xMinutes",1,a):f===0?s.formatDistance("lessThanXMinutes",1,a):s.formatDistance("xMinutes",f,a);if(f<45)return s.formatDistance("xMinutes",f,a);if(f<90)return s.formatDistance("aboutXHours",1,a);if(fu+d.charCodeAt(0),0):0,l=()=>{a(!0)};if(o||!t||t.trim()===""){const u=c%60+140,d=c%8+8,f=c%30+5,p=(c%4+1)/10;return w.jsxs("div",{className:Dt("flex items-center justify-center overflow-hidden relative",n,r),title:e,"aria-label":e,style:{backgroundColor:"#0a1119",backgroundImage:` + linear-gradient(135deg, + rgba(0, 0, 0, 0.9) 25%, + rgba(${u/3}, ${u}, ${u}, 0.15) 25%, + rgba(${u/3}, ${u}, ${u}, 0.15) 50%, + rgba(0, 0, 0, 0.9) 50%, + rgba(0, 0, 0, 0.9) 75%, + rgba(${u/3}, ${u}, ${u}, 0.15) 75%) + `,backgroundSize:`${d}px ${d}px`,boxShadow:"inset 0 0 30px rgba(0, 255, 170, 0.2)"},...i,children:[w.jsx("div",{className:"absolute inset-0 opacity-20",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='${f/100}'/%3E%3C/svg%3E")`,mixBlendMode:"overlay"}}),w.jsx("div",{className:"absolute inset-0 pointer-events-none mix-blend-overlay",style:{background:`repeating-linear-gradient( + to bottom, + transparent, + transparent 1px, + rgba(0, 255, 170, ${p}) 1px, + rgba(0, 255, 170, ${p}) 2px + )`}}),w.jsx("div",{className:"absolute inset-0 opacity-10 bg-cyan-500 blur-xl"}),w.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[w.jsx("div",{className:"absolute w-full h-1 bg-gradient-to-r from-transparent via-cyan-400 to-transparent",style:{top:`${c%70+15}%`,opacity:.4,boxShadow:"0 0 8px rgba(0, 255, 255, 0.8)",transform:`skewY(${c%5-2.5}deg)`}}),w.jsxs("div",{className:"relative flex items-center justify-center",style:{textShadow:"0 0 5px rgba(0, 255, 255, 0.8), 0 0 10px rgba(0, 255, 255, 0.5)"},children:[w.jsx("div",{className:"absolute font-mono opacity-70",style:{color:`hsl(${u}, 100%, 70%)`,transform:`translate(${c%5-2.5}px, ${c%5-2.5}px)`},children:Array.from({length:3},(m,y)=>{const b="01[]{}><#$%&@!?;:+=*/\\|~^";return b[(c+y)%b.length]}).join("")}),w.jsx("div",{className:"relative font-bold text-2xl md:text-3xl cyberpunk-glow z-10",style:{color:`hsl(${u}, 100%, 80%)`},children:e.charAt(0).toUpperCase()}),w.jsx("div",{className:"absolute font-mono text-xs text-cyan-400 opacity-80 z-0",style:{bottom:"20%",right:"20%",transform:`rotate(${c%20-10}deg)`,mixBlendMode:"screen"},children:c.toString(16).substring(0,4)})]})]})]})}return w.jsx("img",{src:t,alt:e,className:n,onError:l,...i})}function W8({address:t,className:e="",showBadge:n=!0}){const{displayName:r,callSign:s,ensName:i,ordinalDetails:o}=H3(t),a=n&&(i||o||s);return w.jsxs("div",{className:`flex items-center gap-1.5 ${e}`,children:[w.jsx("span",{className:"text-xs text-muted-foreground",children:r}),a&&w.jsx(Ao,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-auto bg-green-900/20 border-green-500/30 text-green-400",children:s?w.jsxs(w.Fragment,{children:[w.jsx(xae,{className:"w-3 h-3 mr-1"}),"Call Sign"]}):i?w.jsxs(w.Fragment,{children:[w.jsx(_Ne,{className:"w-3 h-3 mr-1"}),"ENS"]}):w.jsxs(w.Fragment,{children:[w.jsx(zh,{className:"w-3 h-3 mr-1"}),"Ordinal"]})})]})}const hNt=()=>{const{cellId:t}=Cce(),e=bAt(t),n=xAt(t,{sortBy:"relevance"}),{createPost:r,votePost:s,moderatePost:i,unmoderatePost:o,moderateUser:a,refreshData:c,isCreatingPost:l,isVoting:u}=_p(),{canPost:d,canVote:f,canModerate:p}=Cp(),m=I8(),{currentUser:y,verificationStatus:b}=_i(),[v,x]=I.useState(""),[E,A]=I.useState("");if(!t||n.isLoading)return w.jsxs("div",{className:"container mx-auto px-4 py-8 max-w-4xl",children:[w.jsx("div",{className:"mb-6",children:w.jsxs(ks,{to:"/",className:"text-cyber-accent hover:underline flex items-center gap-1 text-sm",children:[w.jsx(DI,{className:"w-4 h-4"})," Back to Cells"]})}),w.jsx(Li,{className:"h-8 w-32 mb-6 bg-cyber-muted"}),w.jsx(Li,{className:"h-6 w-64 mb-6 bg-cyber-muted"}),w.jsx("div",{className:"space-y-4",children:[...Array(3)].map((M,j)=>w.jsxs("div",{className:"border border-cyber-muted rounded-sm p-4",children:[w.jsxs("div",{className:"mb-2",children:[w.jsx(Li,{className:"h-6 w-full mb-2 bg-cyber-muted"}),w.jsx(Li,{className:"h-6 w-3/4 mb-2 bg-cyber-muted"})]}),w.jsx(Li,{className:"h-4 w-32 bg-cyber-muted"})]},j))})]});if(!e)return w.jsxs("div",{className:"container mx-auto px-4 py-8 max-w-4xl",children:[w.jsx("div",{className:"mb-6",children:w.jsxs(ks,{to:"/",className:"text-cyber-accent hover:underline flex items-center gap-1 text-sm",children:[w.jsx(DI,{className:"w-4 h-4"})," Back to Cells"]})}),w.jsxs("div",{className:"p-8 text-center",children:[w.jsx("h1",{className:"text-2xl font-bold mb-4",children:"Cell Not Found"}),w.jsx("p",{className:"text-cyber-neutral mb-6",children:"The cell you're looking for doesn't exist."}),w.jsx(fn,{asChild:!0,children:w.jsx(ks,{to:"/",children:"Return to Cells"})})]})]});const _=async M=>{if(M.preventDefault(),!E.trim())return;await r(t,v,E)&&(x(""),A(""))},k=async(M,j)=>{await s(M,j)},B=M=>m.getPostVoteType(M),W=n.posts,S=async M=>{const j=window.prompt("Enter a reason for moderation (optional):")||void 0;e&&await i(e.id,M,j)},$=async M=>{const j=window.prompt("Optional note for unmoderation?")||void 0;e&&await o(e.id,M,j)},R=async M=>{const j=window.prompt("Reason for moderating this user? (optional)")||void 0;e&&await a(e.id,M,j)};return w.jsxs("div",{className:"page-main",children:[w.jsx("div",{className:"content-spacing",children:w.jsxs(ks,{to:"/",className:"text-cyber-accent hover:underline flex items-center gap-1 text-sm",children:[w.jsx(DI,{className:"w-4 h-4"})," Back to Cells"]})}),w.jsxs("div",{className:"flex gap-4 items-start content-spacing",children:[w.jsx(DH,{src:e.icon,alt:e.name,className:"w-12 h-12 object-cover rounded-sm border border-cyber-muted",generateUniqueFallback:!0}),w.jsxs("div",{className:"flex-1",children:[w.jsxs("div",{className:"flex items-center justify-between",children:[w.jsx("h1",{className:"page-title text-glow",children:e.name}),w.jsx(fn,{variant:"outline",size:"icon",onClick:c,disabled:n.isLoading,title:"Refresh data",children:w.jsx(HF,{className:`w-4 h-4 ${n.isLoading?"animate-spin":""}`})})]}),w.jsx("p",{className:"page-subtitle",children:e.description})]})]}),d&&w.jsx("div",{className:"section-spacing",children:w.jsxs("form",{onSubmit:_,children:[w.jsxs("h2",{className:"text-sm font-bold mb-2 flex items-center gap-1",children:[w.jsx(s0,{className:"w-4 h-4"}),"New Thread"]}),w.jsxs("div",{className:"mb-3",children:[w.jsx(hS,{placeholder:"Thread title",value:v,onChange:M=>x(M.target.value),className:"mb-3 bg-cyber-muted/50 border-cyber-muted",disabled:l}),w.jsx(j8,{placeholder:"What's on your mind?",value:E,onChange:M=>A(M.target.value),className:"bg-cyber-muted/50 border-cyber-muted resize-none",disabled:l})]}),w.jsx("div",{className:"flex justify-end",children:w.jsx(fn,{type:"submit",disabled:l||!E.trim()||!v.trim(),children:l?"Posting...":"Post Thread"})})]})}),!d&&b===Ct.WALLET_CONNECTED&&w.jsxs("div",{className:"section-spacing content-card-sm",children:[w.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[w.jsx(K6,{className:"w-4 h-4 text-cyber-neutral"}),w.jsx("h3",{className:"font-medium",children:"Read-Only Mode"})]}),w.jsx("p",{className:"text-sm text-cyber-neutral mb-2",children:"Your wallet does not contain any Ordinal Operators. You can browse threads but cannot post or interact."}),w.jsx(Ao,{variant:"outline",className:"text-xs",children:"No Ordinals Found"})]}),!d&&!y&&w.jsxs("div",{className:"section-spacing content-card-sm text-center",children:[w.jsx("p",{className:"text-sm mb-3",children:"Connect wallet and verify Ordinal ownership to post"}),w.jsx(fn,{asChild:!0,size:"sm",children:w.jsx(ks,{to:"/",children:"Connect Wallet"})})]}),w.jsx("div",{className:"space-y-4",children:W.length===0?w.jsxs("div",{className:"empty-state",children:[w.jsx(MI,{className:"empty-state-icon text-cyber-neutral opacity-50"}),w.jsx("h2",{className:"empty-state-title",children:"No Threads Yet"}),w.jsx("p",{className:"empty-state-description",children:d?"Be the first to post in this cell!":"Connect your wallet and verify Ordinal ownership to start a thread."})]}):W.map(M=>w.jsx("div",{className:"thread-card",children:w.jsxs("div",{className:"flex gap-4",children:[w.jsxs("div",{className:"flex flex-col items-center",children:[w.jsx("button",{className:`p-1 rounded-sm hover:bg-cyber-muted/50 ${B(M.id)==="upvote"?"text-cyber-accent":""}`,onClick:()=>k(M.id,!0),disabled:!f||u,title:f?"Upvote":"Connect wallet and verify to vote",children:w.jsx(mP,{className:"w-4 h-4"})}),w.jsx("span",{className:"text-sm py-1",children:M.upvotes.length-M.downvotes.length}),w.jsx("button",{className:`p-1 rounded-sm hover:bg-cyber-muted/50 ${B(M.id)==="downvote"?"text-cyber-accent":""}`,onClick:()=>k(M.id,!1),disabled:!f||u,title:f?"Downvote":"Connect wallet and verify to vote",children:w.jsx(gP,{className:"w-4 h-4"})})]}),w.jsxs("div",{className:"flex-1",children:[w.jsxs(ks,{to:`/post/${M.id}`,className:"block",children:[w.jsx("h2",{className:"text-lg font-bold hover:text-cyber-accent",children:M.title}),w.jsx("p",{className:"line-clamp-2 text-sm mb-3",children:w.jsx(z8,{text:M.content})}),w.jsxs("div",{className:"flex items-center gap-4 text-xs text-cyber-neutral",children:[w.jsx("span",{children:G3(M.timestamp,{addSuffix:!0})}),w.jsx("span",{children:"by "}),w.jsx(W8,{address:M.author,className:"text-xs",showBadge:!1})]})]}),p(e.id)&&!M.moderated&&w.jsxs(jm,{children:[w.jsx(zm,{asChild:!0,children:w.jsx(fn,{size:"icon",variant:"ghost",className:"h-6 w-6 text-cyber-neutral hover:text-orange-500",onClick:()=>S(M.id),children:w.jsx(zh,{className:"h-3 w-3"})})}),w.jsx(Hg,{children:w.jsx("p",{children:"Moderate post"})})]}),p(e.id)&&M.author!==e.author&&w.jsxs(jm,{children:[w.jsx(zm,{asChild:!0,children:w.jsx(fn,{size:"icon",variant:"ghost",className:"h-6 w-6 text-cyber-neutral hover:text-red-500",onClick:()=>R(M.author),children:w.jsx(Cae,{className:"h-3 w-3"})})}),w.jsx(Hg,{children:w.jsx("p",{children:"Moderate user"})})]}),p(e.id)&&M.moderated&&w.jsxs(jm,{children:[w.jsx(zm,{asChild:!0,children:w.jsx(fn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-cyber-neutral hover:text-green-500",onClick:()=>$(M.id),children:"Unmoderate"})}),w.jsx(Hg,{children:w.jsx("p",{children:"Unmoderate post"})})]})]})]})},M.id))})]})},pNt=()=>w.jsxs("div",{className:"page-container",children:[w.jsx(Kd,{}),w.jsx("main",{className:"page-content",children:w.jsx(hNt,{})}),w.jsx("footer",{className:"page-footer",children:w.jsx("p",{children:"OpChan - A decentralized forum built on Waku & Bitcoin Ordinals"})})]}),Yu=I.forwardRef(({className:t,...e},n)=>w.jsx("div",{ref:n,className:Dt("rounded-lg border bg-card text-card-foreground shadow-sm",t),...e}));Yu.displayName="Card";const sf=I.forwardRef(({className:t,...e},n)=>w.jsx("div",{ref:n,className:Dt("flex flex-col space-y-1.5 p-6",t),...e}));sf.displayName="CardHeader";const Dh=I.forwardRef(({className:t,...e},n)=>w.jsx("h3",{ref:n,className:Dt("text-2xl font-semibold leading-none tracking-tight",t),...e}));Dh.displayName="CardTitle";const gNt=I.forwardRef(({className:t,...e},n)=>w.jsx("p",{ref:n,className:Dt("text-sm text-muted-foreground",t),...e}));gNt.displayName="CardDescription";const Xu=I.forwardRef(({className:t,...e},n)=>w.jsx("div",{ref:n,className:Dt("p-6 pt-0",t),...e}));Xu.displayName="CardContent";const mNt=I.forwardRef(({className:t,...e},n)=>w.jsx("div",{ref:n,className:Dt("flex items-center p-6 pt-0",t),...e}));mNt.displayName="CardFooter";var yNt="Separator",mse="horizontal",wNt=["horizontal","vertical"],rxe=I.forwardRef((t,e)=>{const{decorative:n,orientation:r=mse,...s}=t,i=bNt(r)?r:mse,a=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return w.jsx(gn.div,{"data-orientation":i,...a,...s,ref:e})});rxe.displayName=yNt;function bNt(t){return wNt.includes(t)}var sxe=rxe;const ixe=I.forwardRef(({className:t,orientation:e="horizontal",decorative:n=!0,...r},s)=>w.jsx(sxe,{ref:s,decorative:n,orientation:e,className:Dt("shrink-0 bg-border",e==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",t),...r}));ixe.displayName=sxe.displayName;function MH({score:t,details:e,type:n,className:r,showTooltip:s=!1}){const[i,o]=I.useState(!1),a=d=>d>=15?"bg-green-500 hover:bg-green-600":d>=10?"bg-blue-500 hover:bg-blue-600":d>=5?"bg-yellow-500 hover:bg-yellow-600":"bg-gray-500 hover:bg-gray-600",c=d=>d.toFixed(1),l=()=>e?w.jsxs("div",{className:"text-xs space-y-1",children:[w.jsxs("div",{className:"font-semibold",children:["Relevance Score: ",c(t)]}),w.jsxs("div",{children:["Base: ",c(e.baseScore)]}),w.jsxs("div",{children:["Engagement: +",c(e.engagementScore)]}),e.authorVerificationBonus>0&&w.jsxs("div",{children:["Author Bonus: +",c(e.authorVerificationBonus)]}),e.verifiedUpvoteBonus>0&&w.jsxs("div",{children:["Verified Upvotes: +",c(e.verifiedUpvoteBonus)]}),e.verifiedCommenterBonus>0&&w.jsxs("div",{children:["Verified Commenters: +",c(e.verifiedCommenterBonus)]}),w.jsxs("div",{children:["Time Decay: ×",e.timeDecayMultiplier.toFixed(2)]}),e.isModerated&&w.jsxs("div",{children:["Moderation: ×",e.moderationPenalty.toFixed(1)]})]}):`Relevance Score: ${c(t)}`,u=w.jsxs(Ao,{variant:"secondary",className:`cursor-pointer ${a(t)} text-white ${r}`,title:s?void 0:"Click to see relevance score details",children:[w.jsx(lC,{className:"w-3 h-3 mr-1"}),c(t)]});return w.jsx(w.Fragment,{children:w.jsxs($H,{open:i,onOpenChange:o,children:[s?w.jsx(ace,{children:w.jsxs(jm,{children:[w.jsx(zm,{asChild:!0,children:w.jsx(DU,{asChild:!0,children:u})}),w.jsx(Hg,{side:"top",className:"max-w-xs",children:l()})]})}):w.jsx(DU,{asChild:!0,children:u}),w.jsxs(B8,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[w.jsx(U8,{children:w.jsxs(F8,{className:"flex items-center gap-2",children:[w.jsx(lC,{className:"w-5 h-5"}),"Relevance Score Details"]})}),w.jsxs("div",{className:"space-y-4",children:[w.jsxs(Yu,{children:[w.jsx(sf,{children:w.jsxs(Dh,{className:"text-lg",children:["Final Score: ",c(t)]})}),w.jsx(Xu,{children:w.jsxs("div",{className:"text-sm text-muted-foreground",children:[n.charAt(0).toUpperCase()+n.slice(1)," relevance score"]})})]}),e&&w.jsxs(w.Fragment,{children:[w.jsxs(Yu,{children:[w.jsx(sf,{children:w.jsx(Dh,{className:"text-base",children:"Score Breakdown"})}),w.jsxs(Xu,{className:"space-y-3",children:[w.jsxs("div",{className:"flex justify-between items-center",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx("div",{className:"w-4 h-4 bg-blue-500 rounded"}),w.jsx("span",{children:"Base Score"})]}),w.jsx("span",{className:"font-mono",children:c(e.baseScore)})]}),w.jsxs("div",{className:"flex justify-between items-center",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(DNe,{className:"w-4 h-4 text-green-500"}),w.jsxs("span",{children:["Engagement (",e.upvotes," upvotes,"," ",e.comments," comments)"]})]}),w.jsxs("span",{className:"font-mono",children:["+",c(e.engagementScore)]})]}),e.authorVerificationBonus>0&&w.jsxs("div",{className:"flex justify-between items-center",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(FZ,{className:"w-4 h-4 text-purple-500"}),w.jsx("span",{children:"Author Verification Bonus"})]}),w.jsxs("span",{className:"font-mono",children:["+",c(e.authorVerificationBonus)]})]}),e.verifiedUpvoteBonus>0&&w.jsxs("div",{className:"flex justify-between items-center",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(zh,{className:"w-4 h-4 text-indigo-500"}),w.jsxs("span",{children:["Verified Upvotes (",e.verifiedUpvotes,")"]})]}),w.jsxs("span",{className:"font-mono",children:["+",c(e.verifiedUpvoteBonus)]})]}),e.verifiedCommenterBonus>0&&w.jsxs("div",{className:"flex justify-between items-center",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(s0,{className:"w-4 h-4 text-teal-500"}),w.jsxs("span",{children:["Verified Commenters (",e.verifiedCommenters,")"]})]}),w.jsxs("span",{className:"font-mono",children:["+",c(e.verifiedCommenterBonus)]})]}),w.jsx(ixe,{}),w.jsxs("div",{className:"flex justify-between items-center",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(W1,{className:"w-4 h-4 text-orange-500"}),w.jsxs("span",{children:["Time Decay (",e.daysOld.toFixed(1)," days old)"]})]}),w.jsxs("span",{className:"font-mono",children:["×",e.timeDecayMultiplier.toFixed(3)]})]}),e.isModerated&&w.jsxs("div",{className:"flex justify-between items-center",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(zh,{className:"w-4 h-4 text-red-500"}),w.jsx("span",{children:"Moderation Penalty"})]}),w.jsxs("span",{className:"font-mono",children:["×",e.moderationPenalty.toFixed(1)]})]})]})]}),w.jsxs(Yu,{children:[w.jsx(sf,{children:w.jsx(Dh,{className:"text-base",children:"User Status"})}),w.jsx(Xu,{children:w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(FZ,{className:`w-4 h-4 ${e.isVerified?"text-green-500":"text-gray-400"}`}),w.jsx("span",{className:e.isVerified?"text-green-600":"text-gray-500",children:e.isVerified?"Verified User":"Unverified User"})]})})]})]})]})]})]})})}function LH({isBookmarked:t,loading:e=!1,onClick:n,size:r="sm",variant:s="ghost",className:i,showText:o=!1}){const a={sm:"h-8 w-10",lg:"h-10 whitespace-nowrap px-4"},c={sm:14,lg:18};return w.jsxs(fn,{variant:s,size:r,onClick:n,disabled:e,className:Dt(a[r],"transition-colors duration-200",t?"text-cyber-accent hover:text-cyber-light":"text-cyber-neutral hover:text-cyber-light",i),title:t?"Remove bookmark":"Add bookmark",children:[e?w.jsx("div",{className:"animate-spin rounded-full h-3 w-3 border-b-2 border-current"}):t?w.jsx(wNe,{size:c[r],className:"fill-current"}):w.jsx(Fm,{size:c[r]}),o&&w.jsx("span",{className:"ml-2 text-xs",children:t?"Bookmarked":"Bookmark"})]})}function V8(t){const[e,n]=I.useState(t?ct.isPending(t):!1);return I.useEffect(()=>t?(n(ct.isPending(t)),ct.onPendingChange(()=>{n(ct.isPending(t))})):void 0,[t]),{isPending:e}}function BH(t){const{currentUser:e}=Qc(),[n,r]=I.useState(!1);return I.useEffect(()=>{const s=()=>{if(!t||!e?.address)return r(!1);const o=Object.values(ct.cache.votes).some(a=>a.targetId===t&&a.author===e.address&&ct.isPending(a.id));r(o)};return s(),ct.onPendingChange(s)},[t,e?.address]),{isPending:n}}const vNt=({id:t})=>{const{isPending:e}=V8(t);return e?w.jsxs(w.Fragment,{children:[w.jsx("span",{children:"•"}),w.jsx("span",{className:"px-2 py-0.5 rounded-sm bg-yellow-500/20 text-yellow-400 border border-yellow-500/30",children:"syncing…"})]}):null},xNt=({comment:t,postId:e,cellId:n,canModerate:r,onModerateComment:s,onUnmoderateComment:i,onModerateUser:o})=>{const{voteComment:a,isVoting:c}=_p(),{canVote:l}=Cp(),u=I8(),{isBookmarked:d,loading:f,toggleBookmark:p}=wAt(t,e),m=BH(t.id),y=async x=>{await a(t.id,x)},b=async()=>{await p()},v=()=>u.getCommentVoteType(t.id);return w.jsx("div",{className:"border border-muted rounded-sm p-4 bg-card",children:w.jsxs("div",{className:"flex gap-4",children:[w.jsxs("div",{className:"flex flex-col items-center",children:[w.jsx("button",{className:`p-1 rounded-sm hover:bg-cyber-muted/50 ${v()==="upvote"?"text-cyber-accent":""}`,onClick:()=>y(!0),disabled:!l||c,title:l?"Upvote comment":"Connect wallet and verify to vote",children:w.jsx(mP,{className:"w-3 h-3"})}),w.jsx("span",{className:"text-sm font-bold",children:t.voteScore}),w.jsx("button",{className:`p-1 rounded-sm hover:bg-cyber-muted/50 ${v()==="downvote"?"text-cyber-accent":""}`,onClick:()=>y(!1),disabled:!l||c,title:l?"Downvote comment":"Connect wallet and verify to vote",children:w.jsx(gP,{className:"w-3 h-3"})}),m.isPending&&w.jsx("span",{className:"mt-1 text-[10px] text-yellow-500",children:"syncing…"})]}),w.jsxs("div",{className:"flex-1",children:[w.jsxs("div",{className:"flex items-center justify-between mb-2",children:[w.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[w.jsx(W8,{address:t.author,className:"text-xs",showBadge:!1}),w.jsx("span",{children:"•"}),w.jsx(W1,{className:"w-3 h-3"}),w.jsx("span",{children:G3(new Date(t.timestamp),{addSuffix:!0})}),w.jsx(vNt,{id:t.id})]}),w.jsx(LH,{isBookmarked:d,loading:f,onClick:b,size:"sm",variant:"ghost"})]}),w.jsx("p",{className:"text-sm break-words mb-2",children:w.jsx(z8,{text:t.content})}),w.jsxs("div",{className:"flex items-center gap-2",children:[r&&!t.moderated&&w.jsxs(jm,{children:[w.jsx(zm,{asChild:!0,children:w.jsx(fn,{size:"icon",variant:"ghost",className:"h-6 w-6 text-cyber-neutral hover:text-orange-500",onClick:()=>s(t.id),children:w.jsx(zh,{className:"h-3 w-3"})})}),w.jsx(Hg,{children:w.jsx("p",{children:"Moderate comment"})})]}),r&&t.moderated&&w.jsxs(jm,{children:[w.jsx(zm,{asChild:!0,children:w.jsx(fn,{size:"sm",variant:"ghost",className:"h-6 px-2 text-cyber-neutral hover:text-green-500",onClick:()=>i?.(t.id),children:"Unmoderate"})}),w.jsx(Hg,{children:w.jsx("p",{children:"Unmoderate comment"})})]}),n&&r&&w.jsxs(jm,{children:[w.jsx(zm,{asChild:!0,children:w.jsx(fn,{size:"icon",variant:"ghost",className:"h-6 w-6 text-cyber-neutral hover:text-red-500",onClick:()=>o(t.author),children:w.jsx(Cae,{className:"h-3 w-3"})})}),w.jsx(Hg,{children:w.jsx("p",{children:"Moderate user"})})]})]})]})]})})},ENt=()=>{const{postId:t}=Cce(),e=NP(),n=vAt(t),r=EAt(t),{createComment:s,votePost:i,moderateComment:o,unmoderateComment:a,moderateUser:c,isCreatingComment:l,isVoting:u}=_p(),{canVote:d,canComment:f,canModerate:p}=Cp(),m=I8(),{isBookmarked:y,loading:b,toggleBookmark:v}=Ibe(n,n?.cellId),x=V8(n?.id),E=BH(n?.id),[A,_]=I.useState("");if(!t)return w.jsx("div",{children:"Invalid post ID"});if(r.isLoading)return w.jsxs("div",{className:"container mx-auto px-4 py-16 text-center",children:[w.jsx(Xd,{className:"w-8 h-8 mx-auto mb-4 animate-spin text-primary"}),w.jsx("p",{className:"text-lg font-medium text-muted-foreground",children:"Loading Post..."})]});if(!n)return w.jsxs("div",{className:"container mx-auto px-4 py-6 text-center",children:[w.jsx("h2",{className:"text-xl font-bold mb-4",children:"Post not found"}),w.jsx("p",{className:"mb-4",children:"The post you're looking for doesn't exist or has been removed."}),w.jsx(fn,{asChild:!0,children:w.jsx(ks,{to:"/",children:"Go back home"})})]});const{cell:k}=n,B=r.comments,W=async U=>{if(U.preventDefault(),!A.trim())return;await s(t,A)&&_("")},S=async U=>{await i(n.id,U)},$=async U=>{U&&(U.preventDefault(),U.stopPropagation()),await v()},R=m.getPostVoteType(n.id),M=R==="upvote",j=R==="downvote",z=async U=>{const L=window.prompt("Enter a reason for moderation (optional):")||void 0;k&&await o(k.id,U,L)},N=async U=>{const L=window.prompt("Optional note for unmoderation?")||void 0;k&&await a(k.id,U,L)},T=async U=>{const L=window.prompt("Reason for moderating this user? (optional)")||void 0;k&&await c(k.id,U,L)};return w.jsxs("div",{className:"container mx-auto px-4 py-6",children:[w.jsxs("div",{className:"mb-6",children:[w.jsxs(fn,{onClick:()=>e(`/cell/${n.cellId}`),variant:"ghost",size:"sm",className:"mb-4",children:[w.jsx(DI,{className:"w-4 h-4 mr-1"}),"Back to /",k?.name||"cell","/"]}),w.jsx("div",{className:"border border-muted rounded-sm p-3 mb-6",children:w.jsxs("div",{className:"flex gap-4",children:[w.jsxs("div",{className:"flex flex-col items-center",children:[w.jsx("button",{className:`p-1 rounded-sm hover:bg-muted/50 ${M?"text-primary":""}`,onClick:()=>S(!0),disabled:!d||u,title:d?"Upvote post":"Connect wallet and verify to vote",children:w.jsx(mP,{className:"w-4 h-4"})}),w.jsx("span",{className:"text-sm font-bold",children:n.voteScore}),w.jsx("button",{className:`p-1 rounded-sm hover:bg-muted/50 ${j?"text-primary":""}`,onClick:()=>S(!1),disabled:!d||u,title:d?"Downvote post":"Connect wallet and verify to vote",children:w.jsx(gP,{className:"w-4 h-4"})}),E.isPending&&w.jsx("span",{className:"mt-1 text-[10px] text-yellow-500",children:"syncing…"})]}),w.jsxs("div",{className:"flex-1",children:[w.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-2",children:[w.jsxs("span",{className:"font-medium text-primary",children:["r/",k?.name||"unknown"]}),w.jsx("span",{children:"•"}),w.jsx("span",{children:"Posted by u/"}),w.jsx(W8,{address:n.author,className:"text-sm",showBadge:!1}),w.jsx("span",{children:"•"}),w.jsx(W1,{className:"w-3 h-3"}),w.jsx("span",{children:G3(new Date(n.timestamp),{addSuffix:!0})}),n.relevanceScore!==void 0&&w.jsxs(w.Fragment,{children:[w.jsx("span",{children:"•"}),w.jsx(MH,{score:n.relevanceScore,details:n.relevanceDetails,type:"post",className:"text-sm",showTooltip:!0})]}),x.isPending&&w.jsxs(w.Fragment,{children:[w.jsx("span",{children:"•"}),w.jsx("span",{className:"px-2 py-0.5 rounded-sm bg-yellow-500/20 text-yellow-400 border border-yellow-500/30",children:"syncing…"})]})]}),w.jsxs("div",{className:"flex items-start justify-between mb-3",children:[w.jsx("h1",{className:"text-2xl font-bold flex-1",children:n.title}),w.jsx(LH,{isBookmarked:y,loading:b,onClick:$,size:"lg",variant:"ghost",showText:!0})]}),w.jsx("p",{className:"text-sm whitespace-pre-wrap break-words",children:w.jsx(z8,{text:n.content})})]})]})})]}),f&&w.jsx("div",{className:"mb-8",children:w.jsxs("form",{onSubmit:W,children:[w.jsxs("h2",{className:"text-sm font-bold mb-2 flex items-center gap-1",children:[w.jsx(MI,{className:"w-4 h-4"}),"Add a comment"]}),w.jsx(j8,{placeholder:"What are your thoughts?",value:A,onChange:U=>_(U.target.value),className:"mb-3 resize-none",disabled:l}),w.jsx("div",{className:"flex justify-end",children:w.jsx(fn,{type:"submit",disabled:!f||l,className:"bg-cyber-accent hover:bg-cyber-accent/80",children:l?w.jsxs(w.Fragment,{children:[w.jsx(Xd,{className:"w-4 h-4 mr-2 animate-spin"}),"Posting..."]}):w.jsxs(w.Fragment,{children:[w.jsx(ONe,{className:"w-4 h-4 mr-2"}),"Post Comment"]})})})]})}),!f&&w.jsxs("div",{className:"mb-6 p-4 border border-cyber-muted rounded-sm bg-cyber-muted/20 text-center",children:[w.jsx("p",{className:"text-sm mb-3",children:"Connect wallet and verify Ordinal ownership to comment"}),w.jsx(fn,{asChild:!0,size:"sm",children:w.jsx(ks,{to:"/",children:"Connect Wallet"})})]}),w.jsxs("div",{className:"space-y-4",children:[w.jsxs("h2",{className:"text-lg font-bold flex items-center gap-2",children:[w.jsx(MI,{className:"w-5 h-5"}),"Comments (",B.length,")"]}),B.length===0?w.jsxs("div",{className:"text-center py-8",children:[w.jsx(MI,{className:"w-12 h-12 mx-auto mb-4 text-muted-foreground opacity-50"}),w.jsx("h3",{className:"text-lg font-bold mb-2",children:"No comments yet"}),w.jsx("p",{className:"text-muted-foreground",children:f?"Be the first to share your thoughts!":"Connect your wallet to join the conversation."})]}):B.map(U=>w.jsx(xNt,{comment:U,postId:t,cellId:k?.id,canModerate:p(k?.id||""),onModerateComment:z,onUnmoderateComment:N,onModerateUser:T},U.id))]})]})},CNt=()=>w.jsxs("div",{className:"min-h-screen flex flex-col bg-cyber-dark text-white",children:[w.jsx(Kd,{}),w.jsx("main",{className:"flex-1 pt-16",children:w.jsx(ENt,{})}),w.jsx("footer",{className:"border-t border-cyber-muted py-4 text-center text-xs text-cyber-neutral",children:w.jsx("p",{children:"OpChan - A decentralized forum built on Waku & Bitcoin Ordinals"})})]}),_Nt=()=>{const t=Z1();return I.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",t.pathname)},[t.pathname]),w.jsxs("div",{className:"min-h-screen flex flex-col bg-cyber-dark text-white",children:[w.jsx("main",{className:"flex-1 flex items-center justify-center",children:w.jsxs("div",{className:"text-center p-8",children:[w.jsx("h1",{className:"text-4xl font-bold mb-4 text-cyber-accent",children:"404"}),w.jsx("p",{className:"text-xl text-cyber-neutral mb-8",children:"Oops! Page not found"}),w.jsx(ks,{to:"/",className:"text-cyber-accent hover:text-cyber-accent/80 hover:underline",children:"Return to Home"})]})}),w.jsx("footer",{className:"border-t border-cyber-muted py-4 text-center text-xs text-cyber-neutral",children:w.jsx("p",{children:"OpChan - A decentralized forum built on Waku & Bitcoin Ordinals"})})]})};function yse(t,[e,n]){return Math.min(n,Math.max(e,t))}function oxe(t){const e=I.useRef({value:t,previous:t});return I.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var SNt=[" ","Enter","ArrowUp","ArrowDown"],ANt=[" ","Enter"],Z3="Select",[H8,q8,INt]=dP(Z3),[Sx,QDt]=pp(Z3,[INt,K1]),K8=K1(),[TNt,B0]=Sx(Z3),[NNt,PNt]=Sx(Z3),axe=t=>{const{__scopeSelect:e,children:n,open:r,defaultOpen:s,onOpenChange:i,value:o,defaultValue:a,onValueChange:c,dir:l,name:u,autoComplete:d,disabled:f,required:p,form:m}=t,y=K8(e),[b,v]=I.useState(null),[x,E]=I.useState(null),[A,_]=I.useState(!1),k=T8(l),[B=!1,W]=jh({prop:r,defaultProp:s,onChange:i}),[S,$]=jh({prop:o,defaultProp:a,onChange:c}),R=I.useRef(null),M=b?m||!!b.closest("form"):!0,[j,z]=I.useState(new Set),N=Array.from(j).map(T=>T.props.value).join(";");return w.jsx(tj,{...y,children:w.jsxs(TNt,{required:p,scope:e,trigger:b,onTriggerChange:v,valueNode:x,onValueNodeChange:E,valueNodeHasChildren:A,onValueNodeHasChildrenChange:_,contentId:Wu(),value:S,onValueChange:$,open:B,onOpenChange:W,dir:k,triggerPointerDownPosRef:R,disabled:f,children:[w.jsx(H8.Provider,{scope:e,children:w.jsx(NNt,{scope:t.__scopeSelect,onNativeOptionAdd:I.useCallback(T=>{z(U=>new Set(U).add(T))},[]),onNativeOptionRemove:I.useCallback(T=>{z(U=>{const L=new Set(U);return L.delete(T),L})},[]),children:n})}),M?w.jsxs(Rxe,{"aria-hidden":!0,required:p,tabIndex:-1,name:u,autoComplete:d,value:S,onChange:T=>$(T.target.value),disabled:f,form:m,children:[S===void 0?w.jsx("option",{value:""}):null,Array.from(j)]},N):null]})})};axe.displayName=Z3;var cxe="SelectTrigger",lxe=I.forwardRef((t,e)=>{const{__scopeSelect:n,disabled:r=!1,...s}=t,i=K8(n),o=B0(cxe,n),a=o.disabled||r,c=ir(e,o.onTriggerChange),l=q8(n),u=I.useRef("touch"),[d,f,p]=Oxe(y=>{const b=l().filter(E=>!E.disabled),v=b.find(E=>E.value===o.value),x=$xe(b,y,v);x!==void 0&&o.onValueChange(x.value)}),m=y=>{a||(o.onOpenChange(!0),p()),y&&(o.triggerPointerDownPosRef.current={x:Math.round(y.pageX),y:Math.round(y.pageY)})};return w.jsx(nj,{asChild:!0,...i,children:w.jsx(gn.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":kxe(o.value)?"":void 0,...s,ref:c,onClick:vt(s.onClick,y=>{y.currentTarget.focus(),u.current!=="mouse"&&m(y)}),onPointerDown:vt(s.onPointerDown,y=>{u.current=y.pointerType;const b=y.target;b.hasPointerCapture(y.pointerId)&&b.releasePointerCapture(y.pointerId),y.button===0&&y.ctrlKey===!1&&y.pointerType==="mouse"&&(m(y),y.preventDefault())}),onKeyDown:vt(s.onKeyDown,y=>{const b=d.current!=="";!(y.ctrlKey||y.altKey||y.metaKey)&&y.key.length===1&&f(y.key),!(b&&y.key===" ")&&SNt.includes(y.key)&&(m(),y.preventDefault())})})})});lxe.displayName=cxe;var uxe="SelectValue",dxe=I.forwardRef((t,e)=>{const{__scopeSelect:n,className:r,style:s,children:i,placeholder:o="",...a}=t,c=B0(uxe,n),{onValueNodeHasChildrenChange:l}=c,u=i!==void 0,d=ir(e,c.onValueNodeChange);return No(()=>{l(u)},[l,u]),w.jsx(gn.span,{...a,ref:d,style:{pointerEvents:"none"},children:kxe(c.value)?w.jsx(w.Fragment,{children:o}):i})});dxe.displayName=uxe;var kNt="SelectIcon",fxe=I.forwardRef((t,e)=>{const{__scopeSelect:n,children:r,...s}=t;return w.jsx(gn.span,{"aria-hidden":!0,...s,ref:e,children:r||"▼"})});fxe.displayName=kNt;var RNt="SelectPortal",hxe=t=>w.jsx(OS,{asChild:!0,...t});hxe.displayName=RNt;var qy="SelectContent",pxe=I.forwardRef((t,e)=>{const n=B0(qy,t.__scopeSelect),[r,s]=I.useState();if(No(()=>{s(new DocumentFragment)},[]),!n.open){const i=r;return i?Qy.createPortal(w.jsx(gxe,{scope:t.__scopeSelect,children:w.jsx(H8.Slot,{scope:t.__scopeSelect,children:w.jsx("div",{children:t.children})})}),i):null}return w.jsx(mxe,{...t,ref:e})});pxe.displayName=qy;var Au=10,[gxe,U0]=Sx(qy),ONt="SelectContentImpl",mxe=I.forwardRef((t,e)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:i,onPointerDownOutside:o,side:a,sideOffset:c,align:l,alignOffset:u,arrowPadding:d,collisionBoundary:f,collisionPadding:p,sticky:m,hideWhenDetached:y,avoidCollisions:b,...v}=t,x=B0(qy,n),[E,A]=I.useState(null),[_,k]=I.useState(null),B=ir(e,oe=>A(oe)),[W,S]=I.useState(null),[$,R]=I.useState(null),M=q8(n),[j,z]=I.useState(!1),N=I.useRef(!1);I.useEffect(()=>{if(E)return aH(E)},[E]),oH();const T=I.useCallback(oe=>{const[Oe,...je]=M().map(Ae=>Ae.ref.current),[V]=je.slice(-1),we=document.activeElement;for(const Ae of oe)if(Ae===we||(Ae?.scrollIntoView({block:"nearest"}),Ae===Oe&&_&&(_.scrollTop=0),Ae===V&&_&&(_.scrollTop=_.scrollHeight),Ae?.focus(),document.activeElement!==we))return},[M,_]),U=I.useCallback(()=>T([W,E]),[T,W,E]);I.useEffect(()=>{j&&U()},[j,U]);const{onOpenChange:L,triggerPointerDownPosRef:P}=x;I.useEffect(()=>{if(E){let oe={x:0,y:0};const Oe=V=>{oe={x:Math.abs(Math.round(V.pageX)-(P.current?.x??0)),y:Math.abs(Math.round(V.pageY)-(P.current?.y??0))}},je=V=>{oe.x<=10&&oe.y<=10?V.preventDefault():E.contains(V.target)||L(!1),document.removeEventListener("pointermove",Oe),P.current=null};return P.current!==null&&(document.addEventListener("pointermove",Oe),document.addEventListener("pointerup",je,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Oe),document.removeEventListener("pointerup",je,{capture:!0})}}},[E,L,P]),I.useEffect(()=>{const oe=()=>L(!1);return window.addEventListener("blur",oe),window.addEventListener("resize",oe),()=>{window.removeEventListener("blur",oe),window.removeEventListener("resize",oe)}},[L]);const[H,Y]=Oxe(oe=>{const Oe=M().filter(we=>!we.disabled),je=Oe.find(we=>we.ref.current===document.activeElement),V=$xe(Oe,oe,je);V&&setTimeout(()=>V.ref.current.focus())}),re=I.useCallback((oe,Oe,je)=>{const V=!N.current&&!je;(x.value!==void 0&&x.value===Oe||V)&&(S(oe),V&&(N.current=!0))},[x.value]),de=I.useCallback(()=>E?.focus(),[E]),fe=I.useCallback((oe,Oe,je)=>{const V=!N.current&&!je;(x.value!==void 0&&x.value===Oe||V)&&R(oe)},[x.value]),ve=r==="popper"?MU:yxe,Ee=ve===MU?{side:a,sideOffset:c,align:l,alignOffset:u,arrowPadding:d,collisionBoundary:f,collisionPadding:p,sticky:m,hideWhenDetached:y,avoidCollisions:b}:{};return w.jsx(gxe,{scope:n,content:E,viewport:_,onViewportChange:k,itemRefCallback:re,selectedItem:W,onItemLeave:de,itemTextRefCallback:fe,focusSelectedItem:U,selectedItemText:$,position:r,isPositioned:j,searchRef:H,children:w.jsx(D8,{as:Fh,allowPinchZoom:!0,children:w.jsx(N8,{asChild:!0,trapped:x.open,onMountAutoFocus:oe=>{oe.preventDefault()},onUnmountAutoFocus:vt(s,oe=>{x.trigger?.focus({preventScroll:!0}),oe.preventDefault()}),children:w.jsx(z1,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:o,onFocusOutside:oe=>oe.preventDefault(),onDismiss:()=>x.onOpenChange(!1),children:w.jsx(ve,{role:"listbox",id:x.contentId,"data-state":x.open?"open":"closed",dir:x.dir,onContextMenu:oe=>oe.preventDefault(),...v,...Ee,onPlaced:()=>z(!0),ref:B,style:{display:"flex",flexDirection:"column",outline:"none",...v.style},onKeyDown:vt(v.onKeyDown,oe=>{const Oe=oe.ctrlKey||oe.altKey||oe.metaKey;if(oe.key==="Tab"&&oe.preventDefault(),!Oe&&oe.key.length===1&&Y(oe.key),["ArrowUp","ArrowDown","Home","End"].includes(oe.key)){let V=M().filter(we=>!we.disabled).map(we=>we.ref.current);if(["ArrowUp","End"].includes(oe.key)&&(V=V.slice().reverse()),["ArrowUp","ArrowDown"].includes(oe.key)){const we=oe.target,Ae=V.indexOf(we);V=V.slice(Ae+1)}setTimeout(()=>T(V)),oe.preventDefault()}})})})})})})});mxe.displayName=ONt;var $Nt="SelectItemAlignedPosition",yxe=I.forwardRef((t,e)=>{const{__scopeSelect:n,onPlaced:r,...s}=t,i=B0(qy,n),o=U0(qy,n),[a,c]=I.useState(null),[l,u]=I.useState(null),d=ir(e,B=>u(B)),f=q8(n),p=I.useRef(!1),m=I.useRef(!0),{viewport:y,selectedItem:b,selectedItemText:v,focusSelectedItem:x}=o,E=I.useCallback(()=>{if(i.trigger&&i.valueNode&&a&&l&&y&&b&&v){const B=i.trigger.getBoundingClientRect(),W=l.getBoundingClientRect(),S=i.valueNode.getBoundingClientRect(),$=v.getBoundingClientRect();if(i.dir!=="rtl"){const we=$.left-W.left,Ae=S.left-we,Ie=B.left-Ae,ge=B.width+Ie,Me=Math.max(ge,W.width),be=window.innerWidth-Au,pe=yse(Ae,[Au,Math.max(Au,be-Me)]);a.style.minWidth=ge+"px",a.style.left=pe+"px"}else{const we=W.right-$.right,Ae=window.innerWidth-S.right-we,Ie=window.innerWidth-B.right-Ae,ge=B.width+Ie,Me=Math.max(ge,W.width),be=window.innerWidth-Au,pe=yse(Ae,[Au,Math.max(Au,be-Me)]);a.style.minWidth=ge+"px",a.style.right=pe+"px"}const R=f(),M=window.innerHeight-Au*2,j=y.scrollHeight,z=window.getComputedStyle(l),N=parseInt(z.borderTopWidth,10),T=parseInt(z.paddingTop,10),U=parseInt(z.borderBottomWidth,10),L=parseInt(z.paddingBottom,10),P=N+T+j+L+U,H=Math.min(b.offsetHeight*5,P),Y=window.getComputedStyle(y),re=parseInt(Y.paddingTop,10),de=parseInt(Y.paddingBottom,10),fe=B.top+B.height/2-Au,ve=M-fe,Ee=b.offsetHeight/2,oe=b.offsetTop+Ee,Oe=N+T+oe,je=P-Oe;if(Oe<=fe){const we=R.length>0&&b===R[R.length-1].ref.current;a.style.bottom="0px";const Ae=l.clientHeight-y.offsetTop-y.offsetHeight,Ie=Math.max(ve,Ee+(we?de:0)+Ae+U),ge=Oe+Ie;a.style.height=ge+"px"}else{const we=R.length>0&&b===R[0].ref.current;a.style.top="0px";const Ie=Math.max(fe,N+y.offsetTop+(we?re:0)+Ee)+je;a.style.height=Ie+"px",y.scrollTop=Oe-fe+y.offsetTop}a.style.margin=`${Au}px 0`,a.style.minHeight=H+"px",a.style.maxHeight=M+"px",r?.(),requestAnimationFrame(()=>p.current=!0)}},[f,i.trigger,i.valueNode,a,l,y,b,v,i.dir,r]);No(()=>E(),[E]);const[A,_]=I.useState();No(()=>{l&&_(window.getComputedStyle(l).zIndex)},[l]);const k=I.useCallback(B=>{B&&m.current===!0&&(E(),x?.(),m.current=!1)},[E,x]);return w.jsx(MNt,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:k,children:w.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:A},children:w.jsx(gn.div,{...s,ref:d,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});yxe.displayName=$Nt;var DNt="SelectPopperPosition",MU=I.forwardRef((t,e)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=Au,...i}=t,o=K8(n);return w.jsx(rj,{...o,...i,ref:e,align:r,collisionPadding:s,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});MU.displayName=DNt;var[MNt,UH]=Sx(qy,{}),LU="SelectViewport",wxe=I.forwardRef((t,e)=>{const{__scopeSelect:n,nonce:r,...s}=t,i=U0(LU,n),o=UH(LU,n),a=ir(e,i.onViewportChange),c=I.useRef(0);return w.jsxs(w.Fragment,{children:[w.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),w.jsx(H8.Slot,{scope:n,children:w.jsx(gn.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...s.style},onScroll:vt(s.onScroll,l=>{const u=l.currentTarget,{contentWrapper:d,shouldExpandOnScrollRef:f}=o;if(f?.current&&d){const p=Math.abs(c.current-u.scrollTop);if(p>0){const m=window.innerHeight-Au*2,y=parseFloat(d.style.minHeight),b=parseFloat(d.style.height),v=Math.max(y,b);if(v0?A:0,d.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});wxe.displayName=LU;var bxe="SelectGroup",[LNt,BNt]=Sx(bxe),UNt=I.forwardRef((t,e)=>{const{__scopeSelect:n,...r}=t,s=Wu();return w.jsx(LNt,{scope:n,id:s,children:w.jsx(gn.div,{role:"group","aria-labelledby":s,...r,ref:e})})});UNt.displayName=bxe;var vxe="SelectLabel",xxe=I.forwardRef((t,e)=>{const{__scopeSelect:n,...r}=t,s=BNt(vxe,n);return w.jsx(gn.div,{id:s.id,...r,ref:e})});xxe.displayName=vxe;var D4="SelectItem",[FNt,Exe]=Sx(D4),Cxe=I.forwardRef((t,e)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:i,...o}=t,a=B0(D4,n),c=U0(D4,n),l=a.value===r,[u,d]=I.useState(i??""),[f,p]=I.useState(!1),m=ir(e,x=>c.itemRefCallback?.(x,r,s)),y=Wu(),b=I.useRef("touch"),v=()=>{s||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return w.jsx(FNt,{scope:n,value:r,disabled:s,textId:y,isSelected:l,onItemTextChange:I.useCallback(x=>{d(E=>E||(x?.textContent??"").trim())},[]),children:w.jsx(H8.ItemSlot,{scope:n,value:r,disabled:s,textValue:u,children:w.jsx(gn.div,{role:"option","aria-labelledby":y,"data-highlighted":f?"":void 0,"aria-selected":l&&f,"data-state":l?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...o,ref:m,onFocus:vt(o.onFocus,()=>p(!0)),onBlur:vt(o.onBlur,()=>p(!1)),onClick:vt(o.onClick,()=>{b.current!=="mouse"&&v()}),onPointerUp:vt(o.onPointerUp,()=>{b.current==="mouse"&&v()}),onPointerDown:vt(o.onPointerDown,x=>{b.current=x.pointerType}),onPointerMove:vt(o.onPointerMove,x=>{b.current=x.pointerType,s?c.onItemLeave?.():b.current==="mouse"&&x.currentTarget.focus({preventScroll:!0})}),onPointerLeave:vt(o.onPointerLeave,x=>{x.currentTarget===document.activeElement&&c.onItemLeave?.()}),onKeyDown:vt(o.onKeyDown,x=>{c.searchRef?.current!==""&&x.key===" "||(ANt.includes(x.key)&&v(),x.key===" "&&x.preventDefault())})})})})});Cxe.displayName=D4;var nE="SelectItemText",_xe=I.forwardRef((t,e)=>{const{__scopeSelect:n,className:r,style:s,...i}=t,o=B0(nE,n),a=U0(nE,n),c=Exe(nE,n),l=PNt(nE,n),[u,d]=I.useState(null),f=ir(e,v=>d(v),c.onItemTextChange,v=>a.itemTextRefCallback?.(v,c.value,c.disabled)),p=u?.textContent,m=I.useMemo(()=>w.jsx("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:y,onNativeOptionRemove:b}=l;return No(()=>(y(m),()=>b(m)),[y,b,m]),w.jsxs(w.Fragment,{children:[w.jsx(gn.span,{id:c.textId,...i,ref:f}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?Qy.createPortal(i.children,o.valueNode):null]})});_xe.displayName=nE;var Sxe="SelectItemIndicator",Axe=I.forwardRef((t,e)=>{const{__scopeSelect:n,...r}=t;return Exe(Sxe,n).isSelected?w.jsx(gn.span,{"aria-hidden":!0,...r,ref:e}):null});Axe.displayName=Sxe;var BU="SelectScrollUpButton",Ixe=I.forwardRef((t,e)=>{const n=U0(BU,t.__scopeSelect),r=UH(BU,t.__scopeSelect),[s,i]=I.useState(!1),o=ir(e,r.onScrollButtonChange);return No(()=>{if(n.viewport&&n.isPositioned){let a=function(){const l=c.scrollTop>0;i(l)};const c=n.viewport;return a(),c.addEventListener("scroll",a),()=>c.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),s?w.jsx(Nxe,{...t,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:c}=n;a&&c&&(a.scrollTop=a.scrollTop-c.offsetHeight)}}):null});Ixe.displayName=BU;var UU="SelectScrollDownButton",Txe=I.forwardRef((t,e)=>{const n=U0(UU,t.__scopeSelect),r=UH(UU,t.__scopeSelect),[s,i]=I.useState(!1),o=ir(e,r.onScrollButtonChange);return No(()=>{if(n.viewport&&n.isPositioned){let a=function(){const l=c.scrollHeight-c.clientHeight,u=Math.ceil(c.scrollTop)c.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),s?w.jsx(Nxe,{...t,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:c}=n;a&&c&&(a.scrollTop=a.scrollTop+c.offsetHeight)}}):null});Txe.displayName=UU;var Nxe=I.forwardRef((t,e)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=t,i=U0("SelectScrollButton",n),o=I.useRef(null),a=q8(n),c=I.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return I.useEffect(()=>()=>c(),[c]),No(()=>{a().find(u=>u.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[a]),w.jsx(gn.div,{"aria-hidden":!0,...s,ref:e,style:{flexShrink:0,...s.style},onPointerDown:vt(s.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(r,50))}),onPointerMove:vt(s.onPointerMove,()=>{i.onItemLeave?.(),o.current===null&&(o.current=window.setInterval(r,50))}),onPointerLeave:vt(s.onPointerLeave,()=>{c()})})}),jNt="SelectSeparator",Pxe=I.forwardRef((t,e)=>{const{__scopeSelect:n,...r}=t;return w.jsx(gn.div,{"aria-hidden":!0,...r,ref:e})});Pxe.displayName=jNt;var FU="SelectArrow",zNt=I.forwardRef((t,e)=>{const{__scopeSelect:n,...r}=t,s=K8(n),i=B0(FU,n),o=U0(FU,n);return i.open&&o.position==="popper"?w.jsx(sj,{...s,...r,ref:e}):null});zNt.displayName=FU;function kxe(t){return t===""||t===void 0}var Rxe=I.forwardRef((t,e)=>{const{value:n,...r}=t,s=I.useRef(null),i=ir(e,s),o=oxe(n);return I.useEffect(()=>{const a=s.current,c=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==n&&u){const d=new Event("change",{bubbles:!0});u.call(a,n),a.dispatchEvent(d)}},[o,n]),w.jsx($S,{asChild:!0,children:w.jsx("select",{...r,ref:i,defaultValue:n})})});Rxe.displayName="BubbleSelect";function Oxe(t){const e=To(t),n=I.useRef(""),r=I.useRef(0),s=I.useCallback(o=>{const a=n.current+o;e(a),function c(l){n.current=l,window.clearTimeout(r.current),l!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(a)},[e]),i=I.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return I.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,i]}function $xe(t,e,n){const s=e.length>1&&Array.from(e).every(l=>l===e[0])?e[0]:e,i=n?t.indexOf(n):-1;let o=WNt(t,Math.max(i,0));s.length===1&&(o=o.filter(l=>l!==n));const c=o.find(l=>l.textValue.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function WNt(t,e){return t.map((n,r)=>t[(e+r)%t.length])}var VNt=axe,Dxe=lxe,HNt=dxe,qNt=fxe,KNt=hxe,Mxe=pxe,GNt=wxe,Lxe=xxe,Bxe=Cxe,ZNt=_xe,YNt=Axe,Uxe=Ixe,Fxe=Txe,jxe=Pxe;const FH=VNt,jH=HNt,G8=I.forwardRef(({className:t,children:e,...n},r)=>w.jsxs(Dxe,{ref:r,className:Dt("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...n,children:[e,w.jsx(qNt,{asChild:!0,children:w.jsx(wae,{className:"h-4 w-4 opacity-50"})})]}));G8.displayName=Dxe.displayName;const zxe=I.forwardRef(({className:t,...e},n)=>w.jsx(Uxe,{ref:n,className:Dt("flex cursor-default items-center justify-center py-1",t),...e,children:w.jsx(vNe,{className:"h-4 w-4"})}));zxe.displayName=Uxe.displayName;const Wxe=I.forwardRef(({className:t,...e},n)=>w.jsx(Fxe,{ref:n,className:Dt("flex cursor-default items-center justify-center py-1",t),...e,children:w.jsx(wae,{className:"h-4 w-4"})}));Wxe.displayName=Fxe.displayName;const Z8=I.forwardRef(({className:t,children:e,position:n="popper",...r},s)=>w.jsx(KNt,{children:w.jsxs(Mxe,{ref:s,className:Dt("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,...r,children:[w.jsx(zxe,{}),w.jsx(GNt,{className:Dt("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),w.jsx(Wxe,{})]})}));Z8.displayName=Mxe.displayName;const XNt=I.forwardRef(({className:t,...e},n)=>w.jsx(Lxe,{ref:n,className:Dt("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...e}));XNt.displayName=Lxe.displayName;const Ch=I.forwardRef(({className:t,children:e,...n},r)=>w.jsxs(Bxe,{ref:r,className:Dt("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[w.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:w.jsx(YNt,{children:w.jsx(yae,{className:"h-4 w-4"})})}),w.jsx(ZNt,{children:e})]}));Ch.displayName=Bxe.displayName;const QNt=I.forwardRef(({className:t,...e},n)=>w.jsx(jxe,{ref:n,className:Dt("-mx-1 my-1 h-px bg-muted",t),...e}));QNt.displayName=jxe.displayName;const JNt=({post:t,commentCount:e=0})=>{const{cellsWithStats:n}=wd(),{votePost:r,isVoting:s}=_p(),{canVote:i}=Cp(),o=I8(),{isBookmarked:a,loading:c,toggleBookmark:l}=Ibe(t,t.cellId),{toast:u}=xf(),f=n.find(B=>B.id===t.cellId)?.name||"unknown",p="voteScore"in t?t.voteScore:t.upvotes.length-t.downvotes.length,{isPending:m}=V8(t.id),y=BH(t.id),b=o.getPostVoteType(t.id),v=b==="upvote",x=b==="downvote",E=t.content.length>200?t.content.substring(0,200)+"...":t.content,A=async(B,W)=>{B.preventDefault(),await r(t.id,W)},_=async B=>{B&&(B.preventDefault(),B.stopPropagation()),await l()},k=async B=>{B.preventDefault(),B.stopPropagation();const W=`${window.location.origin}/post/${t.id}`;try{await navigator.clipboard.writeText(W),u({title:"Link copied!",description:"Post link has been copied to your clipboard."})}catch{const S=document.createElement("textarea");S.value=W,document.body.appendChild(S),S.select(),document.execCommand("copy"),document.body.removeChild(S),u({title:"Link copied!",description:"Post link has been copied to your clipboard."})}};return w.jsx("div",{className:"thread-card mb-2",children:w.jsxs("div",{className:"flex",children:[w.jsxs("div",{className:"flex flex-col items-center p-2 bg-cyber-muted/50 border-r border-cyber-muted",children:[w.jsx("button",{className:`p-1 rounded hover:bg-cyber-muted transition-colors ${v?"text-cyber-accent":"text-cyber-neutral hover:text-cyber-accent"}`,onClick:B=>A(B,!0),disabled:!i||s,title:i?"Upvote":"Connect wallet and verify to vote",children:w.jsx(mP,{className:"w-5 h-5"})}),w.jsx("span",{className:`text-sm font-medium px-1 ${p>0?"text-cyber-accent":p<0?"text-blue-400":"text-cyber-neutral"}`,children:p}),w.jsx("button",{className:`p-1 rounded hover:bg-cyber-muted transition-colors ${x?"text-blue-400":"text-cyber-neutral hover:text-blue-400"}`,onClick:B=>A(B,!1),disabled:!i||s,title:i?"Downvote":"Connect wallet and verify to vote",children:w.jsx(gP,{className:"w-5 h-5"})}),y.isPending&&w.jsx("span",{className:"mt-1 text-[10px] text-yellow-400",children:"syncing…"})]}),w.jsx("div",{className:"flex-1 p-3",children:w.jsxs("div",{className:"block hover:opacity-80",children:[w.jsxs("div",{className:"flex items-center text-xs text-cyber-neutral mb-2 space-x-2",children:[w.jsxs("span",{className:"font-medium text-cyber-accent",children:["r/",f]}),w.jsx("span",{children:"•"}),w.jsx("span",{children:"Posted by u/"}),w.jsx(W8,{address:t.author,className:"text-xs",showBadge:!1}),w.jsx("span",{children:"•"}),w.jsx("span",{children:G3(new Date(t.timestamp),{addSuffix:!0})}),t.relevanceScore!==void 0&&w.jsxs(w.Fragment,{children:[w.jsx("span",{children:"•"}),w.jsx(MH,{score:t.relevanceScore,details:t.relevanceDetails,type:"post",className:"text-xs",showTooltip:!0})]})]}),w.jsxs("div",{className:"block",children:[w.jsx(ks,{to:`/post/${t.id}`,className:"block",children:w.jsx("h2",{className:"text-lg font-semibold text-glow mb-2 hover:text-cyber-accent transition-colors",children:t.title})}),w.jsx("p",{className:"text-cyber-neutral text-sm leading-relaxed mb-3",children:w.jsx(z8,{text:E})})]}),w.jsxs("div",{className:"flex items-center justify-between text-xs text-cyber-neutral",children:[w.jsxs("div",{className:"flex items-center space-x-4",children:[w.jsxs("div",{className:"flex items-center space-x-1 hover:text-cyber-accent transition-colors",children:[w.jsx(s0,{className:"w-4 h-4"}),w.jsxs("span",{children:[e," comments"]})]}),m&&w.jsx("span",{className:"px-2 py-0.5 rounded-sm bg-yellow-500/20 text-yellow-400 border border-yellow-500/30",children:"syncing…"}),w.jsxs("button",{onClick:k,className:"hover:text-cyber-accent transition-colors flex items-center gap-1",title:"Copy link",children:[w.jsx(CNe,{size:14}),"Share"]})]}),w.jsx(LH,{isBookmarked:a,loading:c,onClick:_,size:"sm",variant:"ghost"})]})]})})]})})},e4t=()=>{const t=wd(),{currentUser:e,verificationStatus:n}=_i(),{displayName:r,ensName:s,ordinalDetails:i}=H3(e?.address||""),{filteredPosts:o,filteredComments:a,filteredCellsWithStats:c,cells:l,userVerificationStatus:u}=t,d={totalCells:l.length,totalPosts:o.length,totalComments:a.length,totalUsers:new Set([...o.map(y=>y.author),...a.map(y=>y.author)]).size,verifiedUsers:Object.values(u).filter(y=>y.isVerified).length},f=c.sort((y,b)=>b.recentActivity-y.recentActivity).slice(0,5),m=n===Ct.ENS_ORDINAL_VERIFIED?{text:"Verified Owner",color:"bg-green-500"}:n===Ct.WALLET_CONNECTED?{text:"Verified",color:"bg-blue-500"}:s?{text:"ENS User",color:"bg-purple-500"}:i?{text:"Ordinal User",color:"bg-orange-500"}:{text:"Unverified",color:"bg-gray-500"};return w.jsxs("div",{className:"w-80 bg-cyber-muted/10 border-l border-cyber-muted p-4 space-y-6 overflow-y-auto",children:[e&&w.jsxs(Yu,{className:"bg-cyber-muted/20 border-cyber-muted",children:[w.jsx(sf,{className:"pb-3",children:w.jsx(Dh,{className:"text-sm font-medium",children:"Your Status"})}),w.jsxs(Xu,{className:"space-y-3",children:[w.jsxs("div",{className:"flex items-center space-x-3",children:[w.jsx("div",{className:"w-10 h-10 rounded-full bg-cyber-accent/20 flex items-center justify-center",children:w.jsx(MNe,{className:"w-5 h-5 text-cyber-accent"})}),w.jsxs("div",{className:"flex-1",children:[w.jsx("div",{className:"font-medium text-sm",children:r}),w.jsx(Ao,{variant:"secondary",className:`${m.color} text-white text-xs`,children:m.text})]})]}),n===Ct.WALLET_UNCONNECTED&&w.jsxs("div",{className:"text-xs text-muted-foreground",children:[w.jsx(K6,{className:"w-3 h-3 inline mr-1"}),"Read-only mode. Verify wallet to participate."]}),n===Ct.WALLET_CONNECTED&&!i&&w.jsxs("div",{className:"text-xs text-muted-foreground",children:[w.jsx(K6,{className:"w-3 h-3 inline mr-1"}),"Read-only mode. Acquire Ordinals to post."]})]})]}),w.jsxs(Yu,{className:"bg-cyber-muted/20 border-cyber-muted",children:[w.jsx(sf,{className:"pb-3",children:w.jsxs(Dh,{className:"text-sm font-medium flex items-center",children:[w.jsx(lC,{className:"w-4 h-4 mr-2"}),"Forum Stats"]})}),w.jsx(Xu,{children:w.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[w.jsxs("div",{children:[w.jsx("div",{className:"text-lg font-bold text-cyber-accent",children:d.totalCells}),w.jsx("div",{className:"text-xs text-muted-foreground",children:"Cells"})]}),w.jsxs("div",{children:[w.jsx("div",{className:"text-lg font-bold text-cyber-accent",children:d.totalPosts}),w.jsx("div",{className:"text-xs text-muted-foreground",children:"Posts"})]}),w.jsxs("div",{children:[w.jsx("div",{className:"text-lg font-bold text-cyber-accent",children:d.totalComments}),w.jsx("div",{className:"text-xs text-muted-foreground",children:"Comments"})]})]})})]}),w.jsxs(Yu,{className:"bg-cyber-muted/20 border-cyber-muted",children:[w.jsx(sf,{className:"pb-3",children:w.jsx(Dh,{className:"text-sm font-medium",children:"Trending Cells"})}),w.jsxs(Xu,{className:"space-y-3",children:[f.map(y=>w.jsxs(ks,{to:`/cell/${y.id}`,className:"flex items-center space-x-3 p-2 rounded-sm hover:bg-cyber-muted/30 transition-colors",children:[w.jsx(DH,{src:y.icon,alt:y.name,className:"w-8 h-8 rounded-sm",generateUniqueFallback:!0}),w.jsxs("div",{className:"flex-1 min-w-0",children:[w.jsx("div",{className:"font-medium text-sm truncate",children:y.name}),w.jsxs("div",{className:"text-xs text-muted-foreground",children:[y.postCount," posts • ",y.activeUsers," members"]})]})]},y.id)),f.length===0&&w.jsx("div",{className:"text-center text-xs text-muted-foreground py-4",children:"No active cells yet"})]})]})]})};var zH="Switch",[t4t,JDt]=pp(zH),[n4t,r4t]=t4t(zH),Vxe=I.forwardRef((t,e)=>{const{__scopeSwitch:n,name:r,checked:s,defaultChecked:i,required:o,disabled:a,value:c="on",onCheckedChange:l,form:u,...d}=t,[f,p]=I.useState(null),m=ir(e,E=>p(E)),y=I.useRef(!1),b=f?u||!!f.closest("form"):!0,[v=!1,x]=jh({prop:s,defaultProp:i,onChange:l});return w.jsxs(n4t,{scope:n,checked:v,disabled:a,children:[w.jsx(gn.button,{type:"button",role:"switch","aria-checked":v,"aria-required":o,"data-state":Kxe(v),"data-disabled":a?"":void 0,disabled:a,value:c,...d,ref:m,onClick:vt(t.onClick,E=>{x(A=>!A),b&&(y.current=E.isPropagationStopped(),y.current||E.stopPropagation())})}),b&&w.jsx(s4t,{control:f,bubbles:!y.current,name:r,value:c,checked:v,required:o,disabled:a,form:u,style:{transform:"translateX(-100%)"}})]})});Vxe.displayName=zH;var Hxe="SwitchThumb",qxe=I.forwardRef((t,e)=>{const{__scopeSwitch:n,...r}=t,s=r4t(Hxe,n);return w.jsx(gn.span,{"data-state":Kxe(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:e})});qxe.displayName=Hxe;var s4t=t=>{const{control:e,checked:n,bubbles:r=!0,...s}=t,i=I.useRef(null),o=oxe(n),a=Wae(e);return I.useEffect(()=>{const c=i.current,l=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(l,"checked").set;if(o!==n&&d){const f=new Event("click",{bubbles:r});d.call(c,n),c.dispatchEvent(f)}},[o,n,r]),w.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:i,style:{...t.style,...a,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function Kxe(t){return t?"checked":"unchecked"}var Gxe=Vxe,i4t=qxe;const Zxe=I.forwardRef(({className:t,...e},n)=>w.jsx(Gxe,{className:Dt("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...e,ref:n,children:w.jsx(i4t,{className:Dt("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Zxe.displayName=Gxe.displayName;var o4t="Label",Yxe=I.forwardRef((t,e)=>w.jsx(gn.label,{...t,ref:e,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(t.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));Yxe.displayName=o4t;var Xxe=Yxe;const a4t=pP("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Cg=I.forwardRef(({className:t,...e},n)=>w.jsx(Xxe,{ref:n,className:Dt(a4t(),t),...e}));Cg.displayName=Xxe.displayName;function Qxe(){const{showModerated:t,toggleShowModerated:e}=A8(),{canModerate:n}=Cp(),{cellsWithStats:r}=wd();return r.some(i=>n(i.id))?w.jsxs("div",{className:"flex items-center space-x-2",children:[w.jsx(Zxe,{id:"show-moderated",checked:t,onCheckedChange:e,className:"data-[state=checked]:bg-cyber-accent"}),w.jsxs(Cg,{htmlFor:"show-moderated",className:"flex items-center gap-2 text-sm cursor-pointer",children:[t?w.jsx(K6,{className:"w-4 h-4 text-cyber-accent"}):w.jsx(ANe,{className:"w-4 h-4 text-cyber-neutral"}),w.jsx("span",{className:t?"text-cyber-accent":"text-cyber-neutral",children:"Show Moderated"})]})]}):null}const M4=t=>t.sort((e,n)=>(n.relevanceScore||0)-(e.relevanceScore||0)),Jxe=t=>t.sort((e,n)=>n.timestamp-e.timestamp),c4t=(t,e)=>{switch(e){case"relevance":return M4(t);case"time":return Jxe(t);default:return M4(t)}},l4t=(t,e)=>{switch(e){case"relevance":return M4(t);case"time":return Jxe(t);default:return M4(t)}},u4t=()=>{const t=wd(),{verificationStatus:e}=_i(),{refreshData:n}=_p(),[r,s]=I.useState("relevance"),{filteredPosts:i,filteredCommentsByPost:o,isInitialLoading:a,isRefreshing:c}=t,l=I.useMemo(()=>c4t(i,r),[i,r]),u=d=>(o[d]||[]).length;return a?w.jsx("div",{className:"min-h-screen bg-cyber-dark",children:w.jsx("div",{className:"container mx-auto px-4 py-6 max-w-6xl",children:w.jsxs("div",{className:"flex gap-6",children:[w.jsx("div",{className:"flex-1 max-w-3xl",children:w.jsx("div",{className:"space-y-4",children:[...Array(5)].map((d,f)=>w.jsx("div",{className:"bg-cyber-muted/20 border border-cyber-muted rounded-sm p-4",children:w.jsxs("div",{className:"flex gap-4",children:[w.jsxs("div",{className:"w-10 space-y-2",children:[w.jsx(Li,{className:"h-6 w-6"}),w.jsx(Li,{className:"h-4 w-8"}),w.jsx(Li,{className:"h-6 w-6"})]}),w.jsxs("div",{className:"flex-1 space-y-2",children:[w.jsx(Li,{className:"h-4 w-2/3"}),w.jsx(Li,{className:"h-6 w-full"}),w.jsx(Li,{className:"h-4 w-full"}),w.jsx(Li,{className:"h-4 w-3/4"}),w.jsx(Li,{className:"h-4 w-1/3"})]})]})},f))})}),w.jsx("div",{className:"w-80 space-y-4",children:[...Array(3)].map((d,f)=>w.jsxs("div",{className:"bg-cyber-muted/20 border border-cyber-muted rounded-sm p-4",children:[w.jsx(Li,{className:"h-6 w-1/2 mb-3"}),w.jsxs("div",{className:"space-y-2",children:[w.jsx(Li,{className:"h-4 w-full"}),w.jsx(Li,{className:"h-4 w-3/4"}),w.jsx(Li,{className:"h-4 w-1/2"})]})]},f))})]})})}):w.jsx("div",{className:"page-container",children:w.jsxs("div",{className:"page-main",children:[w.jsx("div",{className:"page-header",children:w.jsxs("div",{className:"flex items-center justify-between",children:[w.jsxs("div",{children:[w.jsx("h1",{className:"page-title text-glow text-cyber-accent",children:"Popular Posts"}),w.jsx("p",{className:"page-subtitle",children:"Latest posts from all cells"})]}),w.jsxs("div",{className:"flex items-center space-x-2",children:[w.jsx(Qxe,{}),w.jsxs(FH,{value:r,onValueChange:d=>s(d),children:[w.jsx(G8,{className:"w-40",children:w.jsx(jH,{})}),w.jsxs(Z8,{children:[w.jsx(Ch,{value:"relevance",children:w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(lC,{className:"w-4 h-4"}),w.jsx("span",{children:"Relevance"})]})}),w.jsx(Ch,{value:"time",children:w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(W1,{className:"w-4 h-4"}),w.jsx("span",{children:"Newest"})]})})]})]}),w.jsxs(fn,{variant:"outline",size:"sm",onClick:n,disabled:c,className:"flex items-center space-x-2",children:[w.jsx(HF,{className:`w-4 h-4 ${c?"animate-spin":""}`}),w.jsx("span",{children:"Refresh"})]})]})]})}),w.jsxs("div",{className:"flex gap-6",children:[w.jsx("div",{className:"flex-1 max-w-3xl",children:w.jsx("div",{className:"space-y-0",children:l.length===0?w.jsx("div",{className:"empty-state",children:w.jsxs("div",{className:"space-y-3",children:[w.jsx("h3",{className:"empty-state-title text-glow",children:"No posts yet"}),w.jsx("p",{className:"empty-state-description",children:"Be the first to create a post in a cell!"}),e!==Ct.ENS_ORDINAL_VERIFIED&&w.jsx("p",{className:"text-sm text-cyber-neutral/80",children:"Connect your wallet and verify Ordinal ownership to start posting"})]})}):l.map(d=>w.jsx(JNt,{post:d,commentCount:u(d.id)},d.id))})}),w.jsx("div",{className:"w-80 flex-shrink-0",children:w.jsx(e4t,{})})]})]})})},d4t=()=>w.jsxs("div",{className:"min-h-screen flex flex-col bg-cyber-dark",children:[w.jsx(Kd,{}),w.jsx("main",{className:"flex-1 pt-16",children:w.jsx(u4t,{})})]});var Y3=t=>t.type==="checkbox",Lm=t=>t instanceof Date,Ko=t=>t==null;const e2e=t=>typeof t=="object";var Ms=t=>!Ko(t)&&!Array.isArray(t)&&e2e(t)&&!Lm(t),t2e=t=>Ms(t)&&t.target?Y3(t.target)?t.target.checked:t.target.value:t,f4t=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,n2e=(t,e)=>t.has(f4t(e)),h4t=t=>{const e=t.constructor&&t.constructor.prototype;return Ms(e)&&e.hasOwnProperty("isPrototypeOf")},WH=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Ia(t){let e;const n=Array.isArray(t);if(t instanceof Date)e=new Date(t);else if(t instanceof Set)e=new Set(t);else if(!(WH&&(t instanceof Blob||t instanceof FileList))&&(n||Ms(t)))if(e=n?[]:{},!n&&!h4t(t))e=t;else for(const r in t)t.hasOwnProperty(r)&&(e[r]=Ia(t[r]));else return t;return e}var Y8=t=>Array.isArray(t)?t.filter(Boolean):[],_s=t=>t===void 0,wt=(t,e,n)=>{if(!e||!Ms(t))return n;const r=Y8(e.split(/[,[\].]+?/)).reduce((s,i)=>Ko(s)?s:s[i],t);return _s(r)||r===t?_s(t[e])?n:t[e]:r},xl=t=>typeof t=="boolean",VH=t=>/^\w*$/.test(t),r2e=t=>Y8(t.replace(/["|']|\]/g,"").split(/\.|\[/)),Nr=(t,e,n)=>{let r=-1;const s=VH(e)?[e]:r2e(e),i=s.length,o=i-1;for(;++rqe.useContext(s2e),p4t=t=>{const{children:e,...n}=t;return qe.createElement(s2e.Provider,{value:n},e)};var i2e=(t,e,n,r=!0)=>{const s={defaultValues:e._defaultValues};for(const i in t)Object.defineProperty(s,i,{get:()=>{const o=i;return e._proxyFormState[o]!==Mu.all&&(e._proxyFormState[o]=!r||Mu.all),n&&(n[o]=!0),t[o]}});return s},Ta=t=>Ms(t)&&!Object.keys(t).length,o2e=(t,e,n,r)=>{n(t);const{name:s,...i}=t;return Ta(i)||Object.keys(i).length>=Object.keys(e).length||Object.keys(i).find(o=>e[o]===(!r||Mu.all))},WE=t=>Array.isArray(t)?t:[t],a2e=(t,e,n)=>!t||!e||t===e||WE(t).some(r=>r&&(n?r===e:r.startsWith(e)||e.startsWith(r)));function HH(t){const e=qe.useRef(t);e.current=t,qe.useEffect(()=>{const n=!t.disabled&&e.current.subject&&e.current.subject.subscribe({next:e.current.next});return()=>{n&&n.unsubscribe()}},[t.disabled])}function g4t(t){const e=X8(),{control:n=e.control,disabled:r,name:s,exact:i}=t||{},[o,a]=qe.useState(n._formState),c=qe.useRef(!0),l=qe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),u=qe.useRef(s);return u.current=s,HH({disabled:r,next:d=>c.current&&a2e(u.current,d.name,i)&&o2e(d,l.current,n._updateFormState)&&a({...n._formState,...d}),subject:n._subjects.state}),qe.useEffect(()=>(c.current=!0,l.current.isValid&&n._updateValid(!0),()=>{c.current=!1}),[n]),i2e(o,n,l.current,!1)}var Gd=t=>typeof t=="string",c2e=(t,e,n,r,s)=>Gd(t)?(r&&e.watch.add(t),wt(n,t,s)):Array.isArray(t)?t.map(i=>(r&&e.watch.add(i),wt(n,i))):(r&&(e.watchAll=!0),n);function m4t(t){const e=X8(),{control:n=e.control,name:r,defaultValue:s,disabled:i,exact:o}=t||{},a=qe.useRef(r);a.current=r,HH({disabled:i,subject:n._subjects.values,next:u=>{a2e(a.current,u.name,o)&&l(Ia(c2e(a.current,n._names,u.values||n._formValues,!1,s)))}});const[c,l]=qe.useState(n._getWatch(r,s));return qe.useEffect(()=>n._removeUnmounted()),c}function y4t(t){const e=X8(),{name:n,disabled:r,control:s=e.control,shouldUnregister:i}=t,o=n2e(s._names.array,n),a=m4t({control:s,name:n,defaultValue:wt(s._formValues,n,wt(s._defaultValues,n,t.defaultValue)),exact:!0}),c=g4t({control:s,name:n,exact:!0}),l=qe.useRef(s.register(n,{...t.rules,value:a,...xl(t.disabled)?{disabled:t.disabled}:{}}));return qe.useEffect(()=>{const u=s._options.shouldUnregister||i,d=(f,p)=>{const m=wt(s._fields,f);m&&m._f&&(m._f.mount=p)};if(d(n,!0),u){const f=Ia(wt(s._options.defaultValues,n));Nr(s._defaultValues,n,f),_s(wt(s._formValues,n))&&Nr(s._formValues,n,f)}return()=>{(o?u&&!s._state.action:u)?s.unregister(n):d(n,!1)}},[n,s,o,i]),qe.useEffect(()=>{wt(s._fields,n)&&s._updateDisabledField({disabled:r,fields:s._fields,name:n,value:wt(s._fields,n)._f.value})},[r,n,s]),{field:{name:n,value:a,...xl(r)||c.disabled?{disabled:c.disabled||r}:{},onChange:qe.useCallback(u=>l.current.onChange({target:{value:t2e(u),name:n},type:L4.CHANGE}),[n]),onBlur:qe.useCallback(()=>l.current.onBlur({target:{value:wt(s._formValues,n),name:n},type:L4.BLUR}),[n,s]),ref:qe.useCallback(u=>{const d=wt(s._fields,n);d&&u&&(d._f.ref={focus:()=>u.focus(),select:()=>u.select(),setCustomValidity:f=>u.setCustomValidity(f),reportValidity:()=>u.reportValidity()})},[s._fields,n])},formState:c,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!wt(c.errors,n)},isDirty:{enumerable:!0,get:()=>!!wt(c.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!wt(c.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!wt(c.validatingFields,n)},error:{enumerable:!0,get:()=>wt(c.errors,n)}})}}const w4t=t=>t.render(y4t(t));var l2e=(t,e,n,r,s)=>e?{...n[t],types:{...n[t]&&n[t].types?n[t].types:{},[r]:s||!0}}:{},wse=t=>({isOnSubmit:!t||t===Mu.onSubmit,isOnBlur:t===Mu.onBlur,isOnChange:t===Mu.onChange,isOnAll:t===Mu.all,isOnTouch:t===Mu.onTouched}),bse=(t,e,n)=>!n&&(e.watchAll||e.watch.has(t)||[...e.watch].some(r=>t.startsWith(r)&&/^\.\w+/.test(t.slice(r.length))));const VE=(t,e,n,r)=>{for(const s of n||Object.keys(t)){const i=wt(t,s);if(i){const{_f:o,...a}=i;if(o){if(o.refs&&o.refs[0]&&e(o.refs[0],s)&&!r)return!0;if(o.ref&&e(o.ref,o.name)&&!r)return!0;if(VE(a,e))break}else if(Ms(a)&&VE(a,e))break}}};var b4t=(t,e,n)=>{const r=WE(wt(t,n));return Nr(r,"root",e[n]),Nr(t,n,r),t},qH=t=>t.type==="file",_h=t=>typeof t=="function",B4=t=>{if(!WH)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},m6=t=>Gd(t),KH=t=>t.type==="radio",U4=t=>t instanceof RegExp;const vse={value:!1,isValid:!1},xse={value:!0,isValid:!0};var u2e=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!_s(t[0].attributes.value)?_s(t[0].value)||t[0].value===""?xse:{value:t[0].value,isValid:!0}:xse:vse}return vse};const Ese={isValid:!1,value:null};var d2e=t=>Array.isArray(t)?t.reduce((e,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:e,Ese):Ese;function Cse(t,e,n="validate"){if(m6(t)||Array.isArray(t)&&t.every(m6)||xl(t)&&!t)return{type:n,message:m6(t)?t:"",ref:e}}var vb=t=>Ms(t)&&!U4(t)?t:{value:t,message:""},_se=async(t,e,n,r,s)=>{const{ref:i,refs:o,required:a,maxLength:c,minLength:l,min:u,max:d,pattern:f,validate:p,name:m,valueAsNumber:y,mount:b,disabled:v}=t._f,x=wt(e,m);if(!b||v)return{};const E=o?o[0]:i,A=M=>{r&&E.reportValidity&&(E.setCustomValidity(xl(M)?"":M||""),E.reportValidity())},_={},k=KH(i),B=Y3(i),W=k||B,S=(y||qH(i))&&_s(i.value)&&_s(x)||B4(i)&&i.value===""||x===""||Array.isArray(x)&&!x.length,$=l2e.bind(null,m,n,_),R=(M,j,z,N=rh.maxLength,T=rh.minLength)=>{const U=M?j:z;_[m]={type:M?N:T,message:U,ref:i,...$(M?N:T,U)}};if(s?!Array.isArray(x)||!x.length:a&&(!W&&(S||Ko(x))||xl(x)&&!x||B&&!u2e(o).isValid||k&&!d2e(o).isValid)){const{value:M,message:j}=m6(a)?{value:!!a,message:a}:vb(a);if(M&&(_[m]={type:rh.required,message:j,ref:E,...$(rh.required,j)},!n))return A(j),_}if(!S&&(!Ko(u)||!Ko(d))){let M,j;const z=vb(d),N=vb(u);if(!Ko(x)&&!isNaN(x)){const T=i.valueAsNumber||x&&+x;Ko(z.value)||(M=T>z.value),Ko(N.value)||(j=Tnew Date(new Date().toDateString()+" "+H),L=i.type=="time",P=i.type=="week";Gd(z.value)&&x&&(M=L?U(x)>U(z.value):P?x>z.value:T>new Date(z.value)),Gd(N.value)&&x&&(j=L?U(x)+M.value,N=!Ko(j.value)&&x.length<+j.value;if((z||N)&&(R(z,M.message,j.message),!n))return A(_[m].message),_}if(f&&!S&&Gd(x)){const{value:M,message:j}=vb(f);if(U4(M)&&!x.match(M)&&(_[m]={type:rh.pattern,message:j,ref:i,...$(rh.pattern,j)},!n))return A(j),_}if(p){if(_h(p)){const M=await p(x,e),j=Cse(M,E);if(j&&(_[m]={...j,...$(rh.validate,j.message)},!n))return A(j.message),_}else if(Ms(p)){let M={};for(const j in p){if(!Ta(M)&&!n)break;const z=Cse(await p[j](x,e),E,j);z&&(M={...z,...$(j,z.message)},A(z.message),n&&(_[m]=M))}if(!Ta(M)&&(_[m]={ref:E,...M},!n))return _}}return A(!0),_};function v4t(t,e){const n=e.slice(0,-1).length;let r=0;for(;r{let t=[];return{get observers(){return t},next:s=>{for(const i of t)i.next&&i.next(s)},subscribe:s=>(t.push(s),{unsubscribe:()=>{t=t.filter(i=>i!==s)}}),unsubscribe:()=>{t=[]}}},jU=t=>Ko(t)||!e2e(t);function _g(t,e){if(jU(t)||jU(e))return t===e;if(Lm(t)&&Lm(e))return t.getTime()===e.getTime();const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(const s of n){const i=t[s];if(!r.includes(s))return!1;if(s!=="ref"){const o=e[s];if(Lm(i)&&Lm(o)||Ms(i)&&Ms(o)||Array.isArray(i)&&Array.isArray(o)?!_g(i,o):i!==o)return!1}}return!0}var f2e=t=>t.type==="select-multiple",E4t=t=>KH(t)||Y3(t),G9=t=>B4(t)&&t.isConnected,h2e=t=>{for(const e in t)if(_h(t[e]))return!0;return!1};function F4(t,e={}){const n=Array.isArray(t);if(Ms(t)||n)for(const r in t)Array.isArray(t[r])||Ms(t[r])&&!h2e(t[r])?(e[r]=Array.isArray(t[r])?[]:{},F4(t[r],e[r])):Ko(t[r])||(e[r]=!0);return e}function p2e(t,e,n){const r=Array.isArray(t);if(Ms(t)||r)for(const s in t)Array.isArray(t[s])||Ms(t[s])&&!h2e(t[s])?_s(e)||jU(n[s])?n[s]=Array.isArray(t[s])?F4(t[s],[]):{...F4(t[s])}:p2e(t[s],Ko(e)?{}:e[s],n[s]):n[s]=!_g(t[s],e[s]);return n}var R2=(t,e)=>p2e(t,e,F4(e)),g2e=(t,{valueAsNumber:e,valueAsDate:n,setValueAs:r})=>_s(t)?t:e?t===""?NaN:t&&+t:n&&Gd(t)?new Date(t):r?r(t):t;function Z9(t){const e=t.ref;if(!(t.refs?t.refs.every(n=>n.disabled):e.disabled))return qH(e)?e.files:KH(e)?d2e(t.refs).value:f2e(e)?[...e.selectedOptions].map(({value:n})=>n):Y3(e)?u2e(t.refs).value:g2e(_s(e.value)?t.ref.value:e.value,t)}var C4t=(t,e,n,r)=>{const s={};for(const i of t){const o=wt(e,i);o&&Nr(s,i,o._f)}return{criteriaMode:n,names:[...t],fields:s,shouldUseNativeValidation:r}},O2=t=>_s(t)?t:U4(t)?t.source:Ms(t)?U4(t.value)?t.value.source:t.value:t;const Sse="AsyncFunction";var _4t=t=>(!t||!t.validate)&&!!(_h(t.validate)&&t.validate.constructor.name===Sse||Ms(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===Sse)),S4t=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate);function Ase(t,e,n){const r=wt(t,n);if(r||VH(n))return{error:r,name:n};const s=n.split(".");for(;s.length;){const i=s.join("."),o=wt(e,i),a=wt(t,i);if(o&&!Array.isArray(o)&&n!==i)return{name:n};if(a&&a.type)return{name:i,error:a};s.pop()}return{name:n}}var A4t=(t,e,n,r,s)=>s.isOnAll?!1:!n&&s.isOnTouch?!(e||t):(n?r.isOnBlur:s.isOnBlur)?!t:(n?r.isOnChange:s.isOnChange)?t:!0,I4t=(t,e)=>!Y8(wt(t,e)).length&&Js(t,e);const T4t={mode:Mu.onSubmit,reValidateMode:Mu.onChange,shouldFocusError:!0};function N4t(t={}){let e={...T4t,...t},n={submitCount:0,isDirty:!1,isLoading:_h(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},r={},s=Ms(e.defaultValues)||Ms(e.values)?Ia(e.defaultValues||e.values)||{}:{},i=e.shouldUnregister?{}:Ia(s),o={action:!1,mount:!1,watch:!1},a={mount:new Set,unMount:new Set,array:new Set,watch:new Set},c,l=0;const u={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},d={values:K9(),array:K9(),state:K9()},f=wse(e.mode),p=wse(e.reValidateMode),m=e.criteriaMode===Mu.all,y=J=>ie=>{clearTimeout(l),l=setTimeout(J,ie)},b=async J=>{if(!t.disabled&&(u.isValid||J)){const ie=e.resolver?Ta((await W()).errors):await $(r,!0);ie!==n.isValid&&d.state.next({isValid:ie})}},v=(J,ie)=>{!t.disabled&&(u.isValidating||u.validatingFields)&&((J||Array.from(a.mount)).forEach(ae=>{ae&&(ie?Nr(n.validatingFields,ae,ie):Js(n.validatingFields,ae))}),d.state.next({validatingFields:n.validatingFields,isValidating:!Ta(n.validatingFields)}))},x=(J,ie=[],ae,Pe,$e=!0,Re=!0)=>{if(Pe&&ae&&!t.disabled){if(o.action=!0,Re&&Array.isArray(wt(r,J))){const ut=ae(wt(r,J),Pe.argA,Pe.argB);$e&&Nr(r,J,ut)}if(Re&&Array.isArray(wt(n.errors,J))){const ut=ae(wt(n.errors,J),Pe.argA,Pe.argB);$e&&Nr(n.errors,J,ut),I4t(n.errors,J)}if(u.touchedFields&&Re&&Array.isArray(wt(n.touchedFields,J))){const ut=ae(wt(n.touchedFields,J),Pe.argA,Pe.argB);$e&&Nr(n.touchedFields,J,ut)}u.dirtyFields&&(n.dirtyFields=R2(s,i)),d.state.next({name:J,isDirty:M(J,ie),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Nr(i,J,ie)},E=(J,ie)=>{Nr(n.errors,J,ie),d.state.next({errors:n.errors})},A=J=>{n.errors=J,d.state.next({errors:n.errors,isValid:!1})},_=(J,ie,ae,Pe)=>{const $e=wt(r,J);if($e){const Re=wt(i,J,_s(ae)?wt(s,J):ae);_s(Re)||Pe&&Pe.defaultChecked||ie?Nr(i,J,ie?Re:Z9($e._f)):N(J,Re),o.mount&&b()}},k=(J,ie,ae,Pe,$e)=>{let Re=!1,ut=!1;const Je={name:J};if(!t.disabled){const ft=!!(wt(r,J)&&wt(r,J)._f&&wt(r,J)._f.disabled);if(!ae||Pe){u.isDirty&&(ut=n.isDirty,n.isDirty=Je.isDirty=M(),Re=ut!==Je.isDirty);const Z=ft||_g(wt(s,J),ie);ut=!!(!ft&&wt(n.dirtyFields,J)),Z||ft?Js(n.dirtyFields,J):Nr(n.dirtyFields,J,!0),Je.dirtyFields=n.dirtyFields,Re=Re||u.dirtyFields&&ut!==!Z}if(ae){const Z=wt(n.touchedFields,J);Z||(Nr(n.touchedFields,J,ae),Je.touchedFields=n.touchedFields,Re=Re||u.touchedFields&&Z!==ae)}Re&&$e&&d.state.next(Je)}return Re?Je:{}},B=(J,ie,ae,Pe)=>{const $e=wt(n.errors,J),Re=u.isValid&&xl(ie)&&n.isValid!==ie;if(t.delayError&&ae?(c=y(()=>E(J,ae)),c(t.delayError)):(clearTimeout(l),c=null,ae?Nr(n.errors,J,ae):Js(n.errors,J)),(ae?!_g($e,ae):$e)||!Ta(Pe)||Re){const ut={...Pe,...Re&&xl(ie)?{isValid:ie}:{},errors:n.errors,name:J};n={...n,...ut},d.state.next(ut)}},W=async J=>{v(J,!0);const ie=await e.resolver(i,e.context,C4t(J||a.mount,r,e.criteriaMode,e.shouldUseNativeValidation));return v(J),ie},S=async J=>{const{errors:ie}=await W(J);if(J)for(const ae of J){const Pe=wt(ie,ae);Pe?Nr(n.errors,ae,Pe):Js(n.errors,ae)}else n.errors=ie;return ie},$=async(J,ie,ae={valid:!0})=>{for(const Pe in J){const $e=J[Pe];if($e){const{_f:Re,...ut}=$e;if(Re){const Je=a.array.has(Re.name),ft=$e._f&&_4t($e._f);ft&&u.validatingFields&&v([Pe],!0);const Z=await _se($e,i,m,e.shouldUseNativeValidation&&!ie,Je);if(ft&&u.validatingFields&&v([Pe]),Z[Re.name]&&(ae.valid=!1,ie))break;!ie&&(wt(Z,Re.name)?Je?b4t(n.errors,Z,Re.name):Nr(n.errors,Re.name,Z[Re.name]):Js(n.errors,Re.name))}!Ta(ut)&&await $(ut,ie,ae)}}return ae.valid},R=()=>{for(const J of a.unMount){const ie=wt(r,J);ie&&(ie._f.refs?ie._f.refs.every(ae=>!G9(ae)):!G9(ie._f.ref))&&Ee(J)}a.unMount=new Set},M=(J,ie)=>!t.disabled&&(J&&ie&&Nr(i,J,ie),!_g(Y(),s)),j=(J,ie,ae)=>c2e(J,a,{...o.mount?i:_s(ie)?s:Gd(J)?{[J]:ie}:ie},ae,ie),z=J=>Y8(wt(o.mount?i:s,J,t.shouldUnregister?wt(s,J,[]):[])),N=(J,ie,ae={})=>{const Pe=wt(r,J);let $e=ie;if(Pe){const Re=Pe._f;Re&&(!Re.disabled&&Nr(i,J,g2e(ie,Re)),$e=B4(Re.ref)&&Ko(ie)?"":ie,f2e(Re.ref)?[...Re.ref.options].forEach(ut=>ut.selected=$e.includes(ut.value)):Re.refs?Y3(Re.ref)?Re.refs.length>1?Re.refs.forEach(ut=>(!ut.defaultChecked||!ut.disabled)&&(ut.checked=Array.isArray($e)?!!$e.find(Je=>Je===ut.value):$e===ut.value)):Re.refs[0]&&(Re.refs[0].checked=!!$e):Re.refs.forEach(ut=>ut.checked=ut.value===$e):qH(Re.ref)?Re.ref.value="":(Re.ref.value=$e,Re.ref.type||d.values.next({name:J,values:{...i}})))}(ae.shouldDirty||ae.shouldTouch)&&k(J,$e,ae.shouldTouch,ae.shouldDirty,!0),ae.shouldValidate&&H(J)},T=(J,ie,ae)=>{for(const Pe in ie){const $e=ie[Pe],Re=`${J}.${Pe}`,ut=wt(r,Re);(a.array.has(J)||Ms($e)||ut&&!ut._f)&&!Lm($e)?T(Re,$e,ae):N(Re,$e,ae)}},U=(J,ie,ae={})=>{const Pe=wt(r,J),$e=a.array.has(J),Re=Ia(ie);Nr(i,J,Re),$e?(d.array.next({name:J,values:{...i}}),(u.isDirty||u.dirtyFields)&&ae.shouldDirty&&d.state.next({name:J,dirtyFields:R2(s,i),isDirty:M(J,Re)})):Pe&&!Pe._f&&!Ko(Re)?T(J,Re,ae):N(J,Re,ae),bse(J,a)&&d.state.next({...n}),d.values.next({name:o.mount?J:void 0,values:{...i}})},L=async J=>{o.mount=!0;const ie=J.target;let ae=ie.name,Pe=!0;const $e=wt(r,ae),Re=()=>ie.type?Z9($e._f):t2e(J),ut=Je=>{Pe=Number.isNaN(Je)||Lm(Je)&&isNaN(Je.getTime())||_g(Je,wt(i,ae,Je))};if($e){let Je,ft;const Z=Re(),O=J.type===L4.BLUR||J.type===L4.FOCUS_OUT,F=!S4t($e._f)&&!e.resolver&&!wt(n.errors,ae)&&!$e._f.deps||A4t(O,wt(n.touchedFields,ae),n.isSubmitted,p,f),ne=bse(ae,a,O);Nr(i,ae,Z),O?($e._f.onBlur&&$e._f.onBlur(J),c&&c(0)):$e._f.onChange&&$e._f.onChange(J);const he=k(ae,Z,O,!1),Te=!Ta(he)||ne;if(!O&&d.values.next({name:ae,type:J.type,values:{...i}}),F)return u.isValid&&(t.mode==="onBlur"?O&&b():b()),Te&&d.state.next({name:ae,...ne?{}:he});if(!O&&ne&&d.state.next({...n}),e.resolver){const{errors:Fe}=await W([ae]);if(ut(Z),Pe){const Bt=Ase(n.errors,r,ae),vn=Ase(Fe,r,Bt.name||ae);Je=vn.error,ae=vn.name,ft=Ta(Fe)}}else v([ae],!0),Je=(await _se($e,i,m,e.shouldUseNativeValidation))[ae],v([ae]),ut(Z),Pe&&(Je?ft=!1:u.isValid&&(ft=await $(r,!0)));Pe&&($e._f.deps&&H($e._f.deps),B(ae,ft,Je,he))}},P=(J,ie)=>{if(wt(n.errors,ie)&&J.focus)return J.focus(),1},H=async(J,ie={})=>{let ae,Pe;const $e=WE(J);if(e.resolver){const Re=await S(_s(J)?J:$e);ae=Ta(Re),Pe=J?!$e.some(ut=>wt(Re,ut)):ae}else J?(Pe=(await Promise.all($e.map(async Re=>{const ut=wt(r,Re);return await $(ut&&ut._f?{[Re]:ut}:ut)}))).every(Boolean),!(!Pe&&!n.isValid)&&b()):Pe=ae=await $(r);return d.state.next({...!Gd(J)||u.isValid&&ae!==n.isValid?{}:{name:J},...e.resolver||!J?{isValid:ae}:{},errors:n.errors}),ie.shouldFocus&&!Pe&&VE(r,P,J?$e:a.mount),Pe},Y=J=>{const ie={...o.mount?i:s};return _s(J)?ie:Gd(J)?wt(ie,J):J.map(ae=>wt(ie,ae))},re=(J,ie)=>({invalid:!!wt((ie||n).errors,J),isDirty:!!wt((ie||n).dirtyFields,J),error:wt((ie||n).errors,J),isValidating:!!wt(n.validatingFields,J),isTouched:!!wt((ie||n).touchedFields,J)}),de=J=>{J&&WE(J).forEach(ie=>Js(n.errors,ie)),d.state.next({errors:J?n.errors:{}})},fe=(J,ie,ae)=>{const Pe=(wt(r,J,{_f:{}})._f||{}).ref,$e=wt(n.errors,J)||{},{ref:Re,message:ut,type:Je,...ft}=$e;Nr(n.errors,J,{...ft,...ie,ref:Pe}),d.state.next({name:J,errors:n.errors,isValid:!1}),ae&&ae.shouldFocus&&Pe&&Pe.focus&&Pe.focus()},ve=(J,ie)=>_h(J)?d.values.subscribe({next:ae=>J(j(void 0,ie),ae)}):j(J,ie,!0),Ee=(J,ie={})=>{for(const ae of J?WE(J):a.mount)a.mount.delete(ae),a.array.delete(ae),ie.keepValue||(Js(r,ae),Js(i,ae)),!ie.keepError&&Js(n.errors,ae),!ie.keepDirty&&Js(n.dirtyFields,ae),!ie.keepTouched&&Js(n.touchedFields,ae),!ie.keepIsValidating&&Js(n.validatingFields,ae),!e.shouldUnregister&&!ie.keepDefaultValue&&Js(s,ae);d.values.next({values:{...i}}),d.state.next({...n,...ie.keepDirty?{isDirty:M()}:{}}),!ie.keepIsValid&&b()},oe=({disabled:J,name:ie,field:ae,fields:Pe,value:$e})=>{if(xl(J)&&o.mount||J){const Re=J?void 0:_s($e)?Z9(ae?ae._f:wt(Pe,ie)._f):$e;Nr(i,ie,Re),k(ie,Re,!1,!1,!0)}},Oe=(J,ie={})=>{let ae=wt(r,J);const Pe=xl(ie.disabled)||xl(t.disabled);return Nr(r,J,{...ae||{},_f:{...ae&&ae._f?ae._f:{ref:{name:J}},name:J,mount:!0,...ie}}),a.mount.add(J),ae?oe({field:ae,disabled:xl(ie.disabled)?ie.disabled:t.disabled,name:J,value:ie.value}):_(J,!0,ie.value),{...Pe?{disabled:ie.disabled||t.disabled}:{},...e.progressive?{required:!!ie.required,min:O2(ie.min),max:O2(ie.max),minLength:O2(ie.minLength),maxLength:O2(ie.maxLength),pattern:O2(ie.pattern)}:{},name:J,onChange:L,onBlur:L,ref:$e=>{if($e){Oe(J,ie),ae=wt(r,J);const Re=_s($e.value)&&$e.querySelectorAll&&$e.querySelectorAll("input,select,textarea")[0]||$e,ut=E4t(Re),Je=ae._f.refs||[];if(ut?Je.find(ft=>ft===Re):Re===ae._f.ref)return;Nr(r,J,{_f:{...ae._f,...ut?{refs:[...Je.filter(G9),Re,...Array.isArray(wt(s,J))?[{}]:[]],ref:{type:Re.type,name:J}}:{ref:Re}}}),_(J,!1,void 0,Re)}else ae=wt(r,J,{}),ae._f&&(ae._f.mount=!1),(e.shouldUnregister||ie.shouldUnregister)&&!(n2e(a.array,J)&&o.action)&&a.unMount.add(J)}}},je=()=>e.shouldFocusError&&VE(r,P,a.mount),V=J=>{xl(J)&&(d.state.next({disabled:J}),VE(r,(ie,ae)=>{const Pe=wt(r,ae);Pe&&(ie.disabled=Pe._f.disabled||J,Array.isArray(Pe._f.refs)&&Pe._f.refs.forEach($e=>{$e.disabled=Pe._f.disabled||J}))},0,!1))},we=(J,ie)=>async ae=>{let Pe;ae&&(ae.preventDefault&&ae.preventDefault(),ae.persist&&ae.persist());let $e=Ia(i);if(d.state.next({isSubmitting:!0}),e.resolver){const{errors:Re,values:ut}=await W();n.errors=Re,$e=ut}else await $(r);if(Js(n.errors,"root"),Ta(n.errors)){d.state.next({errors:{}});try{await J($e,ae)}catch(Re){Pe=Re}}else ie&&await ie({...n.errors},ae),je(),setTimeout(je);if(d.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Ta(n.errors)&&!Pe,submitCount:n.submitCount+1,errors:n.errors}),Pe)throw Pe},Ae=(J,ie={})=>{wt(r,J)&&(_s(ie.defaultValue)?U(J,Ia(wt(s,J))):(U(J,ie.defaultValue),Nr(s,J,Ia(ie.defaultValue))),ie.keepTouched||Js(n.touchedFields,J),ie.keepDirty||(Js(n.dirtyFields,J),n.isDirty=ie.defaultValue?M(J,Ia(wt(s,J))):M()),ie.keepError||(Js(n.errors,J),u.isValid&&b()),d.state.next({...n}))},Ie=(J,ie={})=>{const ae=J?Ia(J):s,Pe=Ia(ae),$e=Ta(J),Re=$e?s:Pe;if(ie.keepDefaultValues||(s=ae),!ie.keepValues){if(ie.keepDirtyValues){const ut=new Set([...a.mount,...Object.keys(R2(s,i))]);for(const Je of Array.from(ut))wt(n.dirtyFields,Je)?Nr(Re,Je,wt(i,Je)):U(Je,wt(Re,Je))}else{if(WH&&_s(J))for(const ut of a.mount){const Je=wt(r,ut);if(Je&&Je._f){const ft=Array.isArray(Je._f.refs)?Je._f.refs[0]:Je._f.ref;if(B4(ft)){const Z=ft.closest("form");if(Z){Z.reset();break}}}}r={}}i=t.shouldUnregister?ie.keepDefaultValues?Ia(s):{}:Ia(Re),d.array.next({values:{...Re}}),d.values.next({values:{...Re}})}a={mount:ie.keepDirtyValues?a.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},o.mount=!u.isValid||!!ie.keepIsValid||!!ie.keepDirtyValues,o.watch=!!t.shouldUnregister,d.state.next({submitCount:ie.keepSubmitCount?n.submitCount:0,isDirty:$e?!1:ie.keepDirty?n.isDirty:!!(ie.keepDefaultValues&&!_g(J,s)),isSubmitted:ie.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:$e?{}:ie.keepDirtyValues?ie.keepDefaultValues&&i?R2(s,i):n.dirtyFields:ie.keepDefaultValues&&J?R2(s,J):ie.keepDirty?n.dirtyFields:{},touchedFields:ie.keepTouched?n.touchedFields:{},errors:ie.keepErrors?n.errors:{},isSubmitSuccessful:ie.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},ge=(J,ie)=>Ie(_h(J)?J(i):J,ie);return{control:{register:Oe,unregister:Ee,getFieldState:re,handleSubmit:we,setError:fe,_executeSchema:W,_getWatch:j,_getDirty:M,_updateValid:b,_removeUnmounted:R,_updateFieldArray:x,_updateDisabledField:oe,_getFieldArray:z,_reset:Ie,_resetDefaultValues:()=>_h(e.defaultValues)&&e.defaultValues().then(J=>{ge(J,e.resetOptions),d.state.next({isLoading:!1})}),_updateFormState:J=>{n={...n,...J}},_disableForm:V,_subjects:d,_proxyFormState:u,_setErrors:A,get _fields(){return r},get _formValues(){return i},get _state(){return o},set _state(J){o=J},get _defaultValues(){return s},get _names(){return a},set _names(J){a=J},get _formState(){return n},set _formState(J){n=J},get _options(){return e},set _options(J){e={...e,...J}}},trigger:H,register:Oe,handleSubmit:we,watch:ve,setValue:U,getValues:Y,reset:ge,resetField:Ae,clearErrors:de,unregister:Ee,setError:fe,setFocus:(J,ie={})=>{const ae=wt(r,J),Pe=ae&&ae._f;if(Pe){const $e=Pe.refs?Pe.refs[0]:Pe.ref;$e.focus&&($e.focus(),ie.shouldSelect&&$e.select())}},getFieldState:re}}function P4t(t={}){const e=qe.useRef(),n=qe.useRef(),[r,s]=qe.useState({isDirty:!1,isValidating:!1,isLoading:_h(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,defaultValues:_h(t.defaultValues)?void 0:t.defaultValues});e.current||(e.current={...N4t(t),formState:r});const i=e.current.control;return i._options=t,HH({subject:i._subjects.state,next:o=>{o2e(o,i._proxyFormState,i._updateFormState,!0)&&s({...i._formState})}}),qe.useEffect(()=>i._disableForm(t.disabled),[i,t.disabled]),qe.useEffect(()=>{if(i._proxyFormState.isDirty){const o=i._getDirty();o!==r.isDirty&&i._subjects.state.next({isDirty:o})}},[i,r.isDirty]),qe.useEffect(()=>{t.values&&!_g(t.values,n.current)?(i._reset(t.values,i._options.resetOptions),n.current=t.values,s(o=>({...o}))):i._resetDefaultValues()},[t.values,i]),qe.useEffect(()=>{t.errors&&i._setErrors(t.errors)},[t.errors,i]),qe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),qe.useEffect(()=>{t.shouldUnregister&&i._subjects.values.next({values:i._getWatch()})},[t.shouldUnregister,i]),qe.useEffect(()=>{e.current&&(e.current.watch=e.current.watch.bind({}))},[r]),e.current.formState=i2e(r,i),e.current}const Ise=(t,e,n)=>{if(t&&"reportValidity"in t){const r=wt(n,e);t.setCustomValidity(r&&r.message||""),t.reportValidity()}},m2e=(t,e)=>{for(const n in e.fields){const r=e.fields[n];r&&r.ref&&"reportValidity"in r.ref?Ise(r.ref,n,t):r.refs&&r.refs.forEach(s=>Ise(s,n,t))}},k4t=(t,e)=>{e.shouldUseNativeValidation&&m2e(t,e);const n={};for(const r in t){const s=wt(e.fields,r),i=Object.assign(t[r]||{},{ref:s&&s.ref});if(R4t(e.names||Object.keys(t),r)){const o=Object.assign({},wt(n,r));Nr(o,"root",i),Nr(n,r,o)}else Nr(n,r,i)}return n},R4t=(t,e)=>t.some(n=>n.startsWith(e+"."));var O4t=function(t,e){for(var n={};t.length;){var r=t[0],s=r.code,i=r.message,o=r.path.join(".");if(!n[o])if("unionErrors"in r){var a=r.unionErrors[0].errors[0];n[o]={message:a.message,type:a.code}}else n[o]={message:i,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(u){return u.errors.forEach(function(d){return t.push(d)})}),e){var c=n[o].types,l=c&&c[r.code];n[o]=l2e(o,e,n,s,l?[].concat(l,r.message):r.message)}t.shift()}return n},$4t=function(t,e,n){return n===void 0&&(n={}),function(r,s,i){try{return Promise.resolve(function(o,a){try{var c=Promise.resolve(t[n.mode==="sync"?"parse":"parseAsync"](r,e)).then(function(l){return i.shouldUseNativeValidation&&m2e({},i),{errors:{},values:n.raw?r:l}})}catch(l){return a(l)}return c&&c.then?c.then(void 0,a):c}(0,function(o){if(function(a){return Array.isArray(a?.errors)}(o))return{values:{},errors:k4t(O4t(o.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw o}))}catch(o){return Promise.reject(o)}}},sr;(function(t){t.assertEqual=s=>s;function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const i={};for(const o of s)i[o]=o;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(const a of i)o[a]=s[a];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(const o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(sr||(sr={}));var zU;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(zU||(zU={}));const Tt=sr.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Sg=t=>{switch(typeof t){case"undefined":return Tt.undefined;case"string":return Tt.string;case"number":return isNaN(t)?Tt.nan:Tt.number;case"boolean":return Tt.boolean;case"function":return Tt.function;case"bigint":return Tt.bigint;case"symbol":return Tt.symbol;case"object":return Array.isArray(t)?Tt.array:t===null?Tt.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Tt.promise:typeof Map<"u"&&t instanceof Map?Tt.map:typeof Set<"u"&&t instanceof Set?Tt.set:typeof Date<"u"&&t instanceof Date?Tt.date:Tt.object;default:return Tt.unknown}},lt=sr.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),D4t=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class Bc extends Error{constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let a=r,c=0;for(;cn.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bc.create=t=>new Bc(t);const M1=(t,e)=>{let n;switch(t.code){case lt.invalid_type:t.received===Tt.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case lt.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,sr.jsonStringifyReplacer)}`;break;case lt.unrecognized_keys:n=`Unrecognized key(s) in object: ${sr.joinValues(t.keys,", ")}`;break;case lt.invalid_union:n="Invalid input";break;case lt.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${sr.joinValues(t.options)}`;break;case lt.invalid_enum_value:n=`Invalid enum value. Expected ${sr.joinValues(t.options)}, received '${t.received}'`;break;case lt.invalid_arguments:n="Invalid function arguments";break;case lt.invalid_return_type:n="Invalid function return type";break;case lt.invalid_date:n="Invalid date";break;case lt.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:sr.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case lt.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case lt.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case lt.custom:n="Invalid input";break;case lt.invalid_intersection_types:n="Intersection results could not be merged";break;case lt.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case lt.not_finite:n="Number must be finite";break;default:n=e.defaultError,sr.assertNever(t)}return{message:n}};let y2e=M1;function M4t(t){y2e=t}function j4(){return y2e}const z4=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="";const c=r.filter(l=>!!l).slice().reverse();for(const l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},L4t=[];function At(t,e){const n=j4(),r=z4({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===M1?void 0:M1].filter(s=>!!s)});t.common.issues.push(r)}class Do{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return pn;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const i=await s.key,o=await s.value;r.push({key:i,value:o})}return Do.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return pn;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}}const pn=Object.freeze({status:"aborted"}),Yb=t=>({status:"dirty",value:t}),aa=t=>({status:"valid",value:t}),WU=t=>t.status==="aborted",VU=t=>t.status==="dirty",pS=t=>t.status==="valid",gS=t=>typeof Promise<"u"&&t instanceof Promise;function W4(t,e,n,r){if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function w2e(t,e,n,r,s){if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}var Wt;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Wt||(Wt={}));var rE,sE;class bf{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Tse=(t,e)=>{if(pS(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Bc(t.common.issues);return this._error=n,this._error}}};function Pn(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{var c,l;const{message:u}=t;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:(c=u??r)!==null&&c!==void 0?c:a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:(l=u??n)!==null&&l!==void 0?l:a.defaultError}},description:s}}class Fn{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Sg(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Sg(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Do,ctx:{common:e.parent.common,data:e.data,parsedType:Sg(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(gS(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){var r;const s={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Sg(e)},i=this._parseSync({data:e,path:s.path,parent:s});return Tse(s,i)}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Sg(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(gS(s)?s:Promise.resolve(s));return Tse(r,i)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const o=e(s),a=()=>i.addIssue({code:lt.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new ld({schema:this,typeName:cn.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return of.create(this,this._def)}nullable(){return A0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qu.create(this,this._def)}promise(){return B1.create(this,this._def)}or(e){return bS.create([this,e],this._def)}and(e){return vS.create(this,e,this._def)}transform(e){return new ld({...Pn(this._def),schema:this,typeName:cn.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new SS({...Pn(this._def),innerType:this,defaultValue:n,typeName:cn.ZodDefault})}brand(){return new GH({typeName:cn.ZodBranded,type:this,...Pn(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new AS({...Pn(this._def),innerType:this,catchValue:n,typeName:cn.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return X3.create(this,e)}readonly(){return IS.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const B4t=/^c[^\s-]{8,}$/i,U4t=/^[0-9a-z]+$/,F4t=/^[0-9A-HJKMNP-TV-Z]{26}$/,j4t=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,z4t=/^[a-z0-9_-]{21}$/i,W4t=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,V4t=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,H4t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Y9;const q4t=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,K4t=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,G4t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,b2e="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Z4t=new RegExp(`^${b2e}$`);function v2e(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Y4t(t){return new RegExp(`^${v2e(t)}$`)}function x2e(t){let e=`${b2e}T${v2e(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function X4t(t,e){return!!((e==="v4"||!e)&&q4t.test(t)||(e==="v6"||!e)&&K4t.test(t))}class Fu extends Fn{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Tt.string){const i=this._getOrReturnCtx(e);return At(i,{code:lt.invalid_type,expected:Tt.string,received:i.parsedType}),pn}const r=new Do;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.lengthi.value&&(s=this._getOrReturnCtx(e,s),At(s,{code:lt.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.lengthe.test(s),{validation:n,code:lt.invalid_string,...Wt.errToObj(r)})}_addCheck(e){return new Fu({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Wt.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Wt.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Wt.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Wt.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Wt.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Wt.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Wt.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Wt.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Wt.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Wt.errToObj(e)})}datetime(e){var n,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(n=e?.offset)!==null&&n!==void 0?n:!1,local:(r=e?.local)!==null&&r!==void 0?r:!1,...Wt.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Wt.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Wt.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Wt.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...Wt.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Wt.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Wt.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Wt.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Wt.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Wt.errToObj(n)})}nonempty(e){return this.min(1,Wt.errToObj(e))}trim(){return new Fu({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Fu({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Fu({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value{var e;return new Fu({checks:[],typeName:cn.ZodString,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...Pn(t)})};function Q4t(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=parseInt(t.toFixed(s).replace(".","")),o=parseInt(e.toFixed(s).replace(".",""));return i%o/Math.pow(10,s)}class C0 extends Fn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Tt.number){const i=this._getOrReturnCtx(e);return At(i,{code:lt.invalid_type,expected:Tt.number,received:i.parsedType}),pn}let r;const s=new Do;for(const i of this._def.checks)i.kind==="int"?sr.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),At(r,{code:lt.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.datai.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),At(r,{code:lt.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Q4t(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),At(r,{code:lt.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),At(r,{code:lt.not_finite,message:i.message}),s.dirty()):sr.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Wt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Wt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Wt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Wt.toString(n))}setLimit(e,n,r,s){return new C0({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Wt.toString(s)}]})}_addCheck(e){return new C0({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Wt.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Wt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Wt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Wt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Wt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Wt.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Wt.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Wt.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Wt.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.valuee.kind==="int"||e.kind==="multipleOf"&&sr.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.valuenew C0({checks:[],typeName:cn.ZodNumber,coerce:t?.coerce||!1,...Pn(t)});class _0 extends Fn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==Tt.bigint){const i=this._getOrReturnCtx(e);return At(i,{code:lt.invalid_type,expected:Tt.bigint,received:i.parsedType}),pn}let r;const s=new Do;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.datai.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),At(r,{code:lt.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),At(r,{code:lt.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):sr.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Wt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Wt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Wt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Wt.toString(n))}setLimit(e,n,r,s){return new _0({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Wt.toString(s)}]})}_addCheck(e){return new _0({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Wt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Wt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Wt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Wt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Wt.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value{var e;return new _0({checks:[],typeName:cn.ZodBigInt,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...Pn(t)})};class mS extends Fn{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Tt.boolean){const r=this._getOrReturnCtx(e);return At(r,{code:lt.invalid_type,expected:Tt.boolean,received:r.parsedType}),pn}return aa(e.data)}}mS.create=t=>new mS({typeName:cn.ZodBoolean,coerce:t?.coerce||!1,...Pn(t)});class Ky extends Fn{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Tt.date){const i=this._getOrReturnCtx(e);return At(i,{code:lt.invalid_type,expected:Tt.date,received:i.parsedType}),pn}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return At(i,{code:lt.invalid_date}),pn}const r=new Do;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()i.value&&(s=this._getOrReturnCtx(e,s),At(s,{code:lt.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):sr.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ky({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Wt.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Wt.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.valuenew Ky({checks:[],coerce:t?.coerce||!1,typeName:cn.ZodDate,...Pn(t)});class V4 extends Fn{_parse(e){if(this._getType(e)!==Tt.symbol){const r=this._getOrReturnCtx(e);return At(r,{code:lt.invalid_type,expected:Tt.symbol,received:r.parsedType}),pn}return aa(e.data)}}V4.create=t=>new V4({typeName:cn.ZodSymbol,...Pn(t)});class yS extends Fn{_parse(e){if(this._getType(e)!==Tt.undefined){const r=this._getOrReturnCtx(e);return At(r,{code:lt.invalid_type,expected:Tt.undefined,received:r.parsedType}),pn}return aa(e.data)}}yS.create=t=>new yS({typeName:cn.ZodUndefined,...Pn(t)});class wS extends Fn{_parse(e){if(this._getType(e)!==Tt.null){const r=this._getOrReturnCtx(e);return At(r,{code:lt.invalid_type,expected:Tt.null,received:r.parsedType}),pn}return aa(e.data)}}wS.create=t=>new wS({typeName:cn.ZodNull,...Pn(t)});class L1 extends Fn{constructor(){super(...arguments),this._any=!0}_parse(e){return aa(e.data)}}L1.create=t=>new L1({typeName:cn.ZodAny,...Pn(t)});class Qm extends Fn{constructor(){super(...arguments),this._unknown=!0}_parse(e){return aa(e.data)}}Qm.create=t=>new Qm({typeName:cn.ZodUnknown,...Pn(t)});class fp extends Fn{_parse(e){const n=this._getOrReturnCtx(e);return At(n,{code:lt.invalid_type,expected:Tt.never,received:n.parsedType}),pn}}fp.create=t=>new fp({typeName:cn.ZodNever,...Pn(t)});class H4 extends Fn{_parse(e){if(this._getType(e)!==Tt.undefined){const r=this._getOrReturnCtx(e);return At(r,{code:lt.invalid_type,expected:Tt.void,received:r.parsedType}),pn}return aa(e.data)}}H4.create=t=>new H4({typeName:cn.ZodVoid,...Pn(t)});class Qu extends Fn{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==Tt.array)return At(n,{code:lt.invalid_type,expected:Tt.array,received:n.parsedType}),pn;if(s.exactLength!==null){const o=n.data.length>s.exactLength.value,a=n.data.lengths.maxLength.value&&(At(n,{code:lt.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>s.type._parseAsync(new bf(n,o,n.path,a)))).then(o=>Do.mergeArray(r,o));const i=[...n.data].map((o,a)=>s.type._parseSync(new bf(n,o,n.path,a)));return Do.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new Qu({...this._def,minLength:{value:e,message:Wt.toString(n)}})}max(e,n){return new Qu({...this._def,maxLength:{value:e,message:Wt.toString(n)}})}length(e,n){return new Qu({...this._def,exactLength:{value:e,message:Wt.toString(n)}})}nonempty(e){return this.min(1,e)}}Qu.create=(t,e)=>new Qu({type:t,minLength:null,maxLength:null,exactLength:null,typeName:cn.ZodArray,...Pn(e)});function Sb(t){if(t instanceof ms){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=of.create(Sb(r))}return new ms({...t._def,shape:()=>e})}else return t instanceof Qu?new Qu({...t._def,type:Sb(t.element)}):t instanceof of?of.create(Sb(t.unwrap())):t instanceof A0?A0.create(Sb(t.unwrap())):t instanceof vf?vf.create(t.items.map(e=>Sb(e))):t}class ms extends Fn{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=sr.objectKeys(e);return this._cached={shape:e,keys:n}}_parse(e){if(this._getType(e)!==Tt.object){const l=this._getOrReturnCtx(e);return At(l,{code:lt.invalid_type,expected:Tt.object,received:l.parsedType}),pn}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof fp&&this._def.unknownKeys==="strip"))for(const l in s.data)o.includes(l)||a.push(l);const c=[];for(const l of o){const u=i[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new bf(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof fp){const l=this._def.unknownKeys;if(l==="passthrough")for(const u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(At(s,{code:lt.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const u of a){const d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new bf(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const u of c){const d=await u.key,f=await u.value;l.push({key:d,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>Do.mergeObjectSync(r,l)):Do.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return Wt.errToObj,new ms({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var s,i,o,a;const c=(o=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,n,r).message)!==null&&o!==void 0?o:r.defaultError;return n.code==="unrecognized_keys"?{message:(a=Wt.errToObj(e).message)!==null&&a!==void 0?a:c}:{message:c}}}:{}})}strip(){return new ms({...this._def,unknownKeys:"strip"})}passthrough(){return new ms({...this._def,unknownKeys:"passthrough"})}extend(e){return new ms({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ms({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:cn.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new ms({...this._def,catchall:e})}pick(e){const n={};return sr.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new ms({...this._def,shape:()=>n})}omit(e){const n={};return sr.objectKeys(this.shape).forEach(r=>{e[r]||(n[r]=this.shape[r])}),new ms({...this._def,shape:()=>n})}deepPartial(){return Sb(this)}partial(e){const n={};return sr.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}),new ms({...this._def,shape:()=>n})}required(e){const n={};return sr.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof of;)i=i._def.innerType;n[r]=i}}),new ms({...this._def,shape:()=>n})}keyof(){return E2e(sr.objectKeys(this.shape))}}ms.create=(t,e)=>new ms({shape:()=>t,unknownKeys:"strip",catchall:fp.create(),typeName:cn.ZodObject,...Pn(e)});ms.strictCreate=(t,e)=>new ms({shape:()=>t,unknownKeys:"strict",catchall:fp.create(),typeName:cn.ZodObject,...Pn(e)});ms.lazycreate=(t,e)=>new ms({shape:t,unknownKeys:"strip",catchall:fp.create(),typeName:cn.ZodObject,...Pn(e)});class bS extends Fn{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Bc(a.ctx.common.issues));return At(n,{code:lt.invalid_union,unionErrors:o}),pn}if(n.common.async)return Promise.all(r.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i;const o=[];for(const c of r){const l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(c=>new Bc(c));return At(n,{code:lt.invalid_union,unionErrors:a}),pn}}get options(){return this._def.options}}bS.create=(t,e)=>new bS({options:t,typeName:cn.ZodUnion,...Pn(e)});const ah=t=>t instanceof ES?ah(t.schema):t instanceof ld?ah(t.innerType()):t instanceof CS?[t.value]:t instanceof S0?t.options:t instanceof _S?sr.objectValues(t.enum):t instanceof SS?ah(t._def.innerType):t instanceof yS?[void 0]:t instanceof wS?[null]:t instanceof of?[void 0,...ah(t.unwrap())]:t instanceof A0?[null,...ah(t.unwrap())]:t instanceof GH||t instanceof IS?ah(t.unwrap()):t instanceof AS?ah(t._def.innerType):[];class Q8 extends Fn{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Tt.object)return At(n,{code:lt.invalid_type,expected:Tt.object,received:n.parsedType}),pn;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(At(n,{code:lt.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),pn)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const i of n){const o=ah(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new Q8({typeName:cn.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Pn(r)})}}function HU(t,e){const n=Sg(t),r=Sg(e);if(t===e)return{valid:!0,data:t};if(n===Tt.object&&r===Tt.object){const s=sr.objectKeys(e),i=sr.objectKeys(t).filter(a=>s.indexOf(a)!==-1),o={...t,...e};for(const a of i){const c=HU(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(n===Tt.array&&r===Tt.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i{if(WU(i)||WU(o))return pn;const a=HU(i.value,o.value);return a.valid?((VU(i)||VU(o))&&n.dirty(),{status:n.value,value:a.data}):(At(r,{code:lt.invalid_intersection_types}),pn)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}vS.create=(t,e,n)=>new vS({left:t,right:e,typeName:cn.ZodIntersection,...Pn(n)});class vf extends Fn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Tt.array)return At(r,{code:lt.invalid_type,expected:Tt.array,received:r.parsedType}),pn;if(r.data.lengththis._def.items.length&&(At(r,{code:lt.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((o,a)=>{const c=this._def.items[a]||this._def.rest;return c?c._parse(new bf(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Do.mergeArray(n,o)):Do.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new vf({...this._def,rest:e})}}vf.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new vf({items:t,typeName:cn.ZodTuple,rest:null,...Pn(e)})};class xS extends Fn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Tt.object)return At(r,{code:lt.invalid_type,expected:Tt.object,received:r.parsedType}),pn;const s=[],i=this._def.keyType,o=this._def.valueType;for(const a in r.data)s.push({key:i._parse(new bf(r,a,r.path,a)),value:o._parse(new bf(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Do.mergeObjectAsync(n,s):Do.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Fn?new xS({keyType:e,valueType:n,typeName:cn.ZodRecord,...Pn(r)}):new xS({keyType:Fu.create(),valueType:e,typeName:cn.ZodRecord,...Pn(n)})}}class q4 extends Fn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Tt.map)return At(r,{code:lt.invalid_type,expected:Tt.map,received:r.parsedType}),pn;const s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new bf(r,a,r.path,[l,"key"])),value:i._parse(new bf(r,c,r.path,[l,"value"]))}));if(r.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const c of o){const l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return pn;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const c of o){const l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return pn;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}}q4.create=(t,e,n)=>new q4({valueType:e,keyType:t,typeName:cn.ZodMap,...Pn(n)});class Gy extends Fn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Tt.set)return At(r,{code:lt.invalid_type,expected:Tt.set,received:r.parsedType}),pn;const s=this._def;s.minSize!==null&&r.data.sizes.maxSize.value&&(At(r,{code:lt.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function o(c){const l=new Set;for(const u of c){if(u.status==="aborted")return pn;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}const a=[...r.data.values()].map((c,l)=>i._parse(new bf(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,n){return new Gy({...this._def,minSize:{value:e,message:Wt.toString(n)}})}max(e,n){return new Gy({...this._def,maxSize:{value:e,message:Wt.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}Gy.create=(t,e)=>new Gy({valueType:t,minSize:null,maxSize:null,typeName:cn.ZodSet,...Pn(e)});class Ev extends Fn{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Tt.function)return At(n,{code:lt.invalid_type,expected:Tt.function,received:n.parsedType}),pn;function r(a,c){return z4({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,j4(),M1].filter(l=>!!l),issueData:{code:lt.invalid_arguments,argumentsError:c}})}function s(a,c){return z4({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,j4(),M1].filter(l=>!!l),issueData:{code:lt.invalid_return_type,returnTypeError:c}})}const i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof B1){const a=this;return aa(async function(...c){const l=new Bc([]),u=await a._def.args.parseAsync(c,i).catch(p=>{throw l.addIssue(r(c,p)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(p=>{throw l.addIssue(s(d,p)),l})})}else{const a=this;return aa(function(...c){const l=a._def.args.safeParse(c,i);if(!l.success)throw new Bc([r(c,l.error)]);const u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new Bc([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ev({...this._def,args:vf.create(e).rest(Qm.create())})}returns(e){return new Ev({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new Ev({args:e||vf.create([]).rest(Qm.create()),returns:n||Qm.create(),typeName:cn.ZodFunction,...Pn(r)})}}class ES extends Fn{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}ES.create=(t,e)=>new ES({getter:t,typeName:cn.ZodLazy,...Pn(e)});class CS extends Fn{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return At(n,{received:n.data,code:lt.invalid_literal,expected:this._def.value}),pn}return{status:"valid",value:e.data}}get value(){return this._def.value}}CS.create=(t,e)=>new CS({value:t,typeName:cn.ZodLiteral,...Pn(e)});function E2e(t,e){return new S0({values:t,typeName:cn.ZodEnum,...Pn(e)})}class S0 extends Fn{constructor(){super(...arguments),rE.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return At(n,{expected:sr.joinValues(r),received:n.parsedType,code:lt.invalid_type}),pn}if(W4(this,rE)||w2e(this,rE,new Set(this._def.values)),!W4(this,rE).has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return At(n,{received:n.data,code:lt.invalid_enum_value,options:r}),pn}return aa(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return S0.create(e,{...this._def,...n})}exclude(e,n=this._def){return S0.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}rE=new WeakMap;S0.create=E2e;class _S extends Fn{constructor(){super(...arguments),sE.set(this,void 0)}_parse(e){const n=sr.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Tt.string&&r.parsedType!==Tt.number){const s=sr.objectValues(n);return At(r,{expected:sr.joinValues(s),received:r.parsedType,code:lt.invalid_type}),pn}if(W4(this,sE)||w2e(this,sE,new Set(sr.getValidEnumValues(this._def.values))),!W4(this,sE).has(e.data)){const s=sr.objectValues(n);return At(r,{received:r.data,code:lt.invalid_enum_value,options:s}),pn}return aa(e.data)}get enum(){return this._def.values}}sE=new WeakMap;_S.create=(t,e)=>new _S({values:t,typeName:cn.ZodNativeEnum,...Pn(e)});class B1 extends Fn{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Tt.promise&&n.common.async===!1)return At(n,{code:lt.invalid_type,expected:Tt.promise,received:n.parsedType}),pn;const r=n.parsedType===Tt.promise?n.data:Promise.resolve(n.data);return aa(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}B1.create=(t,e)=>new B1({type:t,typeName:cn.ZodPromise,...Pn(e)});class ld extends Fn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===cn.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{At(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async a=>{if(n.value==="aborted")return pn;const c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?pn:c.status==="dirty"||n.value==="dirty"?Yb(c.value):c});{if(n.value==="aborted")return pn;const a=this._def.schema._parseSync({data:o,path:r.path,parent:r});return a.status==="aborted"?pn:a.status==="dirty"||n.value==="dirty"?Yb(a.value):a}}if(s.type==="refinement"){const o=a=>{const c=s.refinement(a,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?pn:(a.status==="dirty"&&n.dirty(),o(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?pn:(a.status==="dirty"&&n.dirty(),o(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!pS(o))return o;const a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>pS(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:n.value,value:a})):o);sr.assertNever(s)}}ld.create=(t,e,n)=>new ld({schema:t,typeName:cn.ZodEffects,effect:e,...Pn(n)});ld.createWithPreprocess=(t,e,n)=>new ld({schema:e,effect:{type:"preprocess",transform:t},typeName:cn.ZodEffects,...Pn(n)});class of extends Fn{_parse(e){return this._getType(e)===Tt.undefined?aa(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}of.create=(t,e)=>new of({innerType:t,typeName:cn.ZodOptional,...Pn(e)});class A0 extends Fn{_parse(e){return this._getType(e)===Tt.null?aa(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}A0.create=(t,e)=>new A0({innerType:t,typeName:cn.ZodNullable,...Pn(e)});class SS extends Fn{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===Tt.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}SS.create=(t,e)=>new SS({innerType:t,typeName:cn.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Pn(e)});class AS extends Fn{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return gS(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bc(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Bc(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}AS.create=(t,e)=>new AS({innerType:t,typeName:cn.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Pn(e)});class K4 extends Fn{_parse(e){if(this._getType(e)!==Tt.nan){const r=this._getOrReturnCtx(e);return At(r,{code:lt.invalid_type,expected:Tt.nan,received:r.parsedType}),pn}return{status:"valid",value:e.data}}}K4.create=t=>new K4({typeName:cn.ZodNaN,...Pn(t)});const J4t=Symbol("zod_brand");class GH extends Fn{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class X3 extends Fn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?pn:i.status==="dirty"?(n.dirty(),Yb(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?pn:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new X3({in:e,out:n,typeName:cn.ZodPipeline})}}class IS extends Fn{_parse(e){const n=this._def.innerType._parse(e),r=s=>(pS(s)&&(s.value=Object.freeze(s.value)),s);return gS(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}IS.create=(t,e)=>new IS({innerType:t,typeName:cn.ZodReadonly,...Pn(e)});function C2e(t,e={},n){return t?L1.create().superRefine((r,s)=>{var i,o;if(!t(r)){const a=typeof e=="function"?e(r):typeof e=="string"?{message:e}:e,c=(o=(i=a.fatal)!==null&&i!==void 0?i:n)!==null&&o!==void 0?o:!0,l=typeof a=="string"?{message:a}:a;s.addIssue({code:"custom",...l,fatal:c})}}):L1.create()}const ePt={object:ms.lazycreate};var cn;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(cn||(cn={}));const tPt=(t,e={message:`Input not instance of ${t.name}`})=>C2e(n=>n instanceof t,e),_2e=Fu.create,S2e=C0.create,nPt=K4.create,rPt=_0.create,A2e=mS.create,sPt=Ky.create,iPt=V4.create,oPt=yS.create,aPt=wS.create,cPt=L1.create,lPt=Qm.create,uPt=fp.create,dPt=H4.create,fPt=Qu.create,hPt=ms.create,pPt=ms.strictCreate,gPt=bS.create,mPt=Q8.create,yPt=vS.create,wPt=vf.create,bPt=xS.create,vPt=q4.create,xPt=Gy.create,EPt=Ev.create,CPt=ES.create,_Pt=CS.create,SPt=S0.create,APt=_S.create,IPt=B1.create,Nse=ld.create,TPt=of.create,NPt=A0.create,PPt=ld.createWithPreprocess,kPt=X3.create,RPt=()=>_2e().optional(),OPt=()=>S2e().optional(),$Pt=()=>A2e().optional(),DPt={string:t=>Fu.create({...t,coerce:!0}),number:t=>C0.create({...t,coerce:!0}),boolean:t=>mS.create({...t,coerce:!0}),bigint:t=>_0.create({...t,coerce:!0}),date:t=>Ky.create({...t,coerce:!0})},MPt=pn;var vI=Object.freeze({__proto__:null,defaultErrorMap:M1,setErrorMap:M4t,getErrorMap:j4,makeIssue:z4,EMPTY_PATH:L4t,addIssueToContext:At,ParseStatus:Do,INVALID:pn,DIRTY:Yb,OK:aa,isAborted:WU,isDirty:VU,isValid:pS,isAsync:gS,get util(){return sr},get objectUtil(){return zU},ZodParsedType:Tt,getParsedType:Sg,ZodType:Fn,datetimeRegex:x2e,ZodString:Fu,ZodNumber:C0,ZodBigInt:_0,ZodBoolean:mS,ZodDate:Ky,ZodSymbol:V4,ZodUndefined:yS,ZodNull:wS,ZodAny:L1,ZodUnknown:Qm,ZodNever:fp,ZodVoid:H4,ZodArray:Qu,ZodObject:ms,ZodUnion:bS,ZodDiscriminatedUnion:Q8,ZodIntersection:vS,ZodTuple:vf,ZodRecord:xS,ZodMap:q4,ZodSet:Gy,ZodFunction:Ev,ZodLazy:ES,ZodLiteral:CS,ZodEnum:S0,ZodNativeEnum:_S,ZodPromise:B1,ZodEffects:ld,ZodTransformer:ld,ZodOptional:of,ZodNullable:A0,ZodDefault:SS,ZodCatch:AS,ZodNaN:K4,BRAND:J4t,ZodBranded:GH,ZodPipeline:X3,ZodReadonly:IS,custom:C2e,Schema:Fn,ZodSchema:Fn,late:ePt,get ZodFirstPartyTypeKind(){return cn},coerce:DPt,any:cPt,array:fPt,bigint:rPt,boolean:A2e,date:sPt,discriminatedUnion:mPt,effect:Nse,enum:SPt,function:EPt,instanceof:tPt,intersection:yPt,lazy:CPt,literal:_Pt,map:vPt,nan:nPt,nativeEnum:APt,never:uPt,null:aPt,nullable:NPt,number:S2e,object:hPt,oboolean:$Pt,onumber:OPt,optional:TPt,ostring:RPt,pipeline:kPt,preprocess:PPt,promise:IPt,record:bPt,set:xPt,strictObject:pPt,string:_2e,symbol:iPt,transformer:Nse,tuple:wPt,undefined:oPt,union:gPt,unknown:lPt,void:dPt,NEVER:MPt,ZodIssueCode:lt,quotelessJson:D4t,ZodError:Bc});const LPt=p4t,I2e=I.createContext({}),X9=({...t})=>w.jsx(I2e.Provider,{value:{name:t.name},children:w.jsx(w4t,{...t})}),J8=()=>{const t=I.useContext(I2e),e=I.useContext(T2e),{getFieldState:n,formState:r}=X8(),s=n(t.name,r);if(!t)throw new Error("useFormField should be used within ");const{id:i}=e;return{id:i,name:t.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...s}},T2e=I.createContext({}),y6=I.forwardRef(({className:t,...e},n)=>{const r=I.useId();return w.jsx(T2e.Provider,{value:{id:r},children:w.jsx("div",{ref:n,className:Dt("space-y-2",t),...e})})});y6.displayName="FormItem";const w6=I.forwardRef(({className:t,...e},n)=>{const{error:r,formItemId:s}=J8();return w.jsx(Cg,{ref:n,className:Dt(r&&"text-destructive",t),htmlFor:s,...e})});w6.displayName="FormLabel";const b6=I.forwardRef(({...t},e)=>{const{error:n,formItemId:r,formDescriptionId:s,formMessageId:i}=J8();return w.jsx(Fh,{ref:e,id:r,"aria-describedby":n?`${s} ${i}`:`${s}`,"aria-invalid":!!n,...t})});b6.displayName="FormControl";const BPt=I.forwardRef(({className:t,...e},n)=>{const{formDescriptionId:r}=J8();return w.jsx("p",{ref:n,id:r,className:Dt("text-sm text-muted-foreground",t),...e})});BPt.displayName="FormDescription";const v6=I.forwardRef(({className:t,children:e,...n},r)=>{const{error:s,formMessageId:i}=J8(),o=s?String(s?.message):e;return o?w.jsx("p",{ref:r,id:i,className:Dt("text-sm font-medium text-destructive",t),...n,children:o}):null});v6.displayName="FormMessage";async function UPt(t,e=5e3){try{const n=new AbortController,r=setTimeout(()=>n.abort(),e),s=await fetch(t,{method:"HEAD",signal:n.signal,cache:"no-cache"});return clearTimeout(r),s.ok}catch{return!1}}const FPt=vI.object({title:vI.string().min(3,"Cell name must be at least 3 characters").max(50,"Cell name must be less than 50 characters"),description:vI.string().min(10,"Description must be at least 10 characters").max(500,"Description must be less than 500 characters"),icon:vI.string().optional().refine(t=>t?UPt(t):!0,{message:"Icon must be a valid URL"})});function N2e({open:t,onOpenChange:e}={}){const{createCell:n,isCreatingCell:r}=_p(),{canCreateCell:s}=Cp(),{toast:i}=xf(),[o,a]=qe.useState(!1),c=t??o,l=e??a,u=P4t({resolver:$4t(FPt),defaultValues:{title:"",description:"",icon:""}}),d=async f=>{if(!s){i({title:"Permission Denied",description:"You need to verify Ordinal ownership to create cells.",variant:"destructive"});return}await n(f.title,f.description,f.icon)&&(u.reset(),l(!1))};return w.jsxs($H,{open:c,onOpenChange:l,children:[w.jsx(DU,{asChild:!0,children:w.jsx(fn,{className:"bg-cyber-accent hover:bg-cyber-accent/80",children:"Create Cell"})}),w.jsxs(B8,{className:"sm:max-w-md bg-cyber-dark border-cyber-muted",children:[w.jsx(U8,{children:w.jsx(F8,{className:"text-glow",children:"Create New Cell"})}),w.jsx(LPt,{...u,children:w.jsxs("form",{onSubmit:u.handleSubmit(d),className:"space-y-4",children:[w.jsx(X9,{control:u.control,name:"title",render:({field:f})=>w.jsxs(y6,{children:[w.jsx(w6,{children:"Cell Name"}),w.jsx(b6,{children:w.jsx(hS,{placeholder:"Enter cell name",className:"bg-cyber-muted/50 border-cyber-muted",disabled:r,...f})}),w.jsx(v6,{})]})}),w.jsx(X9,{control:u.control,name:"description",render:({field:f})=>w.jsxs(y6,{children:[w.jsx(w6,{children:"Description"}),w.jsx(b6,{children:w.jsx(j8,{placeholder:"Describe your cell",className:"bg-cyber-muted/50 border-cyber-muted resize-none",disabled:r,...f})}),w.jsx(v6,{})]})}),w.jsx(X9,{control:u.control,name:"icon",render:({field:f})=>w.jsxs(y6,{children:[w.jsx(w6,{children:"Icon URL (Optional)"}),w.jsx(b6,{children:w.jsx(hS,{placeholder:"https://example.com/icon.png",className:"bg-cyber-muted/50 border-cyber-muted",disabled:r,...f})}),w.jsx(v6,{})]})}),w.jsxs("div",{className:"flex justify-end gap-3",children:[w.jsx(fn,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:r,children:"Cancel"}),w.jsx(fn,{type:"submit",disabled:r||!s,className:"bg-cyber-accent hover:bg-cyber-accent/80",children:r?w.jsxs(w.Fragment,{children:[w.jsx(Xd,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Cell"})]})]})})]})]})}const jPt=({canCreateCell:t})=>w.jsxs("div",{className:"col-span-2 flex flex-col items-center justify-center py-16 px-4",children:[w.jsxs("div",{className:"relative mb-8",children:[w.jsx("div",{className:"w-32 h-32 bg-cyber-muted/20 border border-cyber-muted/30 rounded-lg flex items-center justify-center",children:w.jsx(QM,{className:"w-16 h-16 text-cyber-accent/50"})}),w.jsx("div",{className:"absolute -top-2 -right-2 w-6 h-6 bg-cyber-accent/20 border border-cyber-accent/30 rounded-full flex items-center justify-center",children:w.jsx(xae,{className:"w-3 h-3 text-cyber-accent"})}),w.jsx("div",{className:"absolute -bottom-2 -left-2 w-6 h-6 bg-green-500/20 border border-green-500/30 rounded-full flex items-center justify-center",children:w.jsx(zh,{className:"w-3 h-3 text-green-400"})})]}),w.jsxs("div",{className:"text-center max-w-2xl",children:[w.jsx("h2",{className:"text-2xl font-mono font-bold text-white mb-4",children:"No Cells Found"}),t?w.jsxs("div",{className:"space-y-4",children:[w.jsx("p",{className:"text-cyber-neutral",children:"Ready to start your own decentralized community?"}),w.jsx(N2e,{})]}):w.jsx("div",{className:"p-4 bg-orange-500/10 border border-orange-500/30 rounded-md",children:w.jsx("p",{className:"text-orange-400 text-sm",children:"Connect your wallet and verify ownership to create cells"})})]})]}),zPt=({cell:t})=>{const e=V8(t.id);return w.jsx(ks,{to:`/cell/${t.id}`,className:"group block board-card",children:w.jsxs("div",{className:"flex items-start gap-4",children:[w.jsx(DH,{src:t.icon,alt:t.name,className:"w-12 h-12 object-cover rounded-sm border border-cyber-muted flex-shrink-0",generateUniqueFallback:!0}),w.jsxs("div",{className:"flex-1 min-w-0",children:[w.jsxs("div",{className:"flex items-start justify-between mb-2",children:[w.jsx("h2",{className:"text-lg font-bold text-glow group-hover:text-cyber-accent transition-colors line-clamp-1",children:t.name}),t.relevanceScore!==void 0&&w.jsx(MH,{score:t.relevanceScore,details:t.relevanceDetails,type:"cell",className:"ml-2 flex-shrink-0",showTooltip:!0})]}),e.isPending&&w.jsx("div",{className:"mb-2",children:w.jsx("span",{className:"px-2 py-0.5 rounded-sm bg-yellow-500/20 text-yellow-400 border border-yellow-500/30 text-xs",children:"syncing…"})}),w.jsx("p",{className:"text-cyber-neutral text-sm mb-3 line-clamp-2",children:t.description}),w.jsx("div",{className:"flex items-center justify-between text-xs text-cyber-neutral",children:w.jsxs("div",{className:"flex items-center gap-4",children:[w.jsxs("span",{className:"flex items-center gap-1",children:[w.jsx(s0,{className:"w-3 h-3"}),t.postCount||0," posts"]}),w.jsxs("span",{className:"flex items-center gap-1",children:[w.jsx(Eae,{className:"w-3 h-3"}),t.activeMemberCount||0," members"]})]})})]})]})})},WPt=()=>{const{cellsWithStats:t,isInitialLoading:e}=wd(),{refreshData:n}=_p(),{canCreateCell:r}=Cp(),[s,i]=I.useState("relevance"),o=I.useMemo(()=>l4t(t,s),[t,s]);if(e)return w.jsxs("div",{className:"container mx-auto px-4 pt-24 pb-16 text-center",children:[w.jsx(Xd,{className:"w-8 h-8 mx-auto mb-4 animate-spin text-primary"}),w.jsx("p",{className:"text-lg font-medium text-muted-foreground",children:"Loading Cells..."})]});const a=o.length>0;return w.jsxs("div",{className:"page-main",children:[w.jsx("div",{className:"page-header",children:w.jsxs("div",{className:"flex justify-between items-center",children:[w.jsxs("div",{children:[w.jsx("h1",{className:"page-title",children:"Decentralized Cells"}),w.jsx("p",{className:"page-subtitle",children:"Discover communities built on Bitcoin Ordinals"})]}),a&&w.jsxs("div",{className:"flex items-center gap-4",children:[w.jsx(Qxe,{}),w.jsxs(FH,{value:s,onValueChange:c=>i(c),children:[w.jsx(G8,{className:"w-40 bg-cyber-muted/50 border-cyber-muted text-cyber-light",children:w.jsx(jH,{})}),w.jsxs(Z8,{className:"bg-cyber-dark border-cyber-muted/30",children:[w.jsxs(Ch,{value:"relevance",className:"text-cyber-light hover:bg-cyber-muted/30",children:[w.jsx(lC,{className:"w-4 h-4 mr-2 inline"}),"Relevance"]}),w.jsxs(Ch,{value:"activity",className:"text-cyber-light hover:bg-cyber-muted/30",children:[w.jsx(s0,{className:"w-4 h-4 mr-2 inline"}),"Activity"]}),w.jsxs(Ch,{value:"newest",className:"text-cyber-light hover:bg-cyber-muted/30",children:[w.jsx(W1,{className:"w-4 h-4 mr-2 inline"}),"Newest"]}),w.jsxs(Ch,{value:"alphabetical",className:"text-cyber-light hover:bg-cyber-muted/30",children:[w.jsx(Eae,{className:"w-4 h-4 mr-2 inline"}),"A-Z"]})]})]}),w.jsx(fn,{variant:"outline",size:"icon",onClick:n,disabled:e,title:"Refresh data",className:"px-3 border-cyber-muted/30 text-cyber-neutral hover:bg-cyber-muted/30",children:w.jsx(HF,{className:`w-4 h-4 ${e?"animate-spin":""}`})}),r&&w.jsx(N2e,{})]})]})}),w.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:a?o.map(c=>w.jsx(zPt,{cell:c},c.id)):w.jsx(jPt,{canCreateCell:r})})]})},VPt=()=>{const{health:t}=_At(),{refreshData:e}=_p();return w.jsxs("div",{className:"page-container",children:[w.jsx(Kd,{}),w.jsxs("main",{className:"page-content relative",children:[w.jsx(WPt,{}),!t.isConnected&&w.jsx("div",{className:"fixed bottom-4 right-4",children:w.jsxs(fn,{onClick:e,variant:"destructive",className:"flex items-center gap-2 shadow-lg animate-pulse",children:[w.jsx(LNe,{className:"w-4 h-4"}),"Reconnect"]})})]}),w.jsx("footer",{className:"page-footer",children:w.jsx("p",{children:"OpChan - A decentralized forum built on Waku & Bitcoin Ordinals"})})]})};function HPt(){const{updateProfile:t}=CAt(),{refreshData:e}=_p(),{toast:n}=xf(),{currentUser:r,verificationStatus:s}=_i(),{getDelegationStatus:i}=Qc(),{delegationStatus:o}=Pbe(),[a,c]=I.useState(null),l=r?.address;I.useEffect(()=>{i().then(c).catch(console.error)},[i]);const u=H3(l||""),[d,f]=I.useState(!1),[p,m]=I.useState(!1),[y,b]=I.useState(""),[v,x]=I.useState(_l.WALLET_ADDRESS),[E,A]=I.useState(!1);I.useEffect(()=>{if(r){const R=u.callSign||r.callSign||"",M=u.displayPreference||r.displayPreference||_l.WALLET_ADDRESS;b(R),x(M)}},[r,u.callSign,u.displayPreference]);const _=async(R,M)=>{try{await navigator.clipboard.writeText(R),n({title:"Copied!",description:`${M} copied to clipboard`})}catch{n({title:"Copy Failed",description:"Failed to copy to clipboard",variant:"destructive"})}};if(!r)return w.jsxs("div",{className:"min-h-screen flex flex-col bg-cyber-dark text-white",children:[w.jsx(Kd,{}),w.jsx("main",{className:"flex-1 flex items-center justify-center pt-16",children:w.jsx(Yu,{className:"w-full max-w-md bg-cyber-muted/20 border-cyber-muted/30",children:w.jsx(Xu,{className:"pt-6",children:w.jsxs("div",{className:"text-center text-cyber-neutral",children:[w.jsx(gE,{className:"w-12 h-12 mx-auto mb-4 text-cyber-accent"}),w.jsx("h2",{className:"text-xl font-mono font-bold mb-2",children:"Connect Required"}),w.jsx("p",{className:"text-sm",children:"Please connect your wallet to view your profile."})]})})})})]});const k=async()=>{if(!y.trim()){n({title:"Invalid Input",description:"Call sign cannot be empty.",variant:"destructive"});return}if(y.length<3||y.length>20){n({title:"Invalid Call Sign",description:"Call sign must be between 3 and 20 characters.",variant:"destructive"});return}if(!/^[a-zA-Z0-9_-]+$/.test(y)){n({title:"Invalid Call Sign",description:"Call sign can only contain letters, numbers, underscores, and hyphens.",variant:"destructive"});return}m(!0);try{await t({callSign:y.trim(),displayPreference:v})&&(await e(),f(!1),n({title:"Profile Updated",description:"Your profile has been updated successfully."}))}catch{n({title:"Update Failed",description:"Failed to update profile. Please try again.",variant:"destructive"})}finally{m(!1)}},B=()=>{const R=u.callSign||r.callSign||"",M=u.displayPreference||r.displayPreference||_l.WALLET_ADDRESS;b(R),x(M),f(!1)},W=()=>{switch(s){case Ct.ENS_ORDINAL_VERIFIED:return w.jsx(cC,{className:"h-4 w-4 text-green-500"});case Ct.WALLET_CONNECTED:return w.jsx(zh,{className:"h-4 w-4 text-blue-500"});case Ct.WALLET_UNCONNECTED:return w.jsx(G6,{className:"h-4 w-4 text-yellow-500"});default:return w.jsx(ENe,{className:"h-4 w-4 text-red-500"})}},S=()=>{switch(s){case Ct.ENS_ORDINAL_VERIFIED:return"Owns ENS or Ordinal";case Ct.WALLET_CONNECTED:return"Connected Wallet";case Ct.WALLET_UNCONNECTED:return"Unconnected Wallet";default:return"Unknown"}},$=()=>{switch(s){case Ct.ENS_ORDINAL_VERIFIED:return"bg-green-100 text-green-800 border-green-200";case Ct.WALLET_CONNECTED:return"bg-blue-100 text-blue-800 border-blue-200";case Ct.WALLET_UNCONNECTED:return"bg-yellow-100 text-yellow-800 border-yellow-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}};return w.jsxs("div",{className:"page-container",children:[w.jsx(Kd,{}),w.jsx("main",{className:"page-content",children:w.jsxs("div",{className:"page-main",children:[w.jsxs("div",{className:"page-header",children:[w.jsx("h1",{className:"page-title",children:"Profile"}),w.jsx("p",{className:"page-subtitle",children:"Manage your account settings and preferences"})]}),w.jsxs("div",{className:"grid-main-sidebar content-spacing",children:[w.jsx("div",{className:"grid-main-content",children:w.jsxs(Yu,{className:"content-card",children:[w.jsx(sf,{children:w.jsxs(Dh,{className:"flex items-center justify-between text-white",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(gE,{className:"h-5 w-5 text-cyber-accent"}),"User Profile"]}),!d&&w.jsxs(fn,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"border-cyber-muted/30 text-cyber-neutral hover:bg-cyber-muted/30",children:[w.jsx(kNe,{className:"w-4 h-4 mr-2"}),"Edit"]})]})}),w.jsxs(Xu,{className:"space-y-6",children:[w.jsx("div",{className:"space-y-4",children:w.jsxs("div",{className:"flex items-center gap-4",children:[w.jsx("div",{className:"w-16 h-16 bg-cyber-accent/20 border border-cyber-accent/30 rounded-lg flex items-center justify-center",children:w.jsx(gE,{className:"w-8 h-8 text-cyber-accent"})}),w.jsxs("div",{className:"flex-1",children:[w.jsx("div",{className:"text-xl font-mono font-bold text-white",children:u.displayName}),w.jsx("div",{className:"text-sm text-cyber-neutral",children:r.ensDetails?.ensName||"No ENS name"}),w.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[W(),w.jsx(Ao,{className:$(),children:S()})]})]})]})}),w.jsxs("div",{className:"space-y-3",children:[w.jsx("h3",{className:"text-sm font-medium text-cyber-neutral uppercase tracking-wide",children:"Wallet Information"}),w.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[w.jsxs("div",{className:"space-y-2",children:[w.jsx(Cg,{className:"text-sm font-medium text-cyber-neutral",children:"Address"}),w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsxs("div",{className:"flex-1 font-mono text-sm bg-cyber-dark/50 border border-cyber-muted/30 px-3 py-2 rounded-md text-cyber-light",children:[r.address.slice(0,8),"...",r.address.slice(-6)]}),w.jsx(fn,{variant:"outline",size:"sm",onClick:()=>_(r.address,"Address"),className:"border-cyber-muted/30 text-cyber-neutral hover:bg-cyber-muted/30",children:w.jsx(LZ,{className:"w-4 h-4"})})]})]}),w.jsxs("div",{className:"space-y-2",children:[w.jsx(Cg,{className:"text-sm font-medium text-cyber-neutral",children:"Network"}),w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(INe,{className:"w-4 h-4 text-cyber-neutral"}),w.jsx(Ao,{variant:"outline",className:"capitalize bg-cyber-accent/20 text-cyber-accent border-cyber-accent/30",children:r.walletType})]})]})]})]}),w.jsxs("div",{className:"space-y-3",children:[w.jsx("h3",{className:"text-sm font-medium text-cyber-neutral uppercase tracking-wide",children:"Profile Settings"}),w.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[w.jsxs("div",{className:"space-y-2",children:[w.jsx(Cg,{htmlFor:"callSign",className:"text-sm font-medium text-cyber-neutral",children:"Call Sign"}),d?w.jsx(hS,{id:"callSign",value:y,onChange:R=>b(R.target.value),placeholder:"Enter your call sign",className:"bg-cyber-dark/50 border-cyber-muted/30 text-cyber-light",disabled:p}):w.jsx("div",{className:"text-sm bg-cyber-dark/50 border border-cyber-muted/30 px-3 py-2 rounded-md text-cyber-light",children:u.callSign||r.callSign||"Not set"}),w.jsx("p",{className:"text-xs text-cyber-neutral",children:"3-20 characters, letters, numbers, underscores, and hyphens only"})]}),w.jsxs("div",{className:"space-y-2",children:[w.jsx(Cg,{htmlFor:"displayPreference",className:"text-sm font-medium text-cyber-neutral",children:"Display Preference"}),d?w.jsxs(FH,{value:v,onValueChange:R=>x(R),disabled:p,children:[w.jsx(G8,{className:"bg-cyber-dark/50 border-cyber-muted/30 text-cyber-light",children:w.jsx(jH,{})}),w.jsxs(Z8,{className:"bg-cyber-dark border-cyber-muted/30",children:[w.jsx(Ch,{value:_l.CALL_SIGN,className:"text-cyber-light hover:bg-cyber-muted/30",children:"Call Sign (when available)"}),w.jsx(Ch,{value:_l.WALLET_ADDRESS,className:"text-cyber-light hover:bg-cyber-muted/30",children:"Wallet Address"})]})]}):w.jsx("div",{className:"text-sm bg-cyber-dark/50 border border-cyber-muted/30 px-3 py-2 rounded-md text-cyber-light",children:(u.displayPreference||v)===_l.CALL_SIGN?"Call Sign (when available)":"Wallet Address"})]})]})]}),d&&w.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t border-cyber-muted/30",children:[w.jsxs(fn,{variant:"outline",onClick:B,disabled:p,className:"border-cyber-muted/30 text-cyber-neutral hover:bg-cyber-muted/30",children:[w.jsx(wP,{className:"w-4 h-4 mr-2"}),"Cancel"]}),w.jsxs(fn,{onClick:k,disabled:p,className:"bg-cyber-accent hover:bg-cyber-accent/80 text-black font-mono",children:[p?w.jsx(Xd,{className:"mr-2 h-4 w-4 animate-spin"}):w.jsx(RNe,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]})]})}),w.jsx("div",{className:"grid-sidebar",children:w.jsxs(Yu,{className:"content-card",children:[w.jsx(sf,{children:w.jsxs(Dh,{className:"flex items-center justify-between text-white",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(zh,{className:"h-5 w-5 text-cyber-accent"}),"Security"]}),(o.hasDelegation||a?.hasDelegation)&&w.jsxs(fn,{variant:"outline",size:"sm",onClick:()=>A(!0),className:"border-cyber-muted/30 text-cyber-neutral hover:bg-cyber-muted/30",children:[w.jsx(JM,{className:"w-4 h-4 mr-2"}),o.isValid||a?.isValid?"Renew":"Setup"]})]})}),w.jsxs(Xu,{className:"space-y-4",children:[w.jsxs("div",{className:"space-y-3",children:[w.jsxs("div",{className:"flex items-center justify-between",children:[w.jsx("span",{className:"text-sm font-medium text-cyber-neutral",children:"Delegation"}),w.jsx(Ao,{variant:o.isValid||a?.isValid?"default":"secondary",className:o.isValid||a?.isValid?"bg-green-500/20 text-green-400 border-green-500/30":"bg-red-500/20 text-red-400 border-red-500/30",children:o.isValid||a?.isValid?"Active":"Inactive"})]}),(o.expiresAt||r.delegationExpiry)&&w.jsxs("div",{className:"space-y-1",children:[w.jsx("span",{className:"text-xs text-cyber-neutral",children:"Valid until"}),w.jsx("div",{className:"text-sm font-mono text-cyber-light",children:(o.expiresAt||new Date(r.delegationExpiry)).toLocaleDateString()})]}),w.jsxs("div",{className:"flex items-center justify-between",children:[w.jsx("span",{className:"text-sm font-medium text-cyber-neutral",children:"Signature"}),w.jsx(Ao,{variant:"outline",className:o.isValid||r.delegationSignature==="valid"?"text-green-400 border-green-500/30 bg-green-500/10":"text-red-400 border-red-500/30 bg-red-500/10",children:o.isValid||r.delegationSignature==="valid"?"Valid":"Not signed"})]})]}),w.jsxs("div",{className:"space-y-2",children:[w.jsx(Cg,{className:"text-sm font-medium text-cyber-neutral",children:"Browser Public Key"}),w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx("div",{className:"flex-1 font-mono text-xs bg-cyber-dark/50 border border-cyber-muted/30 px-2 py-1 rounded text-cyber-light",children:o.publicKey||r.browserPubKey?`${(o.publicKey||r.browserPubKey).slice(0,12)}...${(o.publicKey||r.browserPubKey).slice(-8)}`:"Not delegated"}),(o.publicKey||r.browserPubKey)&&w.jsx(fn,{variant:"outline",size:"sm",onClick:()=>_(o.publicKey||r.browserPubKey,"Public Key"),className:"border-cyber-muted/30 text-cyber-neutral hover:bg-cyber-muted/30",children:w.jsx(LZ,{className:"w-3 h-3"})})]})]}),!o.isValid&&o.hasDelegation||!a?.isValid&&a?.hasDelegation&&w.jsx("div",{className:"p-3 bg-orange-500/10 border border-orange-500/30 rounded-md",children:w.jsxs("div",{className:"flex items-center gap-2 text-orange-400",children:[w.jsx(G6,{className:"w-4 h-4"}),w.jsx("span",{className:"text-xs font-medium",children:"Delegation expired. Renew to continue using your browser key."})]})})]})]})})]})]})}),w.jsx("footer",{className:"page-footer",children:w.jsx("p",{children:"OpChan - A decentralized forum built on Waku & Bitcoin Ordinals"})}),w.jsx(nxe,{open:E,onOpenChange:A,onComplete:()=>A(!1)})]})}function qPt({bookmark:t,onRemove:e,onNavigate:n,className:r}){const s=H3(t.author||""),i=NP(),o=()=>{n?n(t):t.type===Dc.POST?i(`/post/${t.targetId}`):t.type===Dc.COMMENT&&t.postId&&i(`/post/${t.postId}#comment-${t.targetId}`)},a=c=>{c.stopPropagation(),e(t.id)};return w.jsxs(Yu,{className:Dt("group cursor-pointer transition-all duration-200 hover:bg-cyber-muted/20 hover:border-cyber-accent/30",r),onClick:o,children:[w.jsx(sf,{className:"pb-3",children:w.jsxs("div",{className:"flex items-start justify-between gap-3",children:[w.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[t.type===Dc.POST?w.jsx(XM,{size:16,className:"text-cyber-accent flex-shrink-0"}):w.jsx(s0,{size:16,className:"text-cyber-accent flex-shrink-0"}),w.jsx(Ao,{variant:"outline",className:"text-xs border-cyber-accent/30 text-cyber-accent",children:t.type===Dc.POST?"Post":"Comment"})]}),w.jsx(fn,{variant:"ghost",size:"sm",onClick:a,className:"opacity-0 group-hover:opacity-100 transition-opacity h-8 w-8 p-0 text-cyber-neutral hover:text-red-400",title:"Remove bookmark",children:w.jsx(yP,{size:14})})]})}),w.jsx(Xu,{className:"pt-0",children:w.jsxs("div",{className:"space-y-3",children:[w.jsx("div",{children:w.jsx("h3",{className:"font-medium text-cyber-light line-clamp-2",children:t.title||"Untitled"})}),w.jsxs("div",{className:"flex items-center justify-between text-sm text-cyber-neutral",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx("span",{children:"by"}),w.jsx("span",{className:"font-medium text-cyber-light",children:s.displayName})]}),w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx("span",{children:G3(new Date(t.createdAt),{addSuffix:!0})}),w.jsx(SNe,{size:12,className:"opacity-50"})]})]}),t.cellId&&w.jsxs("div",{className:"text-xs text-cyber-neutral",children:["Cell: ",t.cellId]})]})})]})}function Q9({bookmarks:t,onRemove:e,onNavigate:n,emptyMessage:r="No bookmarks yet",className:s}){return t.length===0?w.jsxs("div",{className:Dt("flex flex-col items-center justify-center py-12 text-center",s),children:[w.jsx(Fm,{size:48,className:"text-cyber-neutral/50 mb-4"}),w.jsx("h3",{className:"text-lg font-medium text-cyber-light mb-2",children:r}),w.jsx("p",{className:"text-cyber-neutral max-w-md",children:"Bookmark posts and comments you want to revisit later. Your bookmarks are saved locally and won't be shared."})]}):w.jsx("div",{className:Dt("space-y-4",s),children:t.map(i=>w.jsx(qPt,{bookmark:i,onRemove:e,onNavigate:n},i.id))})}var ZH="Tabs",[KPt,e9t]=pp(ZH,[k8]),P2e=k8(),[GPt,YH]=KPt(ZH),k2e=I.forwardRef((t,e)=>{const{__scopeTabs:n,value:r,onValueChange:s,defaultValue:i,orientation:o="horizontal",dir:a,activationMode:c="automatic",...l}=t,u=T8(a),[d,f]=jh({prop:r,onChange:s,defaultProp:i});return w.jsx(GPt,{scope:n,baseId:Wu(),value:d,onValueChange:f,orientation:o,dir:u,activationMode:c,children:w.jsx(gn.div,{dir:u,"data-orientation":o,...l,ref:e})})});k2e.displayName=ZH;var R2e="TabsList",O2e=I.forwardRef((t,e)=>{const{__scopeTabs:n,loop:r=!0,...s}=t,i=YH(R2e,n),o=P2e(n);return w.jsx(Lbe,{asChild:!0,...o,orientation:i.orientation,dir:i.dir,loop:r,children:w.jsx(gn.div,{role:"tablist","aria-orientation":i.orientation,...s,ref:e})})});O2e.displayName=R2e;var $2e="TabsTrigger",D2e=I.forwardRef((t,e)=>{const{__scopeTabs:n,value:r,disabled:s=!1,...i}=t,o=YH($2e,n),a=P2e(n),c=B2e(o.baseId,r),l=U2e(o.baseId,r),u=r===o.value;return w.jsx(Bbe,{asChild:!0,...a,focusable:!s,active:u,children:w.jsx(gn.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":l,"data-state":u?"active":"inactive","data-disabled":s?"":void 0,disabled:s,id:c,...i,ref:e,onMouseDown:vt(t.onMouseDown,d=>{!s&&d.button===0&&d.ctrlKey===!1?o.onValueChange(r):d.preventDefault()}),onKeyDown:vt(t.onKeyDown,d=>{[" ","Enter"].includes(d.key)&&o.onValueChange(r)}),onFocus:vt(t.onFocus,()=>{const d=o.activationMode!=="manual";!u&&!s&&d&&o.onValueChange(r)})})})});D2e.displayName=$2e;var M2e="TabsContent",L2e=I.forwardRef((t,e)=>{const{__scopeTabs:n,value:r,forceMount:s,children:i,...o}=t,a=YH(M2e,n),c=B2e(a.baseId,r),l=U2e(a.baseId,r),u=r===a.value,d=I.useRef(u);return I.useEffect(()=>{const f=requestAnimationFrame(()=>d.current=!1);return()=>cancelAnimationFrame(f)},[]),w.jsx(ud,{present:s||u,children:({present:f})=>w.jsx(gn.div,{"data-state":u?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":c,hidden:!f,id:l,tabIndex:0,...o,ref:e,style:{...t.style,animationDuration:d.current?"0s":void 0},children:f&&i})})});L2e.displayName=M2e;function B2e(t,e){return`${t}-trigger-${e}`}function U2e(t,e){return`${t}-content-${e}`}var ZPt=k2e,F2e=O2e,j2e=D2e,z2e=L2e;const YPt=ZPt,W2e=I.forwardRef(({className:t,...e},n)=>w.jsx(F2e,{ref:n,className:Dt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...e}));W2e.displayName=F2e.displayName;const x6=I.forwardRef(({className:t,...e},n)=>w.jsx(j2e,{ref:n,className:Dt("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),...e}));x6.displayName=j2e.displayName;const E6=I.forwardRef(({className:t,...e},n)=>w.jsx(z2e,{ref:n,className:Dt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...e}));E6.displayName=z2e.displayName;const XPt=()=>{const{currentUser:t}=Qc(),e=NP(),{bookmarks:n,loading:r,error:s,removeBookmark:i,getBookmarksByType:o,clearAllBookmarks:a}=yAt(),[c,l]=I.useState("all");if(!t)return w.jsxs("div",{className:"min-h-screen flex flex-col bg-cyber-dark text-white",children:[w.jsx(Kd,{}),w.jsx("main",{className:"flex-1 flex items-center justify-center",children:w.jsxs("div",{className:"text-center",children:[w.jsx("h1",{className:"text-2xl font-bold text-cyber-light mb-4",children:"Authentication Required"}),w.jsx("p",{className:"text-cyber-neutral",children:"Please connect your wallet to view your bookmarks."})]})})]});const u=o(Dc.POST),d=o(Dc.COMMENT),f=()=>{switch(c){case"posts":return u;case"comments":return d;default:return n}},p=y=>{y.type===Dc.POST?e(`/post/${y.targetId}`):y.type===Dc.COMMENT&&y.postId&&e(`/post/${y.postId}#comment-${y.targetId}`)},m=async()=>{await a()};return r?w.jsxs("div",{className:"min-h-screen flex flex-col bg-cyber-dark text-white",children:[w.jsx(Kd,{}),w.jsx("main",{className:"flex-1 flex items-center justify-center",children:w.jsxs("div",{className:"text-center",children:[w.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-cyber-accent mx-auto mb-4"}),w.jsx("p",{className:"text-cyber-neutral",children:"Loading bookmarks..."})]})})]}):s?w.jsxs("div",{className:"min-h-screen flex flex-col bg-cyber-dark text-white",children:[w.jsx(Kd,{}),w.jsx("main",{className:"flex-1 flex items-center justify-center",children:w.jsxs("div",{className:"text-center",children:[w.jsx("h1",{className:"text-2xl font-bold text-red-400 mb-4",children:"Error Loading Bookmarks"}),w.jsx("p",{className:"text-cyber-neutral mb-4",children:s}),w.jsx(fn,{onClick:()=>window.location.reload(),children:"Try Again"})]})})]}):w.jsxs("div",{className:"page-container",children:[w.jsx(Kd,{}),w.jsx("main",{className:"page-content",children:w.jsxs("div",{className:"page-main",children:[w.jsxs("div",{className:"page-header",children:[w.jsxs("div",{className:"flex items-center justify-between mb-4",children:[w.jsxs("div",{className:"flex items-center gap-3",children:[w.jsx(Fm,{className:"text-cyber-accent",size:32}),w.jsx("h1",{className:"page-title",children:"My Bookmarks"})]}),n.length>0&&w.jsxs(X1e,{children:[w.jsx(Q1e,{asChild:!0,children:w.jsxs(fn,{variant:"outline",size:"sm",className:"text-red-400 border-red-400/30 hover:bg-red-400/10",children:[w.jsx(yP,{size:16,className:"mr-2"}),"Clear All"]})}),w.jsxs(IH,{children:[w.jsxs(TH,{children:[w.jsx(PH,{children:"Clear All Bookmarks"}),w.jsx(kH,{children:"Are you sure you want to remove all your bookmarks? This action cannot be undone."})]}),w.jsxs(NH,{children:[w.jsx(OH,{children:"Cancel"}),w.jsx(RH,{onClick:m,className:"bg-red-600 hover:bg-red-700",children:"Clear All"})]})]})]})]}),w.jsx("p",{className:"page-subtitle",children:"Your saved posts and comments. Bookmarks are stored locally and won't be shared."})]}),n.length>0&&w.jsxs("div",{className:"flex gap-4 mb-6",children:[w.jsxs(Ao,{variant:"outline",className:"border-cyber-accent/30 text-cyber-accent",children:[w.jsx(XM,{size:14,className:"mr-1"}),u.length," Posts"]}),w.jsxs(Ao,{variant:"outline",className:"border-cyber-accent/30 text-cyber-accent",children:[w.jsx(s0,{size:14,className:"mr-1"}),d.length," Comments"]}),w.jsxs(Ao,{variant:"outline",className:"border-cyber-accent/30 text-cyber-accent",children:[w.jsx(Fm,{size:14,className:"mr-1"}),n.length," Total"]})]}),w.jsxs(YPt,{value:c,onValueChange:y=>l(y),className:"w-full",children:[w.jsxs(W2e,{className:"grid w-full grid-cols-3 mb-6",children:[w.jsxs(x6,{value:"all",className:"flex items-center gap-2",children:[w.jsx(Fm,{size:16}),"All (",n.length,")"]}),w.jsxs(x6,{value:"posts",className:"flex items-center gap-2",children:[w.jsx(XM,{size:16}),"Posts (",u.length,")"]}),w.jsxs(x6,{value:"comments",className:"flex items-center gap-2",children:[w.jsx(s0,{size:16}),"Comments (",d.length,")"]})]}),w.jsx(E6,{value:"all",children:w.jsx(Q9,{bookmarks:f(),onRemove:i,onNavigate:p,emptyMessage:"No bookmarks yet"})}),w.jsx(E6,{value:"posts",children:w.jsx(Q9,{bookmarks:f(),onRemove:i,onNavigate:p,emptyMessage:"No bookmarked posts yet"})}),w.jsx(E6,{value:"comments",children:w.jsx(Q9,{bookmarks:f(),onRemove:i,onNavigate:p,emptyMessage:"No bookmarked comments yet"})})]})]})}),w.jsx("footer",{className:"page-footer",children:w.jsx("p",{children:"OpChan - A decentralized forum built on Waku & Bitcoin Ordinals"})})]})},QPt=new Hke,JPt=()=>w.jsx(Flt,{config:OE,children:w.jsx(Kke,{client:QPt,children:w.jsx(bpt,{...t0e,children:w.jsx(z8e,{children:w.jsx(xpt,{children:w.jsx(gAt,{children:w.jsx(mAt,{children:w.jsxs(ace,{children:[w.jsx(v4e,{}),w.jsx(Z4e,{}),w.jsxs(D8e,{children:[w.jsx(ag,{path:"/",element:w.jsx(d4t,{})}),w.jsx(ag,{path:"/cells",element:w.jsx(VPt,{})}),w.jsx(ag,{path:"/cell/:cellId",element:w.jsx(pNt,{})}),w.jsx(ag,{path:"/post/:postId",element:w.jsx(CNt,{})}),w.jsx(ag,{path:"/profile",element:w.jsx(HPt,{})}),w.jsx(ag,{path:"/bookmarks",element:w.jsx(XPt,{})}),w.jsx(ag,{path:"*",element:w.jsx(_Nt,{})})]})]})})})})})})})});Voe(document.getElementById("root")).render(w.jsx(JPt,{}));export{Ue as $,Ov as A,ot as B,Uv as C,Br as D,rc as E,wn as F,Gs as G,mE as H,iy as I,ai as J,G as K,De as L,Kde as M,SBe as N,ke as O,fh as P,ye as Q,Wn as R,df as S,ze as T,ti as U,iUe as V,Qt as W,dz as X,nt as Y,Xr as Z,et as _,He as a,Cj as a$,Lt as a0,Ss as a1,_r as a2,Ht as a3,lr as a4,ee as a5,nr as a6,qr as a7,Bi as a8,rt as a9,x3 as aA,PBe as aB,Yo as aC,NBe as aD,Fr as aE,VT as aF,r7 as aG,mi as aH,Da as aI,mk as aJ,PRt as aK,gr as aL,QOt as aM,XOt as aN,kr as aO,ex as aP,B9e as aQ,D7e as aR,Rge as aS,Po as aT,RP as aU,zce as aV,_j as aW,okt as aX,skt as aY,$r as aZ,HS as a_,Ne as aa,u0 as ab,KS as ac,mC as ad,LS as ae,VP as af,Zy as ag,Ql as ah,Zi as ai,_e as aj,vut as ak,bge as al,Vm as am,Am as an,Ge as ao,tn as ap,fs as aq,jC as ar,Gt as as,vm as at,Vt as au,mt as av,Jr as aw,bh as ax,v3 as ay,vE as az,Kr as b,ez as b$,Gg as b0,P$e as b1,ikt as b2,zP as b3,Lj as b4,Mj as b5,vDe as b6,Cf as b7,PDe as b8,FS as b9,WDe as bA,kP as bB,Tj as bC,Dj as bD,jP as bE,Qkt as bF,vr as bG,Fkt as bH,Yg as bI,NMe as bJ,Ble as bK,Kh as bL,tLe as bM,yDe as bN,l0 as bO,n7e as bP,uT as bQ,Que as bR,BC as bS,YLe as bT,v9e as bU,gL as bV,Dce as bW,_9e as bX,EC as bY,R9e as bZ,QRe as b_,ckt as ba,cf as bb,Ej as bc,pue as bd,rT as be,oy as bf,gue as bg,E9e as bh,J8e as bi,Q1 as bj,Y1 as bk,$v as bl,jce as bm,Ckt as bn,fkt as bo,DP as bp,F9e as bq,Ykt as br,SMe as bs,_ue as bt,Gkt as bu,nd as bv,w9e as bw,Yue as bx,gDe as by,Hle as bz,We as c,BS as c$,due as c0,VDe as c1,Wle as c2,lT as c3,kDe as c4,hue as c5,b9e as c6,NDe as c7,Hkt as c8,Jle as c9,jl as cA,hyt as cB,Nu as cC,yyt as cD,_Dt as cE,Dv as cF,pj as cG,CDt as cH,fyt as cI,EDt as cJ,uj as cK,r8 as cL,xDt as cM,ene as cN,VD as cO,Tm as cP,XDe as cQ,zj as cR,P9e as cS,B2 as cT,afe as cU,OX as cV,yFe as cW,mFe as cX,Mv as cY,k$e as cZ,Fce as c_,Vkt as ca,f$ as cb,ZLe as cc,Vj as cd,d7e as ce,o7e as cf,l7e as cg,c7e as ch,u7e as ci,cde as cj,que as ck,yle as cl,jS as cm,Ga as cn,T$e as co,CL as cp,Ij as cq,O9e as cr,Th as cs,wyt as ct,n8 as cu,myt as cv,Yme as cw,Dme as cx,hV as cy,JB as cz,w7e as d,akt as d0,N0t as d1,GDt as d2,kc as d3,ZS as e,Aj as f,wh as g,m$e as h,it as i,Hj as j,O$e as k,Ale as l,Bj as m,$n as n,cy as o,LP as p,Hh as q,rOe as r,Dl as s,uf as t,_kt as u,Hs as v,mue as w,K as x,lkt as y,X1 as z}; diff --git a/dist/assets/index-DCwOSe4Q.js b/dist/assets/index-DCwOSe4Q.js new file mode 100644 index 0000000..d4b978c --- /dev/null +++ b/dist/assets/index-DCwOSe4Q.js @@ -0,0 +1,8 @@ +import{B as Nn,_ as J,h as Zr,y as jo}from"./hooks.module-Dz_XB4AG.js";import{q as Ge,aT as Bn,aU as Ya,z as ce,aV as Ve,o as je,aW as vr,aP as oe,aX as Yr,aY as Qa,A as Te,l as Xa,aZ as W,a_ as Se,a$ as pn,b0 as Yt,b1 as es,B as D,b2 as Qr,b3 as ts,n as M,b4 as ns,b5 as Mo,b6 as Do,b7 as Ae,b8 as kr,b9 as rs,ba as Xr,bb as Uo,bc as Fo,p as Ke,bd as as,be as xr,bf as Je,bg as De,bh as ss,bi as $o,bj as Er,t as ct,I as Go,bk as de,bl as is,bm as Ho,r as zo,u as qo,y as Wo,bn as Vo,bo as Ko,bp as Jo,bq as gt,br as ea,bs as Zo,bt as Yo,bu as Qo,bv as Qt,bw as mn,bx as os,by as Xo,bz as cs,bA as ec,bB as tc,bC as nc,bD as rc,bE as ac,bF as Ln,bG as Sr,bH as sc,bI as us,bJ as ic,bK as oc,bL as ds,bM as ls,bN as cc,bO as he,m as fs,bP as ps,s as ut,bQ as dt,bR as Bt,bS as xt,bT as Ar,bU as ms,bV as hs,bW as ys,bX as _r,bY as gs,bZ as uc,b_ as ta,b$ as hn,c0 as yn,c1 as bs,j as Ir,c2 as dc,c3 as lc,aQ as Pr,c4 as fc,c5 as pc,c6 as Xt,c7 as mc,c8 as ws,c9 as hc,ca as yc,cb as gc,cc as bc,cd as wc,ce as vc,cf as kc,cg as xc,ch as Ec,ci as Sc,cj as vs,ck as Ac,cl as _c,cm as Ic,cn as na,h as Pc,co as Oc,cp as Cc,cq as Tc,cr as Nc,cs as Bc,ct as Lc,cu as ks,cv as Rc,ae as jc,cw as Mc,ad as nt,cx as xs,cy as Dc,cz as en,cA as ra,cB as Uc,cC as pe,cD as Fc,cE as $c,cF as Rn,cG as Gc,cH as Hc,cI as zc,cJ as qc,cK as Wc,cL as gn,cM as Mt,cN as aa,cO as sa,cP as Vc,af as Kc,cQ as Jc,cR as Zc,ai as Es,cS as Yc,cT as ia,cU as Qc,cV as Xc,cW as eu,cX as tu,cY as nu,cZ as Ss,v as ru,c_ as oa,g as ca,c$ as As,d0 as au}from"./index-Cr5N_0pd.js";import{h as Lt}from"./hashTypedData-D0Cx__mD.js";function _s(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;const t=`0x${e.slice(1,65)}`;return Ge(t)?t:null}function jn(e){let t=new Uint8Array(32).fill(0);if(!e)return Bn(t);const n=e.split(".");for(let r=n.length-1;r>=0;r-=1){const a=_s(n[r]),s=a?Ya(a):ce(Ve(n[r]),"bytes");t=ce(je([t,s]),"bytes")}return Bn(t)}function su(e){return`[${e.slice(2)}]`}function iu(e){const t=new Uint8Array(32).fill(0);return e?_s(e)||ce(Ve(e)):Bn(t)}function Or(e){const t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);const n=new Uint8Array(Ve(t).byteLength+2);let r=0;const a=t.split(".");for(let s=0;s255&&(i=Ve(su(iu(a[s])))),n[r]=i.length,n.set(i,r+1),r+=i.length+1}return n.byteLength!==r+1?n.slice(0,r+1):n}async function ou(e,t){const{blockNumber:n,blockTag:r,coinType:a,name:s,gatewayUrls:i,strict:o}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return vr({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(p=>s.endsWith(p)))return null;const l=a!=null?[jn(s),BigInt(a)]:[jn(s)];try{const p=oe({abi:Yr,functionName:"addr",args:l}),f={address:u,abi:Qa,functionName:"resolveWithGateways",args:[Te(Or(s)),p,i??[Xa]],blockNumber:n,blockTag:r},g=await W(e,Se,"readContract")(f);if(g[0]==="0x")return null;const h=pn({abi:Yr,args:l,functionName:"addr",data:g[0]});return h==="0x"||Yt(h)==="0x00"?null:h}catch(p){if(o)throw p;if(es(p))return null;throw p}}class cu extends D{constructor({data:t}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(t)}`],name:"EnsAvatarInvalidMetadataError"})}}class bt extends D{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}}class Cr extends D{constructor({uri:t}){super(`Unable to resolve ENS avatar URI "${t}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class uu extends D{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const du=/(?https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/,lu=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/,fu=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,pu=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function mu(e){try{const t=await fetch(e,{method:"HEAD"});return t.status===200?t.headers.get("content-type")?.startsWith("image/"):!1}catch(t){return typeof t=="object"&&typeof t.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(n=>{const r=new Image;r.onload=()=>{n(!0)},r.onerror=()=>{n(!1)},r.src=e})}}function ua(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function Is({uri:e,gatewayUrls:t}){const n=fu.test(e);if(n)return{uri:e,isOnChain:!0,isEncoded:n};const r=ua(t?.ipfs,"https://ipfs.io"),a=ua(t?.arweave,"https://arweave.net"),s=e.match(du),{protocol:i,subpath:o,target:c,subtarget:u=""}=s?.groups||{},d=i==="ipns:/"||o==="ipns/",l=i==="ipfs:/"||o==="ipfs/"||lu.test(e);if(e.startsWith("http")&&!d&&!l){let f=e;return t?.arweave&&(f=e.replace(/https:\/\/arweave.net/g,t?.arweave)),{uri:f,isOnChain:!1,isEncoded:!1}}if((d||l)&&c)return{uri:`${r}/${d?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(i==="ar:/"&&c)return{uri:`${a}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let p=e.replace(pu,"");if(p.startsWith("a.json());return await Tr({gatewayUrls:e,uri:Ps(n)})}catch{throw new Cr({uri:t})}}async function Tr({gatewayUrls:e,uri:t}){const{uri:n,isOnChain:r}=Is({uri:t,gatewayUrls:e});if(r||await mu(n))return n;throw new Cr({uri:t})}function yu(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));const[n,r,a]=t.split("/"),[s,i]=n.split(":"),[o,c]=r.split(":");if(!s||s.toLowerCase()!=="eip155")throw new bt({reason:"Only EIP-155 supported"});if(!i)throw new bt({reason:"Chain ID not found"});if(!c)throw new bt({reason:"Contract address not found"});if(!a)throw new bt({reason:"Token ID not found"});if(!o)throw new bt({reason:"ERC namespace not found"});return{chainID:Number.parseInt(i,10),namespace:o.toLowerCase(),contractAddress:c,tokenID:a}}async function gu(e,{nft:t}){if(t.namespace==="erc721")return Se(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return Se(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new uu({namespace:t.namespace})}async function bu(e,{gatewayUrls:t,record:n}){return/eip155:/i.test(n)?wu(e,{gatewayUrls:t,record:n}):Tr({uri:n,gatewayUrls:t})}async function wu(e,{gatewayUrls:t,record:n}){const r=yu(n),a=await gu(e,{nft:r}),{uri:s,isOnChain:i,isEncoded:o}=Is({uri:a,gatewayUrls:t});if(i&&(s.includes("data:application/json;base64,")||s.startsWith("{"))){const u=o?atob(s.replace("data:application/json;base64,","")):s,d=JSON.parse(u);return Tr({uri:Ps(d),gatewayUrls:t})}let c=r.tokenID;return r.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),hu({gatewayUrls:t,uri:s.replace(/(?:0x)?{id}/,c)})}async function Os(e,t){const{blockNumber:n,blockTag:r,key:a,name:s,gatewayUrls:i,strict:o}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return vr({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(l=>s.endsWith(l)))return null;try{const l={address:u,abi:Qa,args:[Te(Or(s)),oe({abi:Qr,functionName:"text",args:[jn(s),a]}),i??[Xa]],functionName:"resolveWithGateways",blockNumber:n,blockTag:r},f=await W(e,Se,"readContract")(l);if(f[0]==="0x")return null;const y=pn({abi:Qr,functionName:"text",data:f[0]});return y===""?null:y}catch(l){if(o)throw l;if(es(l))return null;throw l}}async function vu(e,{blockNumber:t,blockTag:n,assetGatewayUrls:r,name:a,gatewayUrls:s,strict:i,universalResolverAddress:o}){const c=await W(e,Os,"getEnsText")({blockNumber:t,blockTag:n,key:"avatar",name:a,universalResolverAddress:o,gatewayUrls:s,strict:i});if(!c)return null;try{return await bu(e,{record:c,gatewayUrls:r})}catch{return null}}async function ku(e,t){const{blockNumber:n,blockTag:r,name:a}=t,{chain:s}=e,i=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!s)throw new Error("client chain not configured. universalResolverAddress is required.");return vr({blockNumber:n,chain:s,contract:"ensUniversalResolver"})})(),o=s?.ensTlds;if(o&&!o.some(u=>a.endsWith(u)))throw new Error(`${a} is not a valid ENS TLD (${o?.join(", ")}) for chain "${s.name}" (id: ${s.id}).`);const[c]=await W(e,Se,"readContract")({address:i,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Te(Or(a))],blockNumber:n,blockTag:r});return c}async function Cs(e,t){const{account:n=e.account,blockNumber:r,blockTag:a="latest",blobs:s,data:i,gas:o,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:l,to:p,value:f,...y}=t,g=n?Ae(n):void 0;try{ts(t);const w=(typeof r=="bigint"?M(r):void 0)||a,E=e.chain?.formatters?.transactionRequest?.format,A=(E||ns)({...Mo(y,{format:E}),from:g?.address,blobs:s,data:i,gas:o,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:l,to:p,value:f}),I=await e.request({method:"eth_createAccessList",params:[A,w]});return{accessList:I.accessList,gasUsed:BigInt(I.gasUsed)}}catch(h){throw Do(h,{...t,account:g,chain:e.chain})}}async function xu(e){const t=kr(e,{method:"eth_newBlockFilter"}),n=await e.request({method:"eth_newBlockFilter"});return{id:n,request:t(n),type:"block"}}class Eu extends D{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}const da="/docs/contract/encodeEventTopics";function Rt(e){const{abi:t,eventName:n,args:r}=e;let a=t[0];if(n){const c=rs({abi:t,name:n});if(!c)throw new Xr(n,{docsPath:da});a=c}if(a.type!=="event")throw new Xr(void 0,{docsPath:da});const s=Uo(a),i=Fo(s);let o=[];if(r&&"inputs"in a){const c=a.inputs?.filter(d=>"indexed"in d&&d.indexed),u=Array.isArray(r)?r:Object.values(r).length>0?c?.map(d=>r[d.name])??[]:[];u.length>0&&(o=c?.map((d,l)=>Array.isArray(u[l])?u[l].map((p,f)=>la({param:d,value:u[l][f]})):typeof u[l]<"u"&&u[l]!==null?la({param:d,value:u[l]}):null)??[])}return[i,...o]}function la({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return ce(Ya(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new Eu(e.type);return Ke([e],[t])}async function Ts(e,t){const{address:n,abi:r,args:a,eventName:s,fromBlock:i,strict:o,toBlock:c}=t,u=kr(e,{method:"eth_newFilter"}),d=s?Rt({abi:r,args:a,eventName:s}):void 0,l=await e.request({method:"eth_newFilter",params:[{address:n,fromBlock:typeof i=="bigint"?M(i):i,toBlock:typeof c=="bigint"?M(c):c,topics:d}]});return{abi:r,args:a,eventName:s,id:l,request:u(l),strict:!!o,type:"event"}}async function Ns(e,{address:t,args:n,event:r,events:a,fromBlock:s,strict:i,toBlock:o}={}){const c=a??(r?[r]:void 0),u=kr(e,{method:"eth_newFilter"});let d=[];c&&(d=[c.flatMap(f=>Rt({abi:[f],eventName:f.name,args:n}))],r&&(d=d[0]));const l=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof s=="bigint"?M(s):s,toBlock:typeof o=="bigint"?M(o):o,...d.length?{topics:d}:{}}]});return{abi:c,args:n,eventName:r?r.name:void 0,fromBlock:s,id:l,request:u(l),strict:!!i,toBlock:o,type:"event"}}async function Su(e,t){const{abi:n,address:r,args:a,functionName:s,dataSuffix:i,...o}=t,c=oe({abi:n,args:a,functionName:s});try{return await W(e,as,"estimateGas")({data:`${c}${i?i.replace("0x",""):""}`,to:r,...o})}catch(u){const d=o.account?Ae(o.account):void 0;throw xr(u,{abi:n,address:r,args:a,docsPath:"/docs/contract/estimateContractGas",functionName:s,sender:d?.address})}}async function Au(e){const t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}async function _u(e,{blockHash:t,blockNumber:n,blockTag:r="latest"}={}){const a=n!==void 0?M(n):void 0;let s;return t?s=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):s=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[a||r]},{dedupe:!!a}),Je(s)}async function Nr(e,{address:t,blockHash:n,fromBlock:r,toBlock:a,event:s,events:i,args:o,strict:c}={}){const u=c??!1,d=i??(s?[s]:void 0);let l=[];d&&(l=[d.flatMap(g=>Rt({abi:[g],eventName:g.name,args:i?void 0:o}))],s&&(l=l[0]));let p;n?p=await e.request({method:"eth_getLogs",params:[{address:t,topics:l,blockHash:n}]}):p=await e.request({method:"eth_getLogs",params:[{address:t,topics:l,fromBlock:typeof r=="bigint"?M(r):r,toBlock:typeof a=="bigint"?M(a):a}]});const f=p.map(y=>De(y));return d?ss({abi:d,args:o,logs:f,strict:u}):f}async function Bs(e,t){const{abi:n,address:r,args:a,blockHash:s,eventName:i,fromBlock:o,toBlock:c,strict:u}=t,d=i?rs({abi:n,name:i}):void 0,l=d?void 0:n.filter(p=>p.type==="event");return W(e,Nr,"getLogs")({address:r,args:a,blockHash:s,event:d,events:l,fromBlock:o,toBlock:c,strict:u})}class Iu extends D{constructor({address:t}){super(`No EIP-712 domain found on contract "${t}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${t}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function Pu(e,t){const{address:n,factory:r,factoryData:a}=t;try{const[s,i,o,c,u,d,l]=await W(e,Se,"readContract")({abi:Ou,address:n,functionName:"eip712Domain",factory:r,factoryData:a});return{domain:{name:i,version:o,chainId:Number(c),verifyingContract:u,salt:d},extensions:l,fields:s}}catch(s){const i=s;throw i.name==="ContractFunctionExecutionError"&&i.cause.name==="ContractFunctionZeroDataError"?new Iu({address:n}):i}}const Ou=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];function Cu(e){return{baseFeePerGas:e.baseFeePerGas.map(t=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map(t=>t.map(n=>BigInt(n)))}}async function Tu(e,{blockCount:t,blockNumber:n,blockTag:r="latest",rewardPercentiles:a}){const s=typeof n=="bigint"?M(n):void 0,i=await e.request({method:"eth_feeHistory",params:[M(t),s||r,a]},{dedupe:!!s});return Cu(i)}async function Nu(e,{filter:t}){const n=t.strict??!1,a=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(s=>De(s));return t.abi?ss({abi:t.abi,logs:a,strict:n}):a}function Bu(e,t){if(e.length!==t.length)throw new $o({expectedLength:e.length,givenLength:t.length});const n=[];for(let r=0;r`${i}.${o}`;return{async consume({address:i,chainId:o,client:c}){const u=s({address:i,chainId:o}),d=this.get({address:i,chainId:o,client:c});this.increment({address:i,chainId:o});const l=await d;return await t.set({address:i,chainId:o},l),r.set(u,l),l},async increment({address:i,chainId:o}){const c=s({address:i,chainId:o}),u=n.get(c)??0;n.set(c,u+1)},async get({address:i,chainId:o,client:c}){const u=s({address:i,chainId:o});let d=a.get(u);return d||(d=(async()=>{try{const p=await t.get({address:i,chainId:o,client:c}),f=r.get(u)??0;return f>0&&p<=f?f+1:(r.delete(u),p)}finally{this.reset({address:i,chainId:o})}})(),a.set(u,d)),(n.get(u)??0)+await d},reset({address:i,chainId:o}){const c=s({address:i,chainId:o});n.delete(c),a.delete(c)}}}const Ru="0x6492649264926492649264926492649264926492649264926492649264926492";function Mn(e){return e.type==="function"?`function ${e.name}(${gt(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${gt(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${gt(e.inputs)})`:e.type==="error"?`error ${e.name}(${gt(e.inputs)})`:e.type==="constructor"?`constructor(${gt(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}function fa(e){let t;if(typeof e=="string")t=ea(e);else{const n=Zo(e),r=e.length;for(let a=0;a({...t,value:BigInt(t.value)}))}function Mu(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?Je(e.nonce):void 0,storageProof:e.storageProof?ju(e.storageProof):void 0}}async function Du(e,{address:t,blockNumber:n,blockTag:r,storageKeys:a}){const s=r??"latest",i=n!==void 0?M(n):void 0,o=await e.request({method:"eth_getProof",params:[t,a,i||s]});return Mu(o)}async function Uu(e,{address:t,blockNumber:n,blockTag:r="latest",slot:a}){const s=n!==void 0?M(n):void 0;return await e.request({method:"eth_getStorageAt",params:[t,a,s||r]})}async function Fu(e,{hash:t,transactionReceipt:n}){const[r,a]=await Promise.all([W(e,mn,"getBlockNumber")({}),t?W(e,os,"getTransaction")({hash:t}):void 0]),s=n?.blockNumber||a?.blockNumber;return s?r-s+1n:0n}async function Dn(e,t){const{blockNumber:n,blockTag:r=e.experimental_blockTag??"latest",blocks:a,returnFullTransactions:s,traceTransfers:i,validation:o}=t;try{const c=[];for(const p of a){const f=p.blockOverrides?Xo(p.blockOverrides):void 0,y=p.calls.map(h=>{const w=h,E=w.account?Ae(w.account):void 0,b=w.abi?oe(w):w.data,A={...w,data:w.dataSuffix?je([b||"0x",w.dataSuffix]):b,from:w.from??E?.address};return ts(A),ns(A)}),g=p.stateOverrides?cs(p.stateOverrides):void 0;c.push({blockOverrides:f,calls:y,stateOverrides:g})}const d=(typeof n=="bigint"?M(n):void 0)||r;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:s,traceTransfers:i,validation:o},d]})).map((p,f)=>({...ec(p),calls:p.calls.map((y,g)=>{const{abi:h,args:w,functionName:E,to:b}=a[f].calls[g],A=y.error?.data??y.returnData,I=BigInt(y.gasUsed),N=y.logs?.map(P=>De(P)),B=y.status==="0x1"?"success":"failure",j=h&&B==="success"&&A!=="0x"?pn({abi:h,data:A,functionName:E}):null,v=(()=>{if(B==="success")return;let P;if(y.error?.data==="0x"?P=new tc:y.error&&(P=new nc(y.error)),!!P)return xr(P,{abi:h??[],address:b??"0x",args:w,functionName:E??""})})();return{data:A,gasUsed:I,logs:N,status:B,...B==="success"?{result:j}:{error:v}}})}))}catch(c){const u=c,d=rc(u,{});throw d instanceof ac?u:d}}function Un(e){let t=!0,n="",r=0,a="",s=!1;for(let i=0;iFn(Object.values(e)[s],a)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(r)?n==="number"||n==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(r)?n==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(r)?Array.isArray(e)&&e.every(a=>Fn(a,{...t,type:r.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function Rs(e,t,n){for(const r in e){const a=e[r],s=t[r];if(a.type==="tuple"&&s.type==="tuple"&&"components"in a&&"components"in s)return Rs(a.components,s.components,n[r]);const i=[a.type,s.type];if(i.includes("address")&&i.includes("bytes20")?!0:i.includes("address")&&i.includes("string")?Ln(n[r],{strict:!1}):i.includes("address")&&i.includes("bytes")?Ln(n[r],{strict:!1}):!1)return i}}function js(e,t={}){const{prepare:n=!0}=t,r=Array.isArray(e)||typeof e=="string"?fa(e):e;return{...r,...n?{hash:rt(r)}:{}}}function $u(e,t,n){const{args:r=[],prepare:a=!0}=n??{},s=sc(t,{strict:!1}),i=e.filter(u=>s?u.type==="function"||u.type==="error"?Ms(u)===us(t,0,4):u.type==="event"?rt(u)===t:!1:"name"in u&&u.name===t);if(i.length===0)throw new $n({name:t});if(i.length===1)return{...i[0],...a?{hash:rt(i[0])}:{}};let o;for(const u of i){if(!("inputs"in u))continue;if(!r||r.length===0){if(!u.inputs||u.inputs.length===0)return{...u,...a?{hash:rt(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==r.length)continue;if(r.every((l,p)=>{const f="inputs"in u&&u.inputs[p];return f?Fn(l,f):!1})){if(o&&"inputs"in o&&o.inputs){const l=Rs(u.inputs,o.inputs,r);if(l)throw new Hu({abiItem:u,type:l[0]},{abiItem:o,type:l[1]})}o=u}}const c=(()=>{if(o)return o;const[u,...d]=i;return{...u,overloads:d}})();if(!c)throw new $n({name:t});return{...c,...a?{hash:rt(c)}:{}}}function Ms(e){return us(rt(e),0,4)}function Gu(e){const t=typeof e=="string"?e:Mn(e);return Un(t)}function rt(e){return typeof e!="string"&&"hash"in e&&e.hash?e.hash:ic(oc(Gu(e)))}class Hu extends Sr{constructor(t,n){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${Un(Mn(t.abiItem))}\`, and`,`\`${n.type}\` in \`${Un(Mn(n.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class $n extends Sr{constructor({name:t,data:n,type:r="item"}){const a=t?` with name "${t}"`:n?` with data "${n}"`:"";super(`ABI ${r}${a} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}function zu(e,t){const{bytecode:n,args:r}=t;return ds(n,e.inputs?.length&&r?.length?ls(e.inputs,r):"0x")}function qu(e){return js(e)}function Wu(e,...t){const{overloads:n}=e,r=n?Vu([e,...n],e.name,{args:t[0]}):e,a=Ku(r),s=t.length>0?ls(r.inputs,t[0]):void 0;return s?ds(a,s):a}function Xe(e,t={}){return js(e,t)}function Vu(e,t,n){const r=$u(e,t,n);if(r.type!=="function")throw new $n({name:t,type:"function"});return r}function Ku(e){return Ms(e)}const Ju="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",we="0x0000000000000000000000000000000000000000",Zu="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function Yu(e,t){const{blockNumber:n,blockTag:r,calls:a,stateOverrides:s,traceAssetChanges:i,traceTransfers:o,validation:c}=t,u=t.account?Ae(t.account):void 0;if(i&&!u)throw new D("`account` is required when `traceAssetChanges` is true");const d=u?zu(qu("constructor(bytes, bytes)"),{bytecode:cc,args:[Zu,Wu(Xe("function getBalance(address)"),[u.address])]}):void 0,l=i?await Promise.all(t.calls.map(async S=>{if(!S.data&&!S.abi)return;const{accessList:$}=await Cs(e,{account:u.address,...S,data:S.abi?oe(S):S.data});return $.map(({address:q,storageKeys:F})=>F.length>0?q:null)})).then(S=>S.flat().filter(Boolean)):[],p=await Dn(e,{blockNumber:n,blockTag:r,blocks:[...i?[{calls:[{data:d}],stateOverrides:s},{calls:l.map((S,$)=>({abi:[Xe("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:S,from:we,nonce:$})),stateOverrides:[{address:we,nonce:0}]}]:[],{calls:[...a,{}].map(S=>({...S,from:u?.address})),stateOverrides:s},...i?[{calls:[{data:d}]},{calls:l.map((S,$)=>({abi:[Xe("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:S,from:we,nonce:$})),stateOverrides:[{address:we,nonce:0}]},{calls:l.map((S,$)=>({to:S,abi:[Xe("function decimals() returns (uint256)")],functionName:"decimals",from:we,nonce:$})),stateOverrides:[{address:we,nonce:0}]},{calls:l.map((S,$)=>({to:S,abi:[Xe("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:we,nonce:$})),stateOverrides:[{address:we,nonce:0}]},{calls:l.map((S,$)=>({to:S,abi:[Xe("function symbol() returns (string)")],functionName:"symbol",from:we,nonce:$})),stateOverrides:[{address:we,nonce:0}]}]:[]],traceTransfers:o,validation:c}),f=i?p[2]:p[0],[y,g,,h,w,E,b,A]=i?p:[],{calls:I,...N}=f,B=I.slice(0,-1)??[],j=y?.calls??[],v=g?.calls??[],P=[...j,...v].map(S=>S.status==="success"?he(S.data):null),x=h?.calls??[],m=w?.calls??[],k=[...x,...m].map(S=>S.status==="success"?he(S.data):null),C=(E?.calls??[]).map(S=>S.status==="success"?S.result:null),O=(A?.calls??[]).map(S=>S.status==="success"?S.result:null),L=(b?.calls??[]).map(S=>S.status==="success"?S.result:null),R=[];for(const[S,$]of k.entries()){const q=P[S];if(typeof $!="bigint"||typeof q!="bigint")continue;const F=C[S-1],ee=O[S-1],te=L[S-1],ne=S===0?{address:Ju,decimals:18,symbol:"ETH"}:{address:l[S-1],decimals:te||F?Number(F??1):void 0,symbol:ee??void 0};R.some(K=>K.token.address===ne.address)||R.push({token:ne,value:{pre:q,post:$,diff:$-q}})}return{assetChanges:R,block:N,results:B}}async function Qu(e,t){const{abi:n,address:r,args:a,dataSuffix:s,functionName:i,...o}=t,c=o.account?Ae(o.account):e.account,u=oe({abi:n,args:a,functionName:i});try{const{data:d}=await W(e,fs,"call")({batch:!1,data:`${u}${s?s.replace("0x",""):""}`,to:r,...o,account:c}),l=pn({abi:n,args:a,functionName:i,data:d||"0x"}),p=n.filter(f=>"name"in f&&f.name===t.functionName);return{result:l,request:{abi:p,address:r,args:a,dataSuffix:s,functionName:i,...o,account:c}}}catch(d){throw xr(d,{abi:n,address:r,args:a,docsPath:"/docs/contract/simulateContract",functionName:i,sender:c?.address})}}async function Xu(e,t){const{address:n,factory:r,factoryData:a,signature:s,message:i,primaryType:o,types:c,domain:u,...d}=t,l=Lt({message:i,primaryType:o,types:c,domain:u});return ps(e,{address:n,factory:r,factoryData:a,hash:l,signature:s,...d})}function ed(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:n=!1,emitOnBegin:r=!1,onBlock:a,onError:s,includeTransactions:i,poll:o,pollingInterval:c=e.pollingInterval}){const u=typeof o<"u"?o:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),d=i??!1;let l;return u?(()=>{const y=ut(["watchBlocks",e.uid,t,n,r,d,c]);return dt(y,{onBlock:a,onError:s},g=>Bt(async()=>{try{const h=await W(e,xt,"getBlock")({blockTag:t,includeTransactions:d});if(h.number!==null&&l?.number!=null){if(h.number===l.number)return;if(h.number-l.number>1&&n)for(let w=l?.number+1n;wl.number)&&(g.onBlock(h,l),l=h)}catch(h){g.onError?.(h)}},{emitOnBegin:r,interval:c}))})():(()=>{let y=!0,g=!0,h=()=>y=!1;return(async()=>{try{r&&W(e,xt,"getBlock")({blockTag:t,includeTransactions:d}).then(b=>{y&&g&&(a(b,void 0),g=!1)}).catch(s);const w=(()=>{if(e.transport.type==="fallback"){const b=e.transport.transports.find(A=>A.config.type==="webSocket"||A.config.type==="ipc");return b?b.value:e.transport}return e.transport})(),{unsubscribe:E}=await w.subscribe({params:["newHeads"],async onData(b){if(!y)return;const A=await W(e,xt,"getBlock")({blockNumber:b.result?.number,includeTransactions:d}).catch(()=>{});y&&(a(A,l),g=!1,l=A)},onError(b){s?.(b)}});h=E,y||h()}catch(w){s?.(w)}})(),()=>h()})()}function td(e,t){const{abi:n,address:r,args:a,batch:s=!0,eventName:i,fromBlock:o,onError:c,onLogs:u,poll:d,pollingInterval:l=e.pollingInterval,strict:p}=t;return(typeof d<"u"?d:typeof o=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")))?(()=>{const h=p??!1,w=ut(["watchContractEvent",r,a,s,e.uid,i,l,h,o]);return dt(w,{onLogs:u,onError:c},E=>{let b;o!==void 0&&(b=o-1n);let A,I=!1;const N=Bt(async()=>{if(!I){try{A=await W(e,Ts,"createContractEventFilter")({abi:n,address:r,args:a,eventName:i,strict:h,fromBlock:o})}catch{}I=!0;return}try{let B;if(A)B=await W(e,_r,"getFilterChanges")({filter:A});else{const j=await W(e,mn,"getBlockNumber")({});b&&b{A&&await W(e,Ar,"uninstallFilter")({filter:A}),N()}})})():(()=>{const h=p??!1,w=ut(["watchContractEvent",r,a,s,e.uid,i,l,h]);let E=!0,b=()=>E=!1;return dt(w,{onLogs:u,onError:c},A=>((async()=>{try{const I=(()=>{if(e.transport.type==="fallback"){const j=e.transport.transports.find(v=>v.config.type==="webSocket"||v.config.type==="ipc");return j?j.value:e.transport}return e.transport})(),N=i?Rt({abi:n,eventName:i,args:a}):[],{unsubscribe:B}=await I.subscribe({params:["logs",{address:r,topics:N}],onData(j){if(!E)return;const v=j.result;try{const{eventName:P,args:x}=ms({abi:n,data:v.data,topics:v.topics,strict:p}),m=De(v,{args:x,eventName:P});A.onLogs([m])}catch(P){let x,m;if(P instanceof hs||P instanceof ys){if(p)return;x=P.abiItem.name,m=P.abiItem.inputs?.some(C=>!("name"in C&&C.name))}const k=De(v,{args:m?[]:{},eventName:x});A.onLogs([k])}},onError(j){A.onError?.(j)}});b=B,E||b()}catch(I){c?.(I)}})(),()=>b()))})()}function nd(e,{address:t,args:n,batch:r=!0,event:a,events:s,fromBlock:i,onError:o,onLogs:c,poll:u,pollingInterval:d=e.pollingInterval,strict:l}){const p=typeof u<"u"?u:typeof i=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),f=l??!1;return p?(()=>{const h=ut(["watchEvent",t,n,r,e.uid,a,d,i]);return dt(h,{onLogs:c,onError:o},w=>{let E;i!==void 0&&(E=i-1n);let b,A=!1;const I=Bt(async()=>{if(!A){try{b=await W(e,Ns,"createEventFilter")({address:t,args:n,event:a,events:s,strict:f,fromBlock:i})}catch{}A=!0;return}try{let N;if(b)N=await W(e,_r,"getFilterChanges")({filter:b});else{const B=await W(e,mn,"getBlockNumber")({});E&&E!==B?N=await W(e,Nr,"getLogs")({address:t,args:n,event:a,events:s,fromBlock:E+1n,toBlock:B}):N=[],E=B}if(N.length===0)return;if(r)w.onLogs(N);else for(const B of N)w.onLogs([B])}catch(N){b&&N instanceof gs&&(A=!1),w.onError?.(N)}},{emitOnBegin:!0,interval:d});return async()=>{b&&await W(e,Ar,"uninstallFilter")({filter:b}),I()}})})():(()=>{let h=!0,w=()=>h=!1;return(async()=>{try{const E=(()=>{if(e.transport.type==="fallback"){const N=e.transport.transports.find(B=>B.config.type==="webSocket"||B.config.type==="ipc");return N?N.value:e.transport}return e.transport})(),b=s??(a?[a]:void 0);let A=[];b&&(A=[b.flatMap(B=>Rt({abi:[B],eventName:B.name,args:n}))],a&&(A=A[0]));const{unsubscribe:I}=await E.subscribe({params:["logs",{address:t,topics:A}],onData(N){if(!h)return;const B=N.result;try{const{eventName:j,args:v}=ms({abi:b??[],data:B.data,topics:B.topics,strict:f}),P=De(B,{args:v,eventName:j});c([P])}catch(j){let v,P;if(j instanceof hs||j instanceof ys){if(l)return;v=j.abiItem.name,P=j.abiItem.inputs?.some(m=>!("name"in m&&m.name))}const x=De(B,{args:P?[]:{},eventName:v});c([x])}},onError(N){o?.(N)}});w=I,h||w()}catch(E){o?.(E)}})(),()=>w()})()}const rd="0x5792579257925792579257925792579257925792579257925792579257925792",ad=M(0,{size:32});async function sd(e,t){async function n(d){if(d.endsWith(rd.slice(2))){const p=Yt(ta(d,-64,-32)),f=ta(d,0,-64).slice(2).match(/.{1,64}/g),y=await Promise.all(f.map(h=>ad.slice(2)!==h?e.request({method:"eth_getTransactionReceipt",params:[`0x${h}`]},{dedupe:!0}):void 0)),g=y.some(h=>h===null)?100:y.every(h=>h?.status==="0x1")?200:y.every(h=>h?.status==="0x0")?500:600;return{atomic:!1,chainId:Je(p),receipts:y.filter(Boolean),status:g,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[d]})}const{atomic:r=!1,chainId:a,receipts:s,version:i="2.0.0",...o}=await n(t.id),[c,u]=(()=>{const d=o.status;return d>=100&&d<200?["pending",d]:d>=200&&d<300?["success",d]:d>=300&&d<700?["failure",d]:d==="CONFIRMED"?["success",200]:d==="PENDING"?["pending",100]:[void 0,d]})();return{...o,atomic:r,chainId:a?Je(a):void 0,receipts:s?.map(d=>({...d,blockNumber:he(d.blockNumber),gasUsed:he(d.gasUsed),status:uc[d.status]}))??[],statusCode:u,status:c,version:i}}async function id(e,t){const{account:n=e.account,chainId:r,nonce:a}=t;if(!n)throw new hn({docsPath:"/docs/eip7702/prepareAuthorization"});const s=Ae(n),i=(()=>{if(t.executor)return t.executor==="self"?t.executor:Ae(t.executor)})(),o={address:t.contractAddress??t.address,chainId:r,nonce:a};return typeof o.chainId>"u"&&(o.chainId=e.chain?.id??await W(e,yn,"getChainId")({})),typeof o.nonce>"u"&&(o.nonce=await W(e,bs,"getTransactionCount")({address:s.address,blockTag:"pending"}),(i==="self"||i?.address&&Ir(i.address,s.address))&&(o.nonce+=1)),o}class od extends D{constructor(t){super(`Call bundle failed with status: ${t.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=t}}async function Ds(e,t){const{id:n,pollingInterval:r=e.pollingInterval,status:a=({statusCode:g})=>g===200||g>=300,retryCount:s=4,retryDelay:i=({count:g})=>~~(1<{const h=Bt(async()=>{const w=E=>{clearTimeout(f),h(),E(),y()};try{const E=await lc(async()=>{const b=await sd(e,{id:n});if(c&&b.status==="failure")throw new od(b);return b},{retryCount:s,delay:i});if(!a(E))return;w(()=>g.resolve(E))}catch(E){w(()=>g.reject(E))}},{interval:r,emitOnBegin:!0});return h});return f=o?setTimeout(()=>{y(),clearTimeout(f),p(new cd({id:n}))},o):void 0,await d}class cd extends D{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}function ud(e){const{scheme:t,statement:n,...r}=e.match(dd)?.groups??{},{chainId:a,expirationTime:s,issuedAt:i,notBefore:o,requestId:c,...u}=e.match(ld)?.groups??{},d=e.split("Resources:")[1]?.split(` +- `).slice(1);return{...r,...u,...a?{chainId:Number(a)}:{},...s?{expirationTime:new Date(s)}:{},...i?{issuedAt:new Date(i)}:{},...o?{notBefore:new Date(o)}:{},...c?{requestId:c}:{},...d?{resources:d}:{},...t?{scheme:t}:{},...n?{statement:n}:{}}}const dd=/^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/,ld=/(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/;function fd(e){const{address:t,domain:n,message:r,nonce:a,scheme:s,time:i=new Date}=e;if(n&&r.domain!==n||a&&r.nonce!==a||s&&r.scheme!==s||r.expirationTime&&i>=r.expirationTime||r.notBefore&&ifs(e,t),createAccessList:t=>Cs(e,t),createBlockFilter:()=>xu(e),createContractEventFilter:t=>Ts(e,t),createEventFilter:t=>Ns(e,t),createPendingTransactionFilter:()=>fc(e),estimateContractGas:t=>Su(e,t),estimateGas:t=>as(e,t),getBalance:t=>pc(e,t),getBlobBaseFee:()=>Au(e),getBlock:t=>xt(e,t),getBlockNumber:t=>mn(e,t),getBlockTransactionCount:t=>_u(e,t),getBytecode:t=>Xt(e,t),getChainId:()=>yn(e),getCode:t=>Xt(e,t),getContractEvents:t=>Bs(e,t),getEip712Domain:t=>Pu(e,t),getEnsAddress:t=>ou(e,t),getEnsAvatar:t=>vu(e,t),getEnsName:t=>mc(e,t),getEnsResolver:t=>ku(e,t),getEnsText:t=>Os(e,t),getFeeHistory:t=>Tu(e,t),estimateFeesPerGas:t=>ws(e,t),getFilterChanges:t=>_r(e,t),getFilterLogs:t=>Nu(e,t),getGasPrice:()=>hc(e),getLogs:t=>Nr(e,t),getProof:t=>Du(e,t),estimateMaxPriorityFeePerGas:t=>yc(e,t),getStorageAt:t=>Uu(e,t),getTransaction:t=>os(e,t),getTransactionConfirmations:t=>Fu(e,t),getTransactionCount:t=>bs(e,t),getTransactionReceipt:t=>gc(e,t),multicall:t=>bc(e,t),prepareTransactionRequest:t=>wc(e,t),readContract:t=>Se(e,t),sendRawTransaction:t=>vc(e,t),simulate:t=>Dn(e,t),simulateBlocks:t=>Dn(e,t),simulateCalls:t=>Yu(e,t),simulateContract:t=>Qu(e,t),verifyMessage:t=>kc(e,t),verifySiweMessage:t=>pd(e,t),verifyTypedData:t=>Xu(e,t),uninstallFilter:t=>Ar(e,t),waitForTransactionReceipt:t=>xc(e,t),watchBlocks:t=>ed(e,t),watchBlockNumber:t=>Ec(e,t),watchContractEvent:t=>td(e,t),watchEvent:t=>nd(e,t),watchPendingTransactions:t=>Sc(e,t)}}function hd(e){const{key:t="public",name:n="Public Client"}=e;return vs({...e,key:t,name:n,type:"publicClient"}).extend(md)}function yd(e){const{r:t,s:n}=Ac.Signature.fromCompact(e.slice(2,130)),r=+`0x${e.slice(130)}`,[a,s]=(()=>{if(r===0||r===1)return[void 0,r];if(r===27)return[BigInt(r),0];if(r===28)return[BigInt(r),1];throw new Error("Invalid yParityOrV value")})();return typeof a<"u"?{r:M(t,{size:32}),s:M(n,{size:32}),v:a,yParity:s}:{r:M(t,{size:32}),s:M(n,{size:32}),yParity:s}}function Us(e,t){let n;try{n=e()}catch{return}return{getItem:a=>{var s;const i=c=>c===null?null:JSON.parse(c,void 0),o=(s=n.getItem(a))!=null?s:null;return o instanceof Promise?o.then(i):i(o)},setItem:(a,s)=>n.setItem(a,JSON.stringify(s,void 0)),removeItem:a=>n.removeItem(a)}}const Gn=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Gn(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Gn(r)(n)}}}},gd=(e,t)=>(n,r,a)=>{let s={storage:Us(()=>localStorage),partialize:g=>g,version:0,merge:(g,h)=>({...h,...g}),...t},i=!1;const o=new Set,c=new Set;let u=s.storage;if(!u)return e((...g)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...g)},r,a);const d=()=>{const g=s.partialize({...r()});return u.setItem(s.name,{state:g,version:s.version})},l=a.setState;a.setState=(g,h)=>{l(g,h),d()};const p=e((...g)=>{n(...g),d()},r,a);a.getInitialState=()=>p;let f;const y=()=>{var g,h;if(!u)return;i=!1,o.forEach(E=>{var b;return E((b=r())!=null?b:p)});const w=((h=s.onRehydrateStorage)==null?void 0:h.call(s,(g=r())!=null?g:p))||void 0;return Gn(u.getItem.bind(u))(s.name).then(E=>{if(E)if(typeof E.version=="number"&&E.version!==s.version){if(s.migrate){const b=s.migrate(E.state,E.version);return b instanceof Promise?b.then(A=>[!0,A]):[!0,b]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,E.state];return[!1,void 0]}).then(E=>{var b;const[A,I]=E;if(f=s.merge(I,(b=r())!=null?b:p),n(f,!0),A)return d()}).then(()=>{w?.(f,void 0),f=r(),i=!0,c.forEach(E=>E(f))}).catch(E=>{w?.(void 0,E)})};return a.persist={setOptions:g=>{s={...s,...g},g.storage&&(u=g.storage)},clearStorage:()=>{u?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>y(),hasHydrated:()=>i,onHydrate:g=>(o.add(g),()=>{o.delete(g)}),onFinishHydration:g=>(c.add(g),()=>{c.delete(g)})},s.skipHydration||y(),f||p},bd=gd,pa=e=>{let t;const n=new Set,r=(u,d)=>{const l=typeof u=="function"?u(t):u;if(!Object.is(l,t)){const p=t;t=d??(typeof l!="object"||l===null)?l:Object.assign({},t,l),n.forEach(f=>f(t,p))}},a=()=>t,o={setState:r,getState:a,getInitialState:()=>c,subscribe:u=>(n.add(u),()=>n.delete(u))},c=t=e(r,a,o);return o},Br=e=>e?pa(e):pa,wd=[{inputs:[{name:"preOpGas",type:"uint256"},{name:"paid",type:"uint256"},{name:"validAfter",type:"uint48"},{name:"validUntil",type:"uint48"},{name:"targetSuccess",type:"bool"},{name:"targetResult",type:"bytes"}],name:"ExecutionResult",type:"error"},{inputs:[{name:"opIndex",type:"uint256"},{name:"reason",type:"string"}],name:"FailedOp",type:"error"},{inputs:[{name:"sender",type:"address"}],name:"SenderAddressResult",type:"error"},{inputs:[{name:"aggregator",type:"address"}],name:"SignatureValidationFailed",type:"error"},{inputs:[{components:[{name:"preOpGas",type:"uint256"},{name:"prefund",type:"uint256"},{name:"sigFailed",type:"bool"},{name:"validAfter",type:"uint48"},{name:"validUntil",type:"uint48"},{name:"paymasterContext",type:"bytes"}],name:"returnInfo",type:"tuple"},{components:[{name:"stake",type:"uint256"},{name:"unstakeDelaySec",type:"uint256"}],name:"senderInfo",type:"tuple"},{components:[{name:"stake",type:"uint256"},{name:"unstakeDelaySec",type:"uint256"}],name:"factoryInfo",type:"tuple"},{components:[{name:"stake",type:"uint256"},{name:"unstakeDelaySec",type:"uint256"}],name:"paymasterInfo",type:"tuple"}],name:"ValidationResult",type:"error"},{inputs:[{components:[{name:"preOpGas",type:"uint256"},{name:"prefund",type:"uint256"},{name:"sigFailed",type:"bool"},{name:"validAfter",type:"uint48"},{name:"validUntil",type:"uint48"},{name:"paymasterContext",type:"bytes"}],name:"returnInfo",type:"tuple"},{components:[{name:"stake",type:"uint256"},{name:"unstakeDelaySec",type:"uint256"}],name:"senderInfo",type:"tuple"},{components:[{name:"stake",type:"uint256"},{name:"unstakeDelaySec",type:"uint256"}],name:"factoryInfo",type:"tuple"},{components:[{name:"stake",type:"uint256"},{name:"unstakeDelaySec",type:"uint256"}],name:"paymasterInfo",type:"tuple"},{components:[{name:"aggregator",type:"address"},{components:[{name:"stake",type:"uint256"},{name:"unstakeDelaySec",type:"uint256"}],name:"stakeInfo",type:"tuple"}],name:"aggregatorInfo",type:"tuple"}],name:"ValidationResultWithAggregation",type:"error"},{anonymous:!1,inputs:[{indexed:!0,name:"userOpHash",type:"bytes32"},{indexed:!0,name:"sender",type:"address"},{indexed:!1,name:"factory",type:"address"},{indexed:!1,name:"paymaster",type:"address"}],name:"AccountDeployed",type:"event"},{anonymous:!1,inputs:[],name:"BeforeExecution",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"account",type:"address"},{indexed:!1,name:"totalDeposit",type:"uint256"}],name:"Deposited",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"aggregator",type:"address"}],name:"SignatureAggregatorChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"account",type:"address"},{indexed:!1,name:"totalStaked",type:"uint256"},{indexed:!1,name:"unstakeDelaySec",type:"uint256"}],name:"StakeLocked",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"account",type:"address"},{indexed:!1,name:"withdrawTime",type:"uint256"}],name:"StakeUnlocked",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"account",type:"address"},{indexed:!1,name:"withdrawAddress",type:"address"},{indexed:!1,name:"amount",type:"uint256"}],name:"StakeWithdrawn",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"userOpHash",type:"bytes32"},{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"paymaster",type:"address"},{indexed:!1,name:"nonce",type:"uint256"},{indexed:!1,name:"success",type:"bool"},{indexed:!1,name:"actualGasCost",type:"uint256"},{indexed:!1,name:"actualGasUsed",type:"uint256"}],name:"UserOperationEvent",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"userOpHash",type:"bytes32"},{indexed:!0,name:"sender",type:"address"},{indexed:!1,name:"nonce",type:"uint256"},{indexed:!1,name:"revertReason",type:"bytes"}],name:"UserOperationRevertReason",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"account",type:"address"},{indexed:!1,name:"withdrawAddress",type:"address"},{indexed:!1,name:"amount",type:"uint256"}],name:"Withdrawn",type:"event"},{inputs:[],name:"SIG_VALIDATION_FAILED",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"initCode",type:"bytes"},{name:"sender",type:"address"},{name:"paymasterAndData",type:"bytes"}],name:"_validateSenderAndPaymaster",outputs:[],stateMutability:"view",type:"function"},{inputs:[{name:"unstakeDelaySec",type:"uint32"}],name:"addStake",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{name:"account",type:"address"}],name:"balanceOf",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"account",type:"address"}],name:"depositTo",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{name:"",type:"address"}],name:"deposits",outputs:[{name:"deposit",type:"uint112"},{name:"staked",type:"bool"},{name:"stake",type:"uint112"},{name:"unstakeDelaySec",type:"uint32"},{name:"withdrawTime",type:"uint48"}],stateMutability:"view",type:"function"},{inputs:[{name:"account",type:"address"}],name:"getDepositInfo",outputs:[{components:[{name:"deposit",type:"uint112"},{name:"staked",type:"bool"},{name:"stake",type:"uint112"},{name:"unstakeDelaySec",type:"uint32"},{name:"withdrawTime",type:"uint48"}],name:"info",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{name:"sender",type:"address"},{name:"key",type:"uint192"}],name:"getNonce",outputs:[{name:"nonce",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"initCode",type:"bytes"}],name:"getSenderAddress",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{name:"sender",type:"address"},{name:"nonce",type:"uint256"},{name:"initCode",type:"bytes"},{name:"callData",type:"bytes"},{name:"callGasLimit",type:"uint256"},{name:"verificationGasLimit",type:"uint256"},{name:"preVerificationGas",type:"uint256"},{name:"maxFeePerGas",type:"uint256"},{name:"maxPriorityFeePerGas",type:"uint256"},{name:"paymasterAndData",type:"bytes"},{name:"signature",type:"bytes"}],name:"userOp",type:"tuple"}],name:"getUserOpHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{components:[{components:[{name:"sender",type:"address"},{name:"nonce",type:"uint256"},{name:"initCode",type:"bytes"},{name:"callData",type:"bytes"},{name:"callGasLimit",type:"uint256"},{name:"verificationGasLimit",type:"uint256"},{name:"preVerificationGas",type:"uint256"},{name:"maxFeePerGas",type:"uint256"},{name:"maxPriorityFeePerGas",type:"uint256"},{name:"paymasterAndData",type:"bytes"},{name:"signature",type:"bytes"}],name:"userOps",type:"tuple[]"},{name:"aggregator",type:"address"},{name:"signature",type:"bytes"}],name:"opsPerAggregator",type:"tuple[]"},{name:"beneficiary",type:"address"}],name:"handleAggregatedOps",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{name:"sender",type:"address"},{name:"nonce",type:"uint256"},{name:"initCode",type:"bytes"},{name:"callData",type:"bytes"},{name:"callGasLimit",type:"uint256"},{name:"verificationGasLimit",type:"uint256"},{name:"preVerificationGas",type:"uint256"},{name:"maxFeePerGas",type:"uint256"},{name:"maxPriorityFeePerGas",type:"uint256"},{name:"paymasterAndData",type:"bytes"},{name:"signature",type:"bytes"}],name:"ops",type:"tuple[]"},{name:"beneficiary",type:"address"}],name:"handleOps",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"key",type:"uint192"}],name:"incrementNonce",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"callData",type:"bytes"},{components:[{components:[{name:"sender",type:"address"},{name:"nonce",type:"uint256"},{name:"callGasLimit",type:"uint256"},{name:"verificationGasLimit",type:"uint256"},{name:"preVerificationGas",type:"uint256"},{name:"paymaster",type:"address"},{name:"maxFeePerGas",type:"uint256"},{name:"maxPriorityFeePerGas",type:"uint256"}],name:"mUserOp",type:"tuple"},{name:"userOpHash",type:"bytes32"},{name:"prefund",type:"uint256"},{name:"contextOffset",type:"uint256"},{name:"preOpGas",type:"uint256"}],name:"opInfo",type:"tuple"},{name:"context",type:"bytes"}],name:"innerHandleOp",outputs:[{name:"actualGasCost",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"",type:"address"},{name:"",type:"uint192"}],name:"nonceSequenceNumber",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{components:[{name:"sender",type:"address"},{name:"nonce",type:"uint256"},{name:"initCode",type:"bytes"},{name:"callData",type:"bytes"},{name:"callGasLimit",type:"uint256"},{name:"verificationGasLimit",type:"uint256"},{name:"preVerificationGas",type:"uint256"},{name:"maxFeePerGas",type:"uint256"},{name:"maxPriorityFeePerGas",type:"uint256"},{name:"paymasterAndData",type:"bytes"},{name:"signature",type:"bytes"}],name:"op",type:"tuple"},{name:"target",type:"address"},{name:"targetCallData",type:"bytes"}],name:"simulateHandleOp",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{name:"sender",type:"address"},{name:"nonce",type:"uint256"},{name:"initCode",type:"bytes"},{name:"callData",type:"bytes"},{name:"callGasLimit",type:"uint256"},{name:"verificationGasLimit",type:"uint256"},{name:"preVerificationGas",type:"uint256"},{name:"maxFeePerGas",type:"uint256"},{name:"maxPriorityFeePerGas",type:"uint256"},{name:"paymasterAndData",type:"bytes"},{name:"signature",type:"bytes"}],name:"userOp",type:"tuple"}],name:"simulateValidation",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unlockStake",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"withdrawAddress",type:"address"}],name:"withdrawStake",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"withdrawAddress",type:"address"},{name:"withdrawAmount",type:"uint256"}],name:"withdrawTo",outputs:[],stateMutability:"nonpayable",type:"function"},{stateMutability:"payable",type:"receive"}];function Fs(e){const{authorization:t,factory:n,factoryData:r}=e;if(n==="0x7702"||n==="0x7702000000000000000000000000000000000000"){if(!t)return"0x7702000000000000000000000000000000000000";const a=t.address;return je([a,r??"0x"])}return n?je([n,r??"0x"]):"0x"}function $s(e){const{callGasLimit:t,callData:n,maxPriorityFeePerGas:r,maxFeePerGas:a,paymaster:s,paymasterData:i,paymasterPostOpGasLimit:o,paymasterVerificationGasLimit:c,sender:u,signature:d="0x",verificationGasLimit:l}=e,p=je([de(M(l||0n),{size:16}),de(M(t||0n),{size:16})]),f=Fs(e),y=je([de(M(r||0n),{size:16}),de(M(a||0n),{size:16})]),g=e.nonce??0n,h=s?je([s,de(M(c||0n),{size:16}),de(M(o||0n),{size:16}),i||"0x"]):"0x",w=e.preVerificationGas??0n;return{accountGasLimits:p,callData:n,initCode:f,gasFees:y,nonce:g,paymasterAndData:h,preVerificationGas:w,sender:u,signature:d}}const vd={PackedUserOperation:[{type:"address",name:"sender"},{type:"uint256",name:"nonce"},{type:"bytes",name:"initCode"},{type:"bytes",name:"callData"},{type:"bytes32",name:"accountGasLimits"},{type:"uint256",name:"preVerificationGas"},{type:"bytes32",name:"gasFees"},{type:"bytes",name:"paymasterAndData"}]};function kd(e){const{chainId:t,entryPointAddress:n,userOperation:r}=e,a=$s(r);return{types:vd,primaryType:"PackedUserOperation",domain:{name:"ERC4337",version:"1",chainId:t,verifyingContract:n},message:a}}function xd(e){const{chainId:t,entryPointAddress:n,entryPointVersion:r}=e,a=e.userOperation,{authorization:s,callData:i="0x",callGasLimit:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,paymasterAndData:l="0x",preVerificationGas:p,sender:f,verificationGasLimit:y}=a;if(r==="0.8")return Lt(kd({chainId:t,entryPointAddress:n,userOperation:a}));const g=(()=>{if(r==="0.6"){const h=a.initCode?.slice(0,42),w=a.initCode?.slice(42),E=Fs({authorization:s,factory:h,factoryData:w});return Ke([{type:"address"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"uint256"},{type:"uint256"},{type:"uint256"},{type:"uint256"},{type:"bytes32"}],[f,d,ce(E),ce(i),o,y,p,c,u,ce(l)])}if(r==="0.7"){const h=$s(a);return Ke([{type:"address"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"}],[h.sender,h.nonce,ce(h.initCode),ce(h.callData),h.accountGasLimits,h.preVerificationGas,h.gasFees,ce(h.paymasterAndData)])}throw new Error(`entryPointVersion "${r}" not supported.`)})();return ce(Ke([{type:"bytes32"},{type:"address"},{type:"uint256"}],[ce(g),n,BigInt(t)]))}async function Ed(e){const{extend:t,nonceKeyManager:n=Lu({source:{get(){return Date.now()},set(){}}}),...r}=e;let a=!1;const s=await e.getAddress();return{...t,...r,address:s,async getFactoryArgs(){return"isDeployed"in this&&await this.isDeployed()?{factory:void 0,factoryData:void 0}:e.getFactoryArgs()},async getNonce(i){const o=i?.key??BigInt(await n.consume({address:s,chainId:e.client.chain.id,client:e.client}));return e.getNonce?await e.getNonce({...i,key:o}):await Se(e.client,{abi:_c(["function getNonce(address, uint192) pure returns (uint256)"]),address:e.entryPoint.address,functionName:"getNonce",args:[s,o]})},async isDeployed(){return a?!0:(a=!!await W(e.client,Xt,"getCode")({address:s}),a)},...e.sign?{async sign(i){const[{factory:o,factoryData:c},u]=await Promise.all([this.getFactoryArgs(),e.sign(i)]);return o&&c?An({address:o,data:c,signature:u}):u}}:{},async signMessage(i){const[{factory:o,factoryData:c},u]=await Promise.all([this.getFactoryArgs(),e.signMessage(i)]);return o&&c&&o!=="0x7702"?An({address:o,data:c,signature:u}):u},async signTypedData(i){const[{factory:o,factoryData:c},u]=await Promise.all([this.getFactoryArgs(),e.signTypedData(i)]);return o&&c&&o!=="0x7702"?An({address:o,data:c,signature:u}):u},type:"smart"}}class Hn extends D{constructor({cause:t}){super("Smart Account is not deployed.",{cause:t,metaMessages:["This could arise when:","- No `factory`/`factoryData` or `initCode` properties are provided for Smart Account deployment.","- An incorrect `sender` address is provided."],name:"AccountNotDeployedError"})}}Object.defineProperty(Hn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa20/});class lt extends D{constructor({cause:t,data:n,message:r}={}){const a=r?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${a?`with reason: ${a}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=n}}Object.defineProperty(lt,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32521});Object.defineProperty(lt,"message",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class zn extends D{constructor({cause:t}){super("Failed to send funds to beneficiary.",{cause:t,name:"FailedToSendToBeneficiaryError"})}}Object.defineProperty(zn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa91/});class qn extends D{constructor({cause:t}){super("Gas value overflowed.",{cause:t,metaMessages:["This could arise when:","- one of the gas values exceeded 2**120 (uint120)"].filter(Boolean),name:"GasValuesOverflowError"})}}Object.defineProperty(qn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa94/});class Wn extends D{constructor({cause:t}){super("The `handleOps` function was called by the Bundler with a gas limit too low.",{cause:t,name:"HandleOpsOutOfGasError"})}}Object.defineProperty(Wn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa95/});class Vn extends D{constructor({cause:t,factory:n,factoryData:r,initCode:a}){super("Failed to simulate deployment for Smart Account.",{cause:t,metaMessages:["This could arise when:","- Invalid `factory`/`factoryData` or `initCode` properties are present","- Smart Account deployment execution ran out of gas (low `verificationGasLimit` value)",`- Smart Account deployment execution reverted with an error +`,n&&`factory: ${n}`,r&&`factoryData: ${r}`,a&&`initCode: ${a}`].filter(Boolean),name:"InitCodeFailedError"})}}Object.defineProperty(Vn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa13/});class Kn extends D{constructor({cause:t,factory:n,factoryData:r,initCode:a}){super("Smart Account initialization implementation did not create an account.",{cause:t,metaMessages:["This could arise when:","- `factory`/`factoryData` or `initCode` properties are invalid",`- Smart Account initialization implementation is incorrect +`,n&&`factory: ${n}`,r&&`factoryData: ${r}`,a&&`initCode: ${a}`].filter(Boolean),name:"InitCodeMustCreateSenderError"})}}Object.defineProperty(Kn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa15/});class Jn extends D{constructor({cause:t,factory:n,factoryData:r,initCode:a,sender:s}){super("Smart Account initialization implementation does not return the expected sender.",{cause:t,metaMessages:["This could arise when:",`Smart Account initialization implementation does not return a sender address +`,n&&`factory: ${n}`,r&&`factoryData: ${r}`,a&&`initCode: ${a}`,s&&`sender: ${s}`].filter(Boolean),name:"InitCodeMustReturnSenderError"})}}Object.defineProperty(Jn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa14/});class Zn extends D{constructor({cause:t}){super("Smart Account does not have sufficient funds to execute the User Operation.",{cause:t,metaMessages:["This could arise when:","- the Smart Account does not have sufficient funds to cover the required prefund, or","- a Paymaster was not provided"].filter(Boolean),name:"InsufficientPrefundError"})}}Object.defineProperty(Zn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa21/});class Yn extends D{constructor({cause:t}){super("Bundler attempted to call an invalid function on the EntryPoint.",{cause:t,name:"InternalCallOnlyError"})}}Object.defineProperty(Yn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa92/});class Qn extends D{constructor({cause:t}){super("Bundler used an invalid aggregator for handling aggregated User Operations.",{cause:t,name:"InvalidAggregatorError"})}}Object.defineProperty(Qn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa96/});class Xn extends D{constructor({cause:t,nonce:n}){super("Invalid Smart Account nonce used for User Operation.",{cause:t,metaMessages:[n&&`nonce: ${n}`].filter(Boolean),name:"InvalidAccountNonceError"})}}Object.defineProperty(Xn,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa25/});class er extends D{constructor({cause:t}){super("Bundler has not set a beneficiary address.",{cause:t,name:"InvalidBeneficiaryError"})}}Object.defineProperty(er,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa90/});class tn extends D{constructor({cause:t}){super("Invalid fields set on User Operation.",{cause:t,name:"InvalidFieldsError"})}}Object.defineProperty(tn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class tr extends D{constructor({cause:t,paymasterAndData:n}){super("Paymaster properties provided are invalid.",{cause:t,metaMessages:["This could arise when:","- the `paymasterAndData` property is of an incorrect length\n",n&&`paymasterAndData: ${n}`].filter(Boolean),name:"InvalidPaymasterAndDataError"})}}Object.defineProperty(tr,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa93/});class We extends D{constructor({cause:t}){super("Paymaster deposit for the User Operation is too low.",{cause:t,metaMessages:["This could arise when:","- the Paymaster has deposited less than the expected amount via the `deposit` function"].filter(Boolean),name:"PaymasterDepositTooLowError"})}}Object.defineProperty(We,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32508});Object.defineProperty(We,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa31/});class nr extends D{constructor({cause:t}){super("The `validatePaymasterUserOp` function on the Paymaster reverted.",{cause:t,name:"PaymasterFunctionRevertedError"})}}Object.defineProperty(nr,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa33/});class rr extends D{constructor({cause:t}){super("The Paymaster contract has not been deployed.",{cause:t,name:"PaymasterNotDeployedError"})}}Object.defineProperty(rr,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa30/});class nn extends D{constructor({cause:t}){super("UserOperation rejected because paymaster (or signature aggregator) is throttled/banned.",{cause:t,name:"PaymasterRateLimitError"})}}Object.defineProperty(nn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32504});class rn extends D{constructor({cause:t}){super("UserOperation rejected because paymaster (or signature aggregator) is throttled/banned.",{cause:t,name:"PaymasterStakeTooLowError"})}}Object.defineProperty(rn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32505});class ar extends D{constructor({cause:t}){super("Paymaster `postOp` function reverted.",{cause:t,name:"PaymasterPostOpFunctionRevertedError"})}}Object.defineProperty(ar,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa50/});class sr extends D{constructor({cause:t,factory:n,factoryData:r,initCode:a}){super("Smart Account has already been deployed.",{cause:t,metaMessages:["Remove the following properties and try again:",n&&"`factory`",r&&"`factoryData`",a&&"`initCode`"].filter(Boolean),name:"SenderAlreadyConstructedError"})}}Object.defineProperty(sr,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa10/});class an extends D{constructor({cause:t}){super("UserOperation rejected because account signature check failed (or paymaster signature, if the paymaster uses its data as signature).",{cause:t,name:"SignatureCheckFailedError"})}}Object.defineProperty(an,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32507});class ir extends D{constructor({cause:t}){super("The `validateUserOp` function on the Smart Account reverted.",{cause:t,name:"SmartAccountFunctionRevertedError"})}}Object.defineProperty(ir,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa23/});class sn extends D{constructor({cause:t}){super("UserOperation rejected because account specified unsupported signature aggregator.",{cause:t,name:"UnsupportedSignatureAggregatorError"})}}Object.defineProperty(sn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32506});class or extends D{constructor({cause:t}){super("User Operation expired.",{cause:t,metaMessages:["This could arise when:","- the `validAfter` or `validUntil` values returned from `validateUserOp` on the Smart Account are not satisfied"].filter(Boolean),name:"UserOperationExpiredError"})}}Object.defineProperty(or,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa22/});class cr extends D{constructor({cause:t}){super("Paymaster for User Operation expired.",{cause:t,metaMessages:["This could arise when:","- the `validAfter` or `validUntil` values returned from `validatePaymasterUserOp` on the Paymaster are not satisfied"].filter(Boolean),name:"UserOperationPaymasterExpiredError"})}}Object.defineProperty(cr,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa32/});class ur extends D{constructor({cause:t}){super("Signature provided for the User Operation is invalid.",{cause:t,metaMessages:["This could arise when:","- the `signature` for the User Operation is incorrectly computed, and unable to be verified by the Smart Account"].filter(Boolean),name:"UserOperationSignatureError"})}}Object.defineProperty(ur,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa24/});class dr extends D{constructor({cause:t}){super("Signature provided for the User Operation is invalid.",{cause:t,metaMessages:["This could arise when:","- the `signature` for the User Operation is incorrectly computed, and unable to be verified by the Paymaster"].filter(Boolean),name:"UserOperationPaymasterSignatureError"})}}Object.defineProperty(dr,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa34/});class on extends D{constructor({cause:t}){super("User Operation rejected by EntryPoint's `simulateValidation` during account creation or validation.",{cause:t,name:"UserOperationRejectedByEntryPointError"})}}Object.defineProperty(on,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32500});class cn extends D{constructor({cause:t}){super("User Operation rejected by Paymaster's `validatePaymasterUserOp`.",{cause:t,name:"UserOperationRejectedByPaymasterError"})}}Object.defineProperty(cn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32501});class un extends D{constructor({cause:t}){super("User Operation rejected with op code validation error.",{cause:t,name:"UserOperationRejectedByOpCodeError"})}}Object.defineProperty(un,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32502});class dn extends D{constructor({cause:t}){super("UserOperation out of time-range: either wallet or paymaster returned a time-range, and it is already expired (or will expire soon).",{cause:t,name:"UserOperationOutOfTimeRangeError"})}}Object.defineProperty(dn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32503});class Sd extends D{constructor({cause:t}){super(`An error occurred while executing user operation: ${t?.shortMessage}`,{cause:t,name:"UnknownBundlerError"})}}class lr extends D{constructor({cause:t}){super("User Operation verification gas limit exceeded.",{cause:t,metaMessages:["This could arise when:","- the gas used for verification exceeded the `verificationGasLimit`"].filter(Boolean),name:"VerificationGasLimitExceededError"})}}Object.defineProperty(lr,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa40/});class fr extends D{constructor({cause:t}){super("User Operation verification gas limit is too low.",{cause:t,metaMessages:["This could arise when:","- the `verificationGasLimit` is too low to verify the User Operation"].filter(Boolean),name:"VerificationGasLimitTooLowError"})}}Object.defineProperty(fr,"message",{enumerable:!0,configurable:!0,writable:!0,value:/aa41/});class Ad extends D{constructor(t,{callData:n,callGasLimit:r,docsPath:a,factory:s,factoryData:i,initCode:o,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,paymaster:l,paymasterAndData:p,paymasterData:f,paymasterPostOpGasLimit:y,paymasterVerificationGasLimit:g,preVerificationGas:h,sender:w,signature:E,verificationGasLimit:b}){const A=Ic({callData:n,callGasLimit:r,factory:s,factoryData:i,initCode:o,maxFeePerGas:typeof c<"u"&&`${na(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${na(u)} gwei`,nonce:d,paymaster:l,paymasterAndData:p,paymasterData:f,paymasterPostOpGasLimit:y,paymasterVerificationGasLimit:g,preVerificationGas:h,sender:w,signature:E,verificationGasLimit:b});super(t.shortMessage,{cause:t,docsPath:a,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",A].filter(Boolean),name:"UserOperationExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class _d extends D{constructor({hash:t}){super(`User Operation receipt with hash "${t}" could not be found. The User Operation may not have been processed yet.`,{name:"UserOperationReceiptNotFoundError"})}}class Id extends D{constructor({hash:t}){super(`User Operation with hash "${t}" could not be found.`,{name:"UserOperationNotFoundError"})}}class ma extends D{constructor({hash:t}){super(`Timed out while waiting for User Operation with hash "${t}" to be confirmed.`,{name:"WaitForUserOperationReceiptTimeoutError"})}}const Pd=[lt,tn,We,nn,rn,an,sn,dn,on,cn,un];function Od(e,t){const n=(e.details||"").toLowerCase();if(Hn.message.test(n))return new Hn({cause:e});if(zn.message.test(n))return new zn({cause:e});if(qn.message.test(n))return new qn({cause:e});if(Wn.message.test(n))return new Wn({cause:e});if(Vn.message.test(n))return new Vn({cause:e,factory:t.factory,factoryData:t.factoryData,initCode:t.initCode});if(Kn.message.test(n))return new Kn({cause:e,factory:t.factory,factoryData:t.factoryData,initCode:t.initCode});if(Jn.message.test(n))return new Jn({cause:e,factory:t.factory,factoryData:t.factoryData,initCode:t.initCode,sender:t.sender});if(Zn.message.test(n))return new Zn({cause:e});if(Yn.message.test(n))return new Yn({cause:e});if(Xn.message.test(n))return new Xn({cause:e,nonce:t.nonce});if(Qn.message.test(n))return new Qn({cause:e});if(er.message.test(n))return new er({cause:e});if(tr.message.test(n))return new tr({cause:e});if(We.message.test(n))return new We({cause:e});if(nr.message.test(n))return new nr({cause:e});if(rr.message.test(n))return new rr({cause:e});if(ar.message.test(n))return new ar({cause:e});if(ir.message.test(n))return new ir({cause:e});if(sr.message.test(n))return new sr({cause:e,factory:t.factory,factoryData:t.factoryData,initCode:t.initCode});if(or.message.test(n))return new or({cause:e});if(cr.message.test(n))return new cr({cause:e});if(dr.message.test(n))return new dr({cause:e});if(ur.message.test(n))return new ur({cause:e});if(lr.message.test(n))return new lr({cause:e});if(fr.message.test(n))return new fr({cause:e});const r=e.walk(a=>Pd.some(s=>s.code===a.code));if(r){if(r.code===lt.code)return new lt({cause:e,data:r.data,message:r.details});if(r.code===tn.code)return new tn({cause:e});if(r.code===We.code)return new We({cause:e});if(r.code===nn.code)return new nn({cause:e});if(r.code===rn.code)return new rn({cause:e});if(r.code===an.code)return new an({cause:e});if(r.code===sn.code)return new sn({cause:e});if(r.code===dn.code)return new dn({cause:e});if(r.code===on.code)return new on({cause:e});if(r.code===cn.code)return new cn({cause:e});if(r.code===un.code)return new un({cause:e})}return new Sd({cause:e})}function Gs(e,{calls:t,docsPath:n,...r}){const a=(()=>{const s=Od(e,r);if(t&&s instanceof lt){const i=Cd(s),o=t?.filter(c=>c.abi);if(i&&o.length>0)return Td({calls:o,revertData:i})}return s})();return new Ad(a,{docsPath:n,...r})}function Cd(e){let t;return e.walk(n=>{const r=n;if(typeof r.data=="string"||typeof r.data?.revertData=="string"||!(r instanceof D)&&typeof r.message=="string"){const a=(r.data?.revertData||r.data||r.message).match?.(/(0x[A-Za-z0-9]*)/);if(a)return t=a[1],!0}return!1}),t}function Td(e){const{calls:t,revertData:n}=e,{abi:r,functionName:a,args:s,to:i}=(()=>{const c=t?.filter(d=>!!d.abi);if(c.length===1)return c[0];const u=c.filter(d=>{try{return!!Pc({abi:d.abi,data:n})}catch{return!1}});return u.length===1?u[0]:{abi:[],functionName:c.reduce((d,l)=>`${d?`${d} | `:""}${l.functionName}`,""),args:void 0,to:void 0}})(),o=n==="0x"?new Oc({functionName:a}):new Cc({abi:r,data:n,functionName:a});return new Tc(o,{abi:r,args:s,contractAddress:i,functionName:a})}function Nd(e){const t={};return e.callGasLimit&&(t.callGasLimit=BigInt(e.callGasLimit)),e.preVerificationGas&&(t.preVerificationGas=BigInt(e.preVerificationGas)),e.verificationGasLimit&&(t.verificationGasLimit=BigInt(e.verificationGasLimit)),e.paymasterPostOpGasLimit&&(t.paymasterPostOpGasLimit=BigInt(e.paymasterPostOpGasLimit)),e.paymasterVerificationGasLimit&&(t.paymasterVerificationGasLimit=BigInt(e.paymasterVerificationGasLimit)),t}function bn(e){const t={};return typeof e.callData<"u"&&(t.callData=e.callData),typeof e.callGasLimit<"u"&&(t.callGasLimit=M(e.callGasLimit)),typeof e.factory<"u"&&(t.factory=e.factory),typeof e.factoryData<"u"&&(t.factoryData=e.factoryData),typeof e.initCode<"u"&&(t.initCode=e.initCode),typeof e.maxFeePerGas<"u"&&(t.maxFeePerGas=M(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(t.maxPriorityFeePerGas=M(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(t.nonce=M(e.nonce)),typeof e.paymaster<"u"&&(t.paymaster=e.paymaster),typeof e.paymasterAndData<"u"&&(t.paymasterAndData=e.paymasterAndData||"0x"),typeof e.paymasterData<"u"&&(t.paymasterData=e.paymasterData),typeof e.paymasterPostOpGasLimit<"u"&&(t.paymasterPostOpGasLimit=M(e.paymasterPostOpGasLimit)),typeof e.paymasterVerificationGasLimit<"u"&&(t.paymasterVerificationGasLimit=M(e.paymasterVerificationGasLimit)),typeof e.preVerificationGas<"u"&&(t.preVerificationGas=M(e.preVerificationGas)),typeof e.sender<"u"&&(t.sender=e.sender),typeof e.signature<"u"&&(t.signature=e.signature),typeof e.verificationGasLimit<"u"&&(t.verificationGasLimit=M(e.verificationGasLimit)),typeof e.authorization<"u"&&(t.eip7702Auth=Bd(e.authorization)),t}function Bd(e){return{address:e.address,chainId:M(e.chainId),nonce:M(e.nonce),r:e.r?M(BigInt(e.r),{size:32}):de("0x",{size:32}),s:e.s?M(BigInt(e.s),{size:32}):de("0x",{size:32}),yParity:e.yParity?M(e.yParity,{size:1}):de("0x",{size:32})}}async function Ld(e,t){const{chainId:n,entryPointAddress:r,context:a,...s}=t,i=bn(s),{paymasterPostOpGasLimit:o,paymasterVerificationGasLimit:c,...u}=await e.request({method:"pm_getPaymasterData",params:[{...i,callGasLimit:i.callGasLimit??"0x0",verificationGasLimit:i.verificationGasLimit??"0x0",preVerificationGas:i.preVerificationGas??"0x0"},r,M(n),a]});return{...u,...o&&{paymasterPostOpGasLimit:he(o)},...c&&{paymasterVerificationGasLimit:he(c)}}}async function Rd(e,t){const{chainId:n,entryPointAddress:r,context:a,...s}=t,i=bn(s),{paymasterPostOpGasLimit:o,paymasterVerificationGasLimit:c,...u}=await e.request({method:"pm_getPaymasterStubData",params:[{...i,callGasLimit:i.callGasLimit??"0x0",verificationGasLimit:i.verificationGasLimit??"0x0",preVerificationGas:i.preVerificationGas??"0x0"},r,M(n),a]});return{...u,...o&&{paymasterPostOpGasLimit:he(o)},...c&&{paymasterVerificationGasLimit:he(c)}}}const jd=["factory","fees","gas","paymaster","nonce","signature","authorization"];async function Lr(e,t){const n=t,{account:r=e.account,parameters:a=jd,stateOverride:s}=n;if(!r)throw new hn;const i=Ae(r),o=e,c=n.paymaster??o?.paymaster,u=typeof c=="string"?c:void 0,{getPaymasterStubData:d,getPaymasterData:l}=(()=>{if(c===!0)return{getPaymasterStubData:N=>W(o,Rd,"getPaymasterStubData")(N),getPaymasterData:N=>W(o,Ld,"getPaymasterData")(N)};if(typeof c=="object"){const{getPaymasterStubData:N,getPaymasterData:B}=c;return{getPaymasterStubData:B&&N?N:B,getPaymasterData:B&&N?B:void 0}}return{getPaymasterStubData:void 0,getPaymasterData:void 0}})(),p=n.paymasterContext?n.paymasterContext:o?.paymasterContext;let f={...n,paymaster:u,sender:i.address};const[y,g,h,w,E]=await Promise.all([(async()=>n.calls?i.encodeCalls(n.calls.map(N=>{const B=N;return B.abi?{data:oe(B),to:B.to,value:B.value}:B})):n.callData)(),(async()=>{if(!a.includes("factory"))return;if(n.initCode)return{initCode:n.initCode};if(n.factory&&n.factoryData)return{factory:n.factory,factoryData:n.factoryData};const{factory:N,factoryData:B}=await i.getFactoryArgs();return i.entryPoint.version==="0.6"?{initCode:N&&B?je([N,B]):void 0}:{factory:N,factoryData:B}})(),(async()=>{if(a.includes("fees")){if(typeof n.maxFeePerGas=="bigint"&&typeof n.maxPriorityFeePerGas=="bigint")return f;if(o?.userOperation?.estimateFeesPerGas){const N=await o.userOperation.estimateFeesPerGas({account:i,bundlerClient:o,userOperation:f});return{...f,...N}}try{const N=o.client??e,B=await W(N,ws,"estimateFeesPerGas")({chain:N.chain,type:"eip1559"});return{maxFeePerGas:typeof n.maxFeePerGas=="bigint"?n.maxFeePerGas:BigInt(2n*B.maxFeePerGas),maxPriorityFeePerGas:typeof n.maxPriorityFeePerGas=="bigint"?n.maxPriorityFeePerGas:BigInt(2n*B.maxPriorityFeePerGas)}}catch{return}}})(),(async()=>{if(a.includes("nonce"))return typeof n.nonce=="bigint"?n.nonce:i.getNonce()})(),(async()=>{if(a.includes("authorization")){if(typeof n.authorization=="object")return n.authorization;if(i.authorization&&!await i.isDeployed())return{...await id(i.client,i.authorization),r:"0xfffffffffffffffffffffffffffffff000000000000000000000000000000000",s:"0x7aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",yParity:1}}})()]);typeof y<"u"&&(f.callData=y),typeof g<"u"&&(f={...f,...g}),typeof h<"u"&&(f={...f,...h}),typeof w<"u"&&(f.nonce=w),typeof E<"u"&&(f.authorization=E),a.includes("signature")&&(typeof n.signature<"u"?f.signature=n.signature:f.signature=await i.getStubSignature(f)),i.entryPoint.version==="0.6"&&!f.initCode&&(f.initCode="0x");let b;async function A(){return b||(e.chain?e.chain.id:(b=await W(e,yn,"getChainId")({}),b))}let I=!1;if(a.includes("paymaster")&&d&&!u&&!n.paymasterAndData){const{isFinal:N=!1,sponsor:B,...j}=await d({chainId:await A(),entryPointAddress:i.entryPoint.address,context:p,...f});I=N,f={...f,...j}}if(i.entryPoint.version==="0.6"&&!f.paymasterAndData&&(f.paymasterAndData="0x"),a.includes("gas")){if(i.userOperation?.estimateGas){const N=await i.userOperation.estimateGas(f);f={...f,...N}}if(typeof f.callGasLimit>"u"||typeof f.preVerificationGas>"u"||typeof f.verificationGasLimit>"u"||f.paymaster&&typeof f.paymasterPostOpGasLimit>"u"||f.paymaster&&typeof f.paymasterVerificationGasLimit>"u"){const N=await W(o,Hs,"estimateUserOperationGas")({account:i,callGasLimit:0n,preVerificationGas:0n,verificationGasLimit:0n,stateOverride:s,...f.paymaster?{paymasterPostOpGasLimit:0n,paymasterVerificationGasLimit:0n}:{},...f});f={...f,callGasLimit:f.callGasLimit??N.callGasLimit,preVerificationGas:f.preVerificationGas??N.preVerificationGas,verificationGasLimit:f.verificationGasLimit??N.verificationGasLimit,paymasterPostOpGasLimit:f.paymasterPostOpGasLimit??N.paymasterPostOpGasLimit,paymasterVerificationGasLimit:f.paymasterVerificationGasLimit??N.paymasterVerificationGasLimit}}}if(a.includes("paymaster")&&l&&!u&&!n.paymasterAndData&&!I){const N=await l({chainId:await A(),entryPointAddress:i.entryPoint.address,context:p,...f});f={...f,...N}}return delete f.calls,delete f.parameters,delete f.paymasterContext,typeof f.paymaster!="string"&&delete f.paymaster,f}async function Hs(e,t){const{account:n=e.account,entryPointAddress:r,stateOverride:a}=t;if(!n&&!t.sender)throw new hn;const s=n?Ae(n):void 0,i=cs(a),o=s?await W(e,Lr,"prepareUserOperation")({...t,parameters:["authorization","factory","nonce","paymaster","signature"]}):t;try{const c=[bn(o),r??s?.entryPoint?.address],u=await e.request({method:"eth_estimateUserOperationGas",params:i?[...c,i]:[...c]});return Nd(u)}catch(c){const u=t.calls;throw Gs(c,{...o,...u?{calls:u}:{}})}}function Md(e){return e.request({method:"eth_supportedEntryPoints"})}function Dd(e){const t={...e};return e.callGasLimit&&(t.callGasLimit=BigInt(e.callGasLimit)),e.maxFeePerGas&&(t.maxFeePerGas=BigInt(e.maxFeePerGas)),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=BigInt(e.maxPriorityFeePerGas)),e.nonce&&(t.nonce=BigInt(e.nonce)),e.paymasterPostOpGasLimit&&(t.paymasterPostOpGasLimit=BigInt(e.paymasterPostOpGasLimit)),e.paymasterVerificationGasLimit&&(t.paymasterVerificationGasLimit=BigInt(e.paymasterVerificationGasLimit)),e.preVerificationGas&&(t.preVerificationGas=BigInt(e.preVerificationGas)),e.verificationGasLimit&&(t.verificationGasLimit=BigInt(e.verificationGasLimit)),t}async function Ud(e,{hash:t}){const n=await e.request({method:"eth_getUserOperationByHash",params:[t]},{dedupe:!0});if(!n)throw new Id({hash:t});const{blockHash:r,blockNumber:a,entryPoint:s,transactionHash:i,userOperation:o}=n;return{blockHash:r,blockNumber:BigInt(a),entryPoint:s,transactionHash:i,userOperation:Dd(o)}}function Fd(e){const t={...e};return e.actualGasCost&&(t.actualGasCost=BigInt(e.actualGasCost)),e.actualGasUsed&&(t.actualGasUsed=BigInt(e.actualGasUsed)),e.logs&&(t.logs=e.logs.map(n=>De(n))),e.receipt&&(t.receipt=Nc(t.receipt)),t}async function zs(e,{hash:t}){const n=await e.request({method:"eth_getUserOperationReceipt",params:[t]},{dedupe:!0});if(!n)throw new _d({hash:t});return Fd(n)}async function $d(e,t){const{account:n=e.account,entryPointAddress:r}=t;if(!n&&!t.sender)throw new hn;const a=n?Ae(n):void 0,s=a?await W(e,Lr,"prepareUserOperation")(t):t,i=t.signature||await a?.signUserOperation?.(s),o=bn({...s,signature:i});try{return await e.request({method:"eth_sendUserOperation",params:[o,r??a?.entryPoint?.address]},{retryCount:0})}catch(c){const u=t.calls;throw Gs(c,{...s,...u?{calls:u}:{},signature:i})}}function Gd(e,t){const{hash:n,pollingInterval:r=e.pollingInterval,retryCount:a,timeout:s=12e4}=t;let i=0;const o=ut(["waitForUserOperationReceipt",e.uid,n]);return new Promise((c,u)=>{const d=dt(o,{resolve:c,reject:u},l=>{const p=y=>{f(),y(),d()},f=Bt(async()=>{a&&i>=a&&p(()=>l.reject(new ma({hash:n})));try{const y=await W(e,zs,"getUserOperationReceipt")({hash:n});p(()=>l.resolve(y))}catch(y){const g=y;g.name!=="UserOperationReceiptNotFoundError"&&p(()=>l.reject(g))}i++},{emitOnBegin:!0,interval:r});return s&&setTimeout(()=>p(()=>l.reject(new ma({hash:n}))),s),f})})}function Hd(e){return{estimateUserOperationGas:t=>Hs(e,t),getChainId:()=>yn(e),getSupportedEntryPoints:()=>Md(e),getUserOperation:t=>Ud(e,t),getUserOperationReceipt:t=>zs(e,t),prepareUserOperation:t=>Lr(e,t),sendUserOperation:t=>$d(e,t),waitForUserOperationReceipt:t=>Gd(e,t)}}function zd(e){const{client:t,key:n="bundler",name:r="Bundler Client",paymaster:a,paymasterContext:s,transport:i,userOperation:o}=e;return Object.assign(vs({...e,chain:e.chain??t?.chain,key:n,name:r,transport:i,type:"bundlerClient"}),{client:t,paymaster:a,paymasterContext:s,userOperation:o}).extend(Hd)}const qd="0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",Wd="0.1.1";function Vd(){return Wd}class Y extends Error{constructor(t,n={}){const r=(()=>{if(n.cause instanceof Y){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause?.message?n.cause.message:n.details})(),a=n.cause instanceof Y&&n.cause.docsPath||n.docsPath,i=`https://oxlib.sh${a??""}`,o=[t||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||a?["",r?`Details: ${r}`:void 0,a?`See: ${i}`:void 0]:[]].filter(c=>typeof c=="string").join(` +`);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Vd()}`}),this.cause=n.cause,this.details=r,this.docs=i,this.docsPath=a,this.shortMessage=t}walk(t){return qs(this,t)}}function qs(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?qs(e.cause,t):t?null:e}const Kd="#__bigint";function wn(e,t,n){return JSON.stringify(e,(r,a)=>typeof a=="bigint"?a.toString()+Kd:a,n)}function Jd(e,t){if(pt(e)>t)throw new ll({givenSize:pt(e),maxSize:t})}function Zd(e,t){if(typeof t=="number"&&t>0&&t>pt(e)-1)throw new ei({offset:t,position:"start",size:pt(e)})}function Yd(e,t,n){if(typeof t=="number"&&typeof n=="number"&&pt(e)!==n-t)throw new ei({offset:n,position:"end",size:pt(e)})}const _e={zero:48,nine:57,A:65,F:70,a:97,f:102};function ha(e){if(e>=_e.zero&&e<=_e.nine)return e-_e.zero;if(e>=_e.A&&e<=_e.F)return e-(_e.A-10);if(e>=_e.a&&e<=_e.f)return e-(_e.a-10)}function Rr(e,t){if(Ue(e)>t)throw new ol({givenSize:Ue(e),maxSize:t})}function Qd(e,t){if(typeof t=="number"&&t>0&&t>Ue(e)-1)throw new Zs({offset:t,position:"start",size:Ue(e)})}function Xd(e,t,n){if(typeof t=="number"&&typeof n=="number"&&Ue(e)!==n-t)throw new Zs({offset:n,position:"end",size:Ue(e)})}function Ws(e,t={}){const{dir:n,size:r=32}=t;if(r===0)return e;const a=e.replace("0x","");if(a.length>r*2)throw new cl({size:Math.ceil(a.length/2),targetSize:r,type:"Hex"});return`0x${a[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const el=new TextEncoder,tl=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function nl(e,t={}){const{strict:n=!1}=t;if(!e)throw new ya(e);if(typeof e!="string")throw new ya(e);if(n&&!/^0x[0-9a-fA-F]*$/.test(e))throw new ga(e);if(!e.startsWith("0x"))throw new ga(e)}function vn(...e){return`0x${e.reduce((t,n)=>t+n.replace("0x",""),"")}`}function Vs(e){return e instanceof Uint8Array?ft(e):Array.isArray(e)?ft(new Uint8Array(e)):e}function ft(e,t={}){let n="";for(let a=0;as||a>1n;return r<=i?r:r-s-1n}function sl(e,t={}){const{strict:n=!1}=t;try{return nl(e,{strict:n}),!0}catch{return!1}}class il extends Y{constructor({max:t,min:n,signed:r,size:a,value:s}){super(`Number \`${s}\` is not in safe${a?` ${a*8}-bit`:""}${r?" signed":" unsigned"} integer range ${t?`(\`${n}\` to \`${t}\`)`:`(above \`${n}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class ya extends Y{constructor(t){super(`Value \`${typeof t=="object"?wn(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class ga extends Y{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}let ol=class extends Y{constructor({givenSize:t,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}},Zs=class extends Y{constructor({offset:t,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}};class cl extends Y{constructor({size:t,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function ul(e){if(!(e instanceof Uint8Array)){if(!e)throw new Dt(e);if(typeof e!="object")throw new Dt(e);if(!("BYTES_PER_ELEMENT"in e))throw new Dt(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new Dt(e)}}function Ys(e){return e instanceof Uint8Array?e:typeof e=="string"?Xs(e):Qs(e)}function Qs(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Xs(e,t={}){const{size:n}=t;let r=e;n&&(Rr(e,n),r=Js(e,n));let a=r.slice(2);a.length%2&&(a=`0${a}`);const s=a.length/2,i=new Uint8Array(s);for(let o=0,c=0;o"u"){if(r!==3&&r!==2)throw new va({prefix:r,cause:new hl});return}throw new ml({publicKey:e})}function fl(e){const t=(()=>{if(sl(e))return ri(e);if(dl(e))return pl(e);const{prefix:n,x:r,y:a}=e;return typeof r=="bigint"&&typeof a=="bigint"?{prefix:n??4,x:r,y:a}:{prefix:n,x:r}})();return ni(t),t}function pl(e){return ri(ft(e))}function ri(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new gl({publicKey:e});if(e.length===130){const r=BigInt(me(e,0,32)),a=BigInt(me(e,32,64));return{prefix:4,x:r,y:a}}if(e.length===132){const r=Number(me(e,0,1)),a=BigInt(me(e,1,33)),s=BigInt(me(e,33,65));return{prefix:r,x:a,y:s}}const t=Number(me(e,0,1)),n=BigInt(me(e,1,33));return{prefix:t,x:n}}function jr(e,t={}){ni(e);const{prefix:n,x:r,y:a}=e,{includePrefix:s=!0}=t;return vn(s?Me(n,{size:1}):"0x",Me(r,{size:32}),typeof a=="bigint"?Me(a,{size:32}):"0x")}class ml extends Y{constructor({publicKey:t}){super(`Value \`${wn(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class va extends Y{constructor({prefix:t,cause:n}){super(`Prefix "${t}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class hl extends Y{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class yl extends Y{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let gl=class extends Y{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Ue(Vs(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const ka=2n**256n-1n;function bl(e,t={}){const{recovered:n}=t;if(typeof e.r>"u")throw new _n({signature:e});if(typeof e.s>"u")throw new _n({signature:e});if(n&&typeof e.yParity>"u")throw new _n({signature:e});if(e.r<0n||e.r>ka)throw new El({value:e.r});if(e.s<0n||e.s>ka)throw new Sl({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new Mr({value:e.yParity})}function ai(e){if(e.length!==130&&e.length!==132)throw new xl({signature:e});const t=BigInt(me(e,0,32)),n=BigInt(me(e,32,64)),r=(()=>{const a=+`0x${e.slice(130)}`;if(!Number.isNaN(a))try{return vl(a)}catch{throw new Mr({value:a})}})();return typeof r>"u"?{r:t,s:n}:{r:t,s:n,yParity:r}}function wl(e){bl(e);const t=e.r,n=e.s;return vn(Me(t,{size:32}),Me(n,{size:32}),typeof e.yParity=="number"?Me(kl(e.yParity),{size:1}):"0x")}function vl(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new Al({value:e})}function kl(e){if(e===0)return 27;if(e===1)return 28;throw new Mr({value:e})}class xl extends Y{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Ue(Vs(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class _n extends Y{constructor({signature:t}){super(`Signature \`${wn(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class El extends Y{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class Sl extends Y{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class Mr extends Y{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class Al extends Y{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}const _l=new TextDecoder,Ut=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)]));({...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t]))});function Il(e,t={}){const{pad:n=!0,url:r=!1}=t,a=new Uint8Array(Math.ceil(e.length/3)*4);for(let c=0,u=0;u>18],a[c+1]=Ut[d>>12&63],a[c+2]=Ut[d>>6&63],a[c+3]=Ut[d&63]}const s=e.length%3,i=Math.floor(e.length/3)*4+(s&&s+1);let o=_l.decode(new Uint8Array(a.buffer,0,i));return n&&s===1&&(o+="=="),n&&s===2&&(o+="="),r&&(o=o.replaceAll("+","-").replaceAll("/","_")),o}function Pl(e,t={}){return Il(Xs(e),t)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function xa(e){e.lowS!==void 0&&en("lowS",e.lowS),e.prehash!==void 0&&en("prehash",e.prehash)}class Ol extends Error{constructor(t=""){super(t)}}const Pe={Err:Ol,_tlv:{encode:(e,t)=>{const{Err:n}=Pe;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const r=t.length/2,a=Mt(r);if(a.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Mt(a.length/2|128):"";return Mt(e)+s+a+t},decode(e,t){const{Err:n}=Pe;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const a=t[r++],s=!!(a&128);let i=0;if(!s)i=a;else{const c=a&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=t.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const d of u)i=i<<8|d;if(r+=c,i<128)throw new n("tlv.decode(long): not minimal encoding")}const o=t.subarray(r,r+i);if(o.length!==i)throw new n("tlv.decode: wrong value length");return{v:o,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=Pe;if(e{const{px:P,py:x,pz:m}=j;if(n.eql(m,n.ONE))return{x:P,y:x};const k=j.is0();v==null&&(v=k?n.ONE:n.inv(m));const C=n.mul(P,v),O=n.mul(x,v),L=n.mul(m,v);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(L,n.ONE))throw new Error("invZ was invalid");return{x:C,y:O}}),b=aa(j=>{if(j.is0()){if(t.allowInfinityPoint&&!n.is0(j.py))return;throw new Error("bad point: ZERO")}const{x:v,y:P}=j.toAffine();if(!n.isValid(v)||!n.isValid(P))throw new Error("bad point: x or y not field elements");if(!f(v,P))throw new Error("bad point: equation left != right");if(!j.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(j,v,P,x,m){return P=new I(n.mul(P.px,j),P.py,P.pz),v=sa(x,v),P=sa(m,P),v.add(P)}class I{constructor(v,P,x){this.px=h("x",v),this.py=h("y",P,!0),this.pz=h("z",x),Object.freeze(this)}static fromAffine(v){const{x:P,y:x}=v||{};if(!v||!n.isValid(P)||!n.isValid(x))throw new Error("invalid affine point");if(v instanceof I)throw new Error("projective point not allowed");return n.is0(P)&&n.is0(x)?I.ZERO:new I(P,x,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){return Uc(I,"pz",v)}static fromBytes(v){return ra(v),I.fromHex(v)}static fromHex(v){const P=I.fromAffine(l(pe("pointHex",v)));return P.assertValidity(),P}static fromPrivateKey(v){const P=si(r,t.allowedPrivateKeyLengths,t.wrapPrivateKey);return I.BASE.multiply(P(v))}static msm(v,P){return Fc(I,r,v,P)}precompute(v=8,P=!0){return B.setWindowSize(this,v),P||this.multiply(Ft),this}_setWindowSize(v){this.precompute(v)}assertValidity(){b(this)}hasEvenY(){const{y:v}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(v)}equals(v){w(v);const{px:P,py:x,pz:m}=this,{px:k,py:C,pz:O}=v,L=n.eql(n.mul(P,O),n.mul(k,m)),R=n.eql(n.mul(x,O),n.mul(C,m));return L&&R}negate(){return new I(this.px,n.neg(this.py),this.pz)}double(){const{a:v,b:P}=e,x=n.mul(P,Ft),{px:m,py:k,pz:C}=this;let O=n.ZERO,L=n.ZERO,R=n.ZERO,S=n.mul(m,m),$=n.mul(k,k),q=n.mul(C,C),F=n.mul(m,k);return F=n.add(F,F),R=n.mul(m,C),R=n.add(R,R),O=n.mul(v,R),L=n.mul(x,q),L=n.add(O,L),O=n.sub($,L),L=n.add($,L),L=n.mul(O,L),O=n.mul(F,O),R=n.mul(x,R),q=n.mul(v,q),F=n.sub(S,q),F=n.mul(v,F),F=n.add(F,R),R=n.add(S,S),S=n.add(R,S),S=n.add(S,q),S=n.mul(S,F),L=n.add(L,S),q=n.mul(k,C),q=n.add(q,q),S=n.mul(q,F),O=n.sub(O,S),R=n.mul(q,$),R=n.add(R,R),R=n.add(R,R),new I(O,L,R)}add(v){w(v);const{px:P,py:x,pz:m}=this,{px:k,py:C,pz:O}=v;let L=n.ZERO,R=n.ZERO,S=n.ZERO;const $=e.a,q=n.mul(e.b,Ft);let F=n.mul(P,k),ee=n.mul(x,C),te=n.mul(m,O),ne=n.add(P,x),K=n.add(k,C);ne=n.mul(ne,K),K=n.add(F,ee),ne=n.sub(ne,K),K=n.add(P,m);let se=n.add(k,O);return K=n.mul(K,se),se=n.add(F,te),K=n.sub(K,se),se=n.add(x,m),L=n.add(C,O),se=n.mul(se,L),L=n.add(ee,te),se=n.sub(se,L),S=n.mul($,K),L=n.mul(q,te),S=n.add(L,S),L=n.sub(ee,S),S=n.add(ee,S),R=n.mul(L,S),ee=n.add(F,F),ee=n.add(ee,F),te=n.mul($,te),K=n.mul(q,K),ee=n.add(ee,te),te=n.sub(F,te),te=n.mul($,te),K=n.add(K,te),F=n.mul(ee,K),R=n.add(R,F),F=n.mul(se,K),L=n.mul(ne,L),L=n.sub(L,F),F=n.mul(ne,ee),S=n.mul(se,S),S=n.add(S,F),new I(L,R,S)}subtract(v){return this.add(v.negate())}is0(){return this.equals(I.ZERO)}multiply(v){const{endo:P}=t;if(!r.isValidNot0(v))throw new Error("invalid scalar: out of range");let x,m;const k=C=>B.wNAFCached(this,C,I.normalizeZ);if(P){const{k1neg:C,k1:O,k2neg:L,k2:R}=P.splitScalar(v),{p:S,f:$}=k(O),{p:q,f:F}=k(R);m=$.add(F),x=A(P.beta,S,q,C,L)}else{const{p:C,f:O}=k(v);x=C,m=O}return I.normalizeZ([x,m])[0]}multiplyUnsafe(v){const{endo:P}=t,x=this;if(!r.isValid(v))throw new Error("invalid scalar: out of range");if(v===St||x.is0())return I.ZERO;if(v===At)return x;if(B.hasPrecomputes(this))return this.multiply(v);if(P){const{k1neg:m,k1:k,k2neg:C,k2:O}=P.splitScalar(v),{p1:L,p2:R}=$c(I,x,k,O);return A(P.beta,L,R,m,C)}else return B.wNAFCachedUnsafe(x,v)}multiplyAndAddUnsafe(v,P,x){const m=this.multiplyUnsafe(P).add(v.multiplyUnsafe(x));return m.is0()?void 0:m}toAffine(v){return E(this,v)}isTorsionFree(){const{isTorsionFree:v}=t;return a===At?!0:v?v(I,this):B.wNAFCachedUnsafe(this,s).is0()}clearCofactor(){const{clearCofactor:v}=t;return a===At?this:v?v(I,this):this.multiplyUnsafe(a)}toBytes(v=!0){return en("isCompressed",v),this.assertValidity(),d(I,this,v)}toRawBytes(v=!0){return this.toBytes(v)}toHex(v=!0){return Rn(this.toBytes(v))}toString(){return``}}I.BASE=new I(e.Gx,e.Gy,n.ONE),I.ZERO=new I(n.ZERO,n.ONE,n.ZERO),I.Fp=n,I.Fn=r;const N=r.BITS,B=Rc(I,t.endo?Math.ceil(N/2):N);return I}function ii(e){return Uint8Array.of(e?2:3)}function Ll(e,t,n={}){ks(t,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=t.randomBytes||jc,a=t.hmac||((x,...m)=>Mc.hmac(t.hash,x,nt(...m))),{Fp:s,Fn:i}=e,{ORDER:o,BITS:c}=i;function u(x){const m=o>>At;return x>m}function d(x){return u(x)?i.neg(x):x}function l(x,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${x}: out of range 1..CURVE.n`)}class p{constructor(m,k,C){l("r",m),l("s",k),this.r=m,this.s=k,C!=null&&(this.recovery=C),Object.freeze(this)}static fromCompact(m){const k=i.BYTES,C=pe("compactSignature",m,k*2);return new p(i.fromBytes(C.subarray(0,k)),i.fromBytes(C.subarray(k,k*2)))}static fromDER(m){const{r:k,s:C}=Pe.toSig(pe("DER",m));return new p(k,C)}assertValidity(){}addRecoveryBit(m){return new p(this.r,this.s,m)}recoverPublicKey(m){const k=s.ORDER,{r:C,s:O,recovery:L}=this;if(L==null||![0,1,2,3].includes(L))throw new Error("recovery id invalid");if(o*Cl1)throw new Error("recovery id is ambiguous for h>1 curve");const S=L===2||L===3?C+o:C;if(!s.isValid(S))throw new Error("recovery id 2 or 3 invalid");const $=s.toBytes(S),q=e.fromHex(nt(ii((L&1)===0),$)),F=i.inv(S),ee=b(pe("msgHash",m)),te=i.create(-ee*F),ne=i.create(O*F),K=e.BASE.multiplyUnsafe(te).add(q.multiplyUnsafe(ne));if(K.is0())throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return u(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,i.neg(this.s),this.recovery):this}toBytes(m){if(m==="compact")return nt(i.toBytes(this.r),i.toBytes(this.s));if(m==="der")return Gc(Pe.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Rn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Rn(this.toBytes("compact"))}}const f=si(i,n.allowedPrivateKeyLengths,n.wrapPrivateKey),y={isValidPrivateKey(x){try{return f(x),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const x=o;return Hc(r(zc(x)),x)},precompute(x=8,m=e.BASE){return m.precompute(x,!1)}};function g(x,m=!0){return e.fromPrivateKey(x).toBytes(m)}function h(x){if(typeof x=="bigint")return!1;if(x instanceof e)return!0;const k=pe("key",x).length,C=s.BYTES,O=C+1,L=2*C+1;if(!(n.allowedPrivateKeyLengths||i.BYTES===O))return k===O||k===L}function w(x,m,k=!0){if(h(x)===!0)throw new Error("first arg must be private key");if(h(m)===!1)throw new Error("second arg must be public key");return e.fromHex(m).multiply(f(x)).toBytes(k)}const E=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");const m=xs(x),k=x.length*8-c;return k>0?m>>BigInt(k):m},b=t.bits2int_modN||function(x){return i.create(E(x))},A=Dc(c);function I(x){return Vc("num < 2^"+c,x,St,A),i.toBytes(x)}function N(x,m,k=B){if(["recovered","canonical"].some(ne=>ne in k))throw new Error("sign() legacy options not supported");const{hash:C}=t;let{lowS:O,prehash:L,extraEntropy:R}=k;O==null&&(O=!0),x=pe("msgHash",x),xa(k),L&&(x=pe("prehashed msgHash",C(x)));const S=b(x),$=f(m),q=[I($),I(S)];if(R!=null&&R!==!1){const ne=R===!0?r(s.BYTES):R;q.push(pe("extraEntropy",ne))}const F=nt(...q),ee=S;function te(ne){const K=E(ne);if(!i.isValidNot0(K))return;const se=i.inv(K),yt=e.BASE.multiply(K).toAffine(),Ye=i.create(yt.x);if(Ye===St)return;const $e=i.create(se*i.create(ee+Ye*$));if($e===St)return;let Sn=(yt.x===Ye?0:2)|Number(yt.y&At),Qe=$e;return O&&u($e)&&(Qe=d($e),Sn^=1),new p(Ye,Qe,Sn)}return{seed:F,k2sig:te}}const B={lowS:t.lowS,prehash:!1},j={lowS:t.lowS,prehash:!1};function v(x,m,k=B){const{seed:C,k2sig:O}=N(x,m,k);return qc(t.hash.outputLen,i.BYTES,a)(C,O)}e.BASE.precompute(8);function P(x,m,k,C=j){const O=x;m=pe("msgHash",m),k=pe("publicKey",k),xa(C);const{lowS:L,prehash:R,format:S}=C;if("strict"in C)throw new Error("options.strict was renamed to lowS");if(S!==void 0&&!["compact","der","js"].includes(S))throw new Error('format must be "compact", "der" or "js"');const $=typeof O=="string"||Wc(O),q=!$&&!S&&typeof O=="object"&&O!==null&&typeof O.r=="bigint"&&typeof O.s=="bigint";if(!$&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,ee;try{if(q)if(S===void 0||S==="js")F=new p(O.r,O.s);else throw new Error("invalid format");if($){try{S!=="compact"&&(F=p.fromDER(O))}catch(Qe){if(!(Qe instanceof Pe.Err))throw Qe}!F&&S!=="der"&&(F=p.fromCompact(O))}ee=e.fromHex(k)}catch{return!1}if(!F||L&&F.hasHighS())return!1;R&&(m=t.hash(m));const{r:te,s:ne}=F,K=b(m),se=i.inv(ne),yt=i.create(K*se),Ye=i.create(te*se),$e=e.BASE.multiplyUnsafe(yt).add(ee.multiplyUnsafe(Ye));return $e.is0()?!1:i.create($e.x)===te}return Object.freeze({getPublicKey:g,getSharedSecret:w,sign:v,verify:P,utils:y,Point:e,Signature:p})}function Rl(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=gn(t.n,e.nBitLength),a={Fp:n,Fn:r,allowedPrivateKeyLengths:e.allowedPrivateKeyLengths,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,wrapPrivateKey:e.wrapPrivateKey,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:a}}function jl(e){const{CURVE:t,curveOpts:n}=Rl(e),r={hash:e.hash,hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,ecdsaOpts:r}}function Ml(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}function Dl(e){const{CURVE:t,curveOpts:n,ecdsaOpts:r}=jl(e),a=Bl(t,n),s=Ll(a,r,n);return Ml(e,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Dr(e,t){const n=r=>Dl({...e,hash:r});return{...n(t),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const oi={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},ci={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},ui={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Ul=gn(oi.p),Fl=gn(ci.p),$l=gn(ui.p),Gl=Dr({...oi,Fp:Ul,lowS:!1},Kc);Dr({...ci,Fp:Fl,lowS:!1},Jc);Dr({...ui,Fp:$l,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Zc);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ea=Gl;Uint8Array.from([105,171,180,181,160,222,75,198,42,42,32,31,141,37,186,233]);function Hl(e={}){const{flag:t=5,rpId:n=window.location.hostname,signCount:r=0}=e,a=ti(Ks(n)),s=Me(t,{size:1}),i=Me(r,{size:4});return vn(a,s,i)}function zl(e){const{challenge:t,crossOrigin:n=!1,extraClientData:r,origin:a=window.location.origin}=e;return JSON.stringify({type:"webauthn.get",challenge:Pl(t,{url:!0,pad:!1}),origin:a,crossOrigin:n,...r})}function ql(e){const{challenge:t,crossOrigin:n,extraClientData:r,flag:a,origin:s,rpId:i,signCount:o,userVerification:c="required"}=e,u=Hl({flag:a,rpId:i,signCount:o}),d=zl({challenge:t,crossOrigin:n,extraClientData:r,origin:s}),l=ti(Ks(d)),p=d.indexOf('"challenge"'),f=d.indexOf('"type"'),y={authenticatorData:u,clientDataJSON:d,challengeIndex:p,typeIndex:f,userVerificationRequired:c==="required"},g=vn(u,l);return{metadata:y,payload:g}}async function Wl(e={}){const{extractable:t=!1}=e,n=await globalThis.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},t,["sign","verify"]),r=await globalThis.crypto.subtle.exportKey("raw",n.publicKey),a=fl(new Uint8Array(r));return{privateKey:n.privateKey,publicKey:a}}async function Vl(e){const{payload:t,privateKey:n}=e,r=await globalThis.crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},n,Ys(t)),a=Qs(new Uint8Array(r)),s=wa(ba(a,0,32));let i=wa(ba(a,32,64));return i>Ea.CURVE.n/2n&&(i=Ea.CURVE.n-i),{r:s,s:i}}const ht="4.3.6",di="@coinbase/wallet-sdk",Kl=()=>({chains:[]}),Jl=()=>({keys:{}}),Zl=()=>({account:{}}),Yl=()=>({subAccount:void 0}),Ql=()=>({subAccountConfig:{}}),Xl=()=>({spendPermissions:[]}),ef=()=>({config:{version:ht}}),X=Br(bd((...e)=>Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Kl(...e)),Jl(...e)),Zl(...e)),Yl(...e)),Xl(...e)),ef(...e)),Ql(...e)),{name:"cbwsdk.store",storage:Us(()=>localStorage),partialize:e=>({chains:e.chains,keys:e.keys,account:e.account,subAccount:e.subAccount,spendPermissions:e.spendPermissions,config:e.config})})),tf={get:()=>X.getState().subAccountConfig,set:e=>{X.setState(t=>({subAccountConfig:Object.assign(Object.assign({},t.subAccountConfig),e)}))},clear:()=>{X.setState({subAccountConfig:{}})}},nf={get:()=>X.getState().subAccount,set:e=>{X.setState(t=>({subAccount:t.subAccount?Object.assign(Object.assign({},t.subAccount),e):Object.assign({address:e.address},e)}))},clear:()=>{X.setState({subAccount:void 0})}},rf={get:()=>X.getState().spendPermissions,set:e=>{X.setState({spendPermissions:e})},clear:()=>{X.setState({spendPermissions:[]})}},af={get:()=>X.getState().account,set:e=>{X.setState(t=>({account:Object.assign(Object.assign({},t.account),e)}))},clear:()=>{X.setState({account:{}})}},sf={get:()=>X.getState().chains,set:e=>{X.setState({chains:e})},clear:()=>{X.setState({chains:[]})}},of={get:e=>X.getState().keys[e],set:(e,t)=>{X.setState(n=>({keys:Object.assign(Object.assign({},n.keys),{[e]:t})}))},clear:()=>{X.setState({keys:{}})}},li={get:()=>X.getState().config,set:e=>{X.setState(t=>({config:Object.assign(Object.assign({},t.config),e)}))}},cf={subAccounts:nf,subAccountsConfig:tf,spendPermissions:rf,account:af,chains:sf,keys:of,config:li},T=Object.assign(Object.assign({},X),cf),uf='!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ClientAnalytics=t():e.ClientAnalytics=t()}(this,(function(){return(()=>{var e={792:e=>{var t={utf8:{stringToBytes:function(e){return t.bin.stringToBytes(unescape(encodeURIComponent(e)))},bytesToString:function(e){return decodeURIComponent(escape(t.bin.bytesToString(e)))}},bin:{stringToBytes:function(e){for(var t=[],n=0;n{var t,n;t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n={rotl:function(e,t){return e<>>32-t},rotr:function(e,t){return e<<32-t|e>>>t},endian:function(e){if(e.constructor==Number)return 16711935&n.rotl(e,8)|4278255360&n.rotl(e,24);for(var t=0;t0;e--)t.push(Math.floor(256*Math.random()));return t},bytesToWords:function(e){for(var t=[],n=0,r=0;n>>5]|=e[n]<<24-r%32;return t},wordsToBytes:function(e){for(var t=[],n=0;n<32*e.length;n+=8)t.push(e[n>>>5]>>>24-n%32&255);return t},bytesToHex:function(e){for(var t=[],n=0;n>>4).toString(16)),t.push((15&e[n]).toString(16));return t.join("")},hexToBytes:function(e){for(var t=[],n=0;n>>6*(3-a)&63)):n.push("=");return n.join("")},base64ToBytes:function(e){e=e.replace(/[^A-Z0-9+\\/]/gi,"");for(var n=[],r=0,i=0;r>>6-2*i);return n}},e.exports=n},335:e=>{function t(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}e.exports=function(e){return null!=e&&(t(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&t(e.slice(0,0))}(e)||!!e._isBuffer)}},762:(e,t,n)=>{var r,i,a,o,s;r=n(562),i=n(792).utf8,a=n(335),o=n(792).bin,(s=function(e,t){e.constructor==String?e=t&&"binary"===t.encoding?o.stringToBytes(e):i.stringToBytes(e):a(e)?e=Array.prototype.slice.call(e,0):Array.isArray(e)||e.constructor===Uint8Array||(e=e.toString());for(var n=r.bytesToWords(e),c=8*e.length,u=1732584193,l=-271733879,d=-1732584194,p=271733878,m=0;m>>24)|4278255360&(n[m]<<24|n[m]>>>8);n[c>>>5]|=128<>>9<<4)]=c;var f=s._ff,v=s._gg,g=s._hh,b=s._ii;for(m=0;m>>0,l=l+w>>>0,d=d+y>>>0,p=p+T>>>0}return r.endian([u,l,d,p])})._ff=function(e,t,n,r,i,a,o){var s=e+(t&n|~t&r)+(i>>>0)+o;return(s<>>32-a)+t},s._gg=function(e,t,n,r,i,a,o){var s=e+(t&r|n&~r)+(i>>>0)+o;return(s<>>32-a)+t},s._hh=function(e,t,n,r,i,a,o){var s=e+(t^n^r)+(i>>>0)+o;return(s<>>32-a)+t},s._ii=function(e,t,n,r,i,a,o){var s=e+(n^(t|~r))+(i>>>0)+o;return(s<>>32-a)+t},s._blocksize=16,s._digestsize=16,e.exports=function(e,t){if(null==e)throw new Error("Illegal argument "+e);var n=r.wordsToBytes(s(e,t));return t&&t.asBytes?n:t&&t.asString?o.bytesToString(n):r.bytesToHex(n)}},2:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Perfume:()=>ze,incrementUjNavigation:()=>Le,markStep:()=>Re,markStepOnce:()=>qe});var r,i,a={isResourceTiming:!1,isElementTiming:!1,maxTime:3e4,reportOptions:{},enableNavigationTracking:!0},o=window,s=o.console,c=o.navigator,u=o.performance,l=function(){return c.deviceMemory},d=function(){return c.hardwareConcurrency},p="mark.",m=function(){return u&&!!u.getEntriesByType&&!!u.now&&!!u.mark},f="4g",v=!1,g={},b={value:0},h={value:{beacon:0,css:0,fetch:0,img:0,other:0,script:0,total:0,xmlhttprequest:0}},w={value:0},y={value:0},T={},k={isHidden:!1,didChange:!1},_=function(){k.isHidden=!1,document.hidden&&(k.isHidden=document.hidden,k.didChange=!0)},S=function(e,t){try{var n=new PerformanceObserver((function(e){t(e.getEntries())}));return n.observe({type:e,buffered:!0}),n}catch(e){s.warn("Perfume.js:",e)}return null},E=function(){return!!(d()&&d()<=4)||!!(l()&&l()<=4)},x=function(e,t){switch(e){case"slow-2g":case"2g":case"3g":return!0;default:return E()||t}},O=function(e){return parseFloat(e.toFixed(4))},j=function(e){return"number"!=typeof e?null:O(e/Math.pow(1024,2))},N=function(e,t,n,r,i){var s,u=function(){a.analyticsTracker&&(k.isHidden&&!["CLS","INP"].includes(e)||a.analyticsTracker({attribution:r,metricName:e,data:t,navigatorInformation:c?{deviceMemory:l()||0,hardwareConcurrency:d()||0,serviceWorkerStatus:"serviceWorker"in c?c.serviceWorker.controller?"controlled":"supported":"unsupported",isLowEndDevice:E(),isLowEndExperience:x(f,v)}:{},rating:n,navigationType:i}))};["CLS","INP"].includes(e)?u():(s=u,"requestIdleCallback"in o?o.requestIdleCallback(s,{timeout:3e3}):s())},I=function(e){e.forEach((function(e){if(!("self"!==e.name||e.startTime0&&(w.value+=t,y.value+=t)}}))};!function(e){e.instant="instant",e.quick="quick",e.moderate="moderate",e.slow="slow",e.unavoidable="unavoidable"}(r||(r={}));var P,M,B,C,D,A=((i={})[r.instant]={vitalsThresholds:[100,200],maxOutlierThreshold:1e4},i[r.quick]={vitalsThresholds:[200,500],maxOutlierThreshold:1e4},i[r.moderate]={vitalsThresholds:[500,1e3],maxOutlierThreshold:1e4},i[r.slow]={vitalsThresholds:[1e3,2e3],maxOutlierThreshold:1e4},i[r.unavoidable]={vitalsThresholds:[2e3,5e3],maxOutlierThreshold:2e4},i),L={RT:[100,200],TBT:[200,600],NTBT:[200,600]},U=function(e,t){return L[e]?t<=L[e][0]?"good":t<=L[e][1]?"needsImprovement":"poor":null},R=function(e,t,n){Object.keys(t).forEach((function(e){"number"==typeof t[e]&&(t[e]=O(t[e]))})),N(e,t,null,n||{})},q=function(e){var t=e.attribution,n=e.name,r=e.rating,i=e.value,o=e.navigationType;"FCP"===n&&(b.value=i),["FCP","LCP"].includes(n)&&!T[0]&&(T[0]=S("longtask",I)),"FID"===n&&setTimeout((function(){k.didChange||(q({attribution:t,name:"TBT",rating:U("TBT",w.value),value:w.value,navigationType:o}),R("dataConsumption",h.value))}),1e4);var s=O(i);s<=a.maxTime&&s>=0&&N(n,s,r,t,o)},F=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},z=function(e){if("loading"===document.readyState)return"loading";var t=F();if(t){if(e(t||100)-1)return n||i;if(n=n?i+">"+n:i,r.id)break;e=r.parentNode}}catch(e){}return n},Q=-1,W=function(){return Q},H=function(e){addEventListener("pageshow",(function(t){t.persisted&&(Q=t.timeStamp,e(t))}),!0)},V=function(){var e=F();return e&&e.activationStart||0},J=function(e,t){var n=F(),r="navigate";return W()>=0?r="back-forward-cache":n&&(r=document.prerendering||V()>0?"prerender":document.wasDiscarded?"restore":n.type.replace(/_/g,"-")),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},X=function(e,t,n){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var r=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return r.observe(Object.assign({type:e,buffered:!0},n||{})),r}}catch(e){}},G=function(e,t){var n=function n(r){"pagehide"!==r.type&&"hidden"!==document.visibilityState||(e(r),t&&(removeEventListener("visibilitychange",n,!0),removeEventListener("pagehide",n,!0)))};addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0)},Z=function(e,t,n,r){var i,a;return function(o){t.value>=0&&(o||r)&&((a=t.value-(i||0))||void 0===i)&&(i=t.value,t.delta=a,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,n),e(t))}},Y=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},ee=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()},te=-1,ne=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},re=function(e){"hidden"===document.visibilityState&&te>-1&&(te="visibilitychange"===e.type?e.timeStamp:0,ae())},ie=function(){addEventListener("visibilitychange",re,!0),addEventListener("prerenderingchange",re,!0)},ae=function(){removeEventListener("visibilitychange",re,!0),removeEventListener("prerenderingchange",re,!0)},oe=function(){return te<0&&(te=ne(),ie(),H((function(){setTimeout((function(){te=ne(),ie()}),0)}))),{get firstHiddenTime(){return te}}},se=function(e,t){t=t||{},ee((function(){var n,r=[1800,3e3],i=oe(),a=J("FCP"),o=X("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(o.disconnect(),e.startTime=0&&M1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?function(e,t){var n=function(){le(e,t),i()},r=function(){i()},i=function(){removeEventListener("pointerup",n,ce),removeEventListener("pointercancel",r,ce)};addEventListener("pointerup",n,ce),addEventListener("pointercancel",r,ce)}(t,e):le(t,e)}},me=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach((function(t){return e(t,pe,ce)}))},fe=0,ve=1/0,ge=0,be=function(e){e.forEach((function(e){e.interactionId&&(ve=Math.min(ve,e.interactionId),ge=Math.max(ge,e.interactionId),fe=ge?(ge-ve)/7+1:0)}))},he=function(){return D?fe:performance.interactionCount||0},we=0,ye=function(){return he()-we},Te=[],ke={},_e=function(e){var t=Te[Te.length-1],n=ke[e.interactionId];if(n||Te.length<10||e.duration>t.latency){if(n)n.entries.push(e),n.latency=Math.max(n.latency,e.duration);else{var r={id:e.interactionId,latency:e.duration,entries:[e]};ke[r.id]=r,Te.push(r)}Te.sort((function(e,t){return t.latency-e.latency})),Te.splice(10).forEach((function(e){delete ke[e.id]}))}},Se={},Ee=function e(t){document.prerendering?ee((function(){return e(t)})):"complete"!==document.readyState?addEventListener("load",(function(){return e(t)}),!0):setTimeout(t,0)},xe=function(e,t){t=t||{};var n=[800,1800],r=J("TTFB"),i=Z(e,r,n,t.reportAllChanges);Ee((function(){var a=F();if(a){var o=a.responseStart;if(o<=0||o>performance.now())return;r.value=Math.max(o-V(),0),r.entries=[a],i(!0),H((function(){r=J("TTFB",0),(i=Z(e,r,n,t.reportAllChanges))(!0)}))}}))},Oe=function(e){e.forEach((function(e){e.identifier&&q({attribution:{identifier:e.identifier},name:"ET",rating:null,value:e.startTime})}))},je=function(e){e.forEach((function(e){if(a.isResourceTiming&&R("resourceTiming",e),e.decodedBodySize&&e.initiatorType){var t=e.decodedBodySize/1e3;h.value[e.initiatorType]+=t,h.value.total+=t}}))},Ne=function(){!function(e,t){xe((function(e){!function(e){if(e.entries.length){var t=e.entries[0],n=t.activationStart||0,r=Math.max(t.domainLookupStart-n,0),i=Math.max(t.connectStart-n,0),a=Math.max(t.requestStart-n,0);e.attribution={waitingTime:r,dnsTime:i-r,connectionTime:a-i,requestTime:e.value-a,navigationEntry:t}}else e.attribution={waitingTime:0,dnsTime:0,connectionTime:0,requestTime:0}}(e),function(e){e.value>0&&q(e)}(e)}),t)}(0,a.reportOptions.ttfb),function(e,t){!function(e,t){t=t||{},ee((function(){var e,n=[.1,.25],r=J("CLS"),i=-1,a=0,o=[],s=function(e){i>-1&&function(e){!function(e){if(e.entries.length){var t=e.entries.reduce((function(e,t){return e&&e.value>t.value?e:t}));if(t&&t.sources&&t.sources.length){var n=(r=t.sources).find((function(e){return e.node&&1===e.node.nodeType}))||r[0];if(n)return void(e.attribution={largestShiftTarget:$(n.node),largestShiftTime:t.startTime,largestShiftValue:t.value,largestShiftSource:n,largestShiftEntry:t,loadState:z(t.startTime)})}}var r;e.attribution={}}(e),function(e){q(e)}(e)}(e)},c=function(t){t.forEach((function(t){if(!t.hadRecentInput){var n=o[0],i=o[o.length-1];a&&t.startTime-i.startTime<1e3&&t.startTime-n.startTime<5e3?(a+=t.value,o.push(t)):(a=t.value,o=[t]),a>r.value&&(r.value=a,r.entries=o,e())}}))},u=X("layout-shift",c);u&&(e=Z(s,r,n,t.reportAllChanges),se((function(t){i=t.value,r.value<0&&(r.value=0,e())})),G((function(){c(u.takeRecords()),e(!0)})),H((function(){a=0,i=-1,r=J("CLS",0),e=Z(s,r,n,t.reportAllChanges),Y((function(){return e()}))})))}))}(0,t)}(0,a.reportOptions.cls),function(e,t){se((function(e){!function(e){if(e.entries.length){var t=F(),n=e.entries[e.entries.length-1];if(t){var r=t.activationStart||0,i=Math.max(0,t.responseStart-r);return void(e.attribution={timeToFirstByte:i,firstByteToFCP:e.value-i,loadState:z(e.entries[0].startTime),navigationEntry:t,fcpEntry:n})}}e.attribution={timeToFirstByte:0,firstByteToFCP:e.value,loadState:z(W())}}(e),function(e){q(e)}(e)}),t)}(0,a.reportOptions.fcp),function(e,t){!function(e,t){t=t||{},ee((function(){var n,r=[100,300],i=oe(),a=J("FID"),o=function(e){e.startTime0&&(i.value=0,i.entries=[]),r(!0)})),H((function(){Te=[],we=he(),i=J("INP"),r=Z(e,i,n,t.reportAllChanges)})))}))}((function(t){!function(e){if(e.entries.length){var t=e.entries.sort((function(e,t){return t.duration-e.duration||t.processingEnd-t.processingStart-(e.processingEnd-e.processingStart)}))[0];e.attribution={eventTarget:$(t.target),eventType:t.name,eventTime:t.startTime,eventEntry:t,loadState:z(t.startTime)}}else e.attribution={}}(t),e(t)}),t)}((function(e){return q(e)}),a.reportOptions.inp),a.isResourceTiming&&S("resource",je),a.isElementTiming&&S("element",Oe)},Ie=function(e){var t="usageDetails"in e?e.usageDetails:{};R("storageEstimate",{quota:j(e.quota),usage:j(e.usage),caches:j(t.caches),indexedDB:j(t.indexedDB),serviceWorker:j(t.serviceWorkerRegistrations)})},Pe={finalMarkToStepsMap:{},startMarkToStepsMap:{},active:{},navigationSteps:{}},Me=function(e){delete Pe.active[e]},Be=function(){return Pe.navigationSteps},Ce=function(e){var t;return null!==(t=Be()[e])&&void 0!==t?t:{}},De=function(e,t,n){var r="step."+e,i=u.getEntriesByName(p+t).length>0;if(u.getEntriesByName(p+n).length>0&&a.steps){var o=A[a.steps[e].threshold],s=o.maxOutlierThreshold,c=o.vitalsThresholds;if(i){var l=u.measure(r,p+t,p+n),d=l.duration;if(d<=s){var m=function(e,t){return e<=t[0]?"good":e<=t[1]?"needsImprovement":"poor"}(d,c);d>=0&&(N("userJourneyStep",d,m,{stepName:e},void 0),u.measure("step.".concat(e,"_vitals_").concat(m),{start:l.startTime+l.duration,end:l.startTime+l.duration,detail:{type:"stepVital",duration:d}}))}}}},Ae=function(){var e=Be(),t=Pe.startMarkToStepsMap,n=Object.keys(e).length;if(0===n)return{};var r={},i=n-1,a=Ce(i);if(Object.keys(a).forEach((function(e){var n,i=null!==(n=t[e])&&void 0!==n?n:[];Object.keys(i).forEach((function(e){r[e]=!0}))})),n>1){var o=Ce(i-1);Object.keys(o).forEach((function(e){var n,i=null!==(n=t[e])&&void 0!==n?n:[];Object.keys(i).forEach((function(e){r[e]=!0}))}))}return r},Le=function(){var e,t=Object.keys(Pe.navigationSteps).length;Pe.navigationSteps[t]={};var n=Ae();null===(e=a.onMarkStep)||void 0===e||e.call(a,"",Object.keys(n))},Ue=function(e){var t,n,r,i,o,s,c;if(Pe.finalMarkToStepsMap[e]){!function(e){var t=Pe.navigationSteps,n=Pe.finalMarkToStepsMap,r=Object.keys(t).length;if(0!==r){var i=r-1,a=Ce(i);if(a&&n[e]){var o=n[e];o&&Object.keys(o).forEach((function(e){if(a[e]){var n=Ce(i)||{};n[e]=!1,t[i]=n}if(r>1){var o=i-1,s=Ce(o);s[e]&&(s[e]=!1,t[o]=s)}}))}}}(e);var u=Pe.finalMarkToStepsMap[e];Object.keys(u).forEach((function(t){var n=u[t];n.forEach(Me),Promise.all(n.map((function(n){return function(e,t,n,r){return new(n||(n=Promise))((function(e,t){function i(e){try{o(r.next(e))}catch(e){t(e)}}function a(e){try{o(r.throw(e))}catch(e){t(e)}}function o(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(i,a)}o((r=r.apply(undefined,[])).next())}))}(0,0,void 0,(function(){return function(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]0?o:1)-1)||[])[r]=!0,i[s]=c,function(e){var t,n=null!==(t=Pe.startMarkToStepsMap[e])&&void 0!==t?t:[];Object.keys(n).forEach((function(e){Pe.active[e]||(Pe.active[e]=!0)}))}(e);if(a.enableNavigationTracking){var l=Ae();null===(t=a.onMarkStep)||void 0===t||t.call(a,e,Object.keys(l))}else null===(n=a.onMarkStep)||void 0===n||n.call(a,e,Object.keys(Pe.active))},Re=function(e){u.mark(p+e),Ue(e)},qe=function(e){0===u.getEntriesByName(p+e).length&&(u.mark(p+e),Ue(e))},Fe=0,ze=function(){function e(e){if(void 0===e&&(e={}),this.v="9.0.0-rc.3",a.analyticsTracker=e.analyticsTracker,a.isResourceTiming=!!e.resourceTiming,a.isElementTiming=!!e.elementTiming,a.maxTime=e.maxMeasureTime||a.maxTime,a.reportOptions=e.reportOptions||a.reportOptions,a.steps=e.steps,a.onMarkStep=e.onMarkStep,a.enableNavigationTracking=e.enableNavigationTracking,m()){"PerformanceObserver"in o&&Ne(),void 0!==document.hidden&&document.addEventListener("visibilitychange",_);var t=function(){if(!m())return{};var e=u.getEntriesByType("navigation")[0];if(!e)return{};var t=e.responseStart,n=e.responseEnd;return{fetchTime:n-e.fetchStart,workerTime:e.workerStart>0?n-e.workerStart:0,totalTime:n-e.requestStart,downloadTime:n-t,timeToFirstByte:t-e.requestStart,headerSize:e.transferSize-e.encodedBodySize||0,dnsLookupTime:e.domainLookupEnd-e.domainLookupStart,redirectTime:e.redirectEnd-e.redirectStart}}();R("navigationTiming",t),t.redirectTime&&q({attribution:{},name:"RT",rating:U("RT",t.redirectTime),value:t.redirectTime}),R("networkInformation",function(){if("connection"in c){var e=c.connection;return"object"!=typeof e?{}:(f=e.effectiveType,v=!!e.saveData,{downlink:e.downlink,effectiveType:e.effectiveType,rtt:e.rtt,saveData:!!e.saveData})}return{}}()),c&&c.storage&&"function"==typeof c.storage.estimate&&c.storage.estimate().then(Ie),a.steps&&a.steps&&(Pe.startMarkToStepsMap={},Pe.finalMarkToStepsMap={},Pe.active={},Pe.navigationSteps={},Object.entries(a.steps).forEach((function(e){var t,n,r=e[0],i=e[1].marks,a=i[0],o=i[1],s=null!==(n=Pe.startMarkToStepsMap[a])&&void 0!==n?n:{};if(s[r]=!0,Pe.startMarkToStepsMap[a]=s,Pe.finalMarkToStepsMap[o]){var c=Pe.finalMarkToStepsMap[o][a]||[];c.push(r),Pe.finalMarkToStepsMap[o][a]=c}else Pe.finalMarkToStepsMap[o]=((t={})[a]=[r],t)})))}}return e.prototype.start=function(e){m()&&!g[e]&&(g[e]=!0,u.mark("mark_".concat(e,"_start")))},e.prototype.end=function(e,t,n){if(void 0===t&&(t={}),void 0===n&&(n=!0),m()&&g[e]){u.mark("mark_".concat(e,"_end")),delete g[e];var r=function(e){u.measure(e,"mark_".concat(e,"_start"),"mark_".concat(e,"_end"));var t=u.getEntriesByName(e).pop();return t&&"measure"===t.entryType?t.duration:-1}(e);n&&R(e,O(r),t)}},e.prototype.endPaint=function(e,t){var n=this;setTimeout((function(){n.end(e,t)}))},e.prototype.clear=function(e){delete g[e],u.clearMarks&&(u.clearMarks("mark_".concat(e,"_start")),u.clearMarks("mark_".concat(e,"_end")))},e.prototype.markNTBT=function(){var e=this;this.start("ntbt"),y.value=0,clearTimeout(Fe),Fe=setTimeout((function(){e.end("ntbt",{},!1),q({attribution:{},name:"NTBT",rating:U("NTBT",y.value),value:y.value}),y.value=0}),2e3)},e}()},426:(e,t)=>{"use strict";Symbol.for("react.element"),Symbol.for("react.portal"),Symbol.for("react.fragment"),Symbol.for("react.strict_mode"),Symbol.for("react.profiler"),Symbol.for("react.provider"),Symbol.for("react.context"),Symbol.for("react.forward_ref"),Symbol.for("react.suspense"),Symbol.for("react.memo"),Symbol.for("react.lazy"),Symbol.iterator;var n={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},r=Object.assign,i={};function a(e,t,r){this.props=e,this.context=t,this.refs=i,this.updater=r||n}function o(){}function s(e,t,r){this.props=e,this.context=t,this.refs=i,this.updater=r||n}a.prototype.isReactComponent={},a.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},a.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},o.prototype=a.prototype;var c=s.prototype=new o;c.constructor=s,r(c,a.prototype),c.isPureReactComponent=!0;Array.isArray,Object.prototype.hasOwnProperty;var u={current:null};t.useCallback=function(e,t){return u.current.useCallback(e,t)},t.useEffect=function(e,t){return u.current.useEffect(e,t)},t.useRef=function(e){return u.current.useRef(e)}},784:(e,t,n)=>{"use strict";e.exports=n(426)},353:function(e,t,n){var r;!function(i,a){"use strict";var o="function",s="undefined",c="object",u="string",l="major",d="model",p="name",m="type",f="vendor",v="version",g="architecture",b="console",h="mobile",w="tablet",y="smarttv",T="wearable",k="embedded",_="Amazon",S="Apple",E="ASUS",x="BlackBerry",O="Browser",j="Chrome",N="Firefox",I="Google",P="Huawei",M="LG",B="Microsoft",C="Motorola",D="Opera",A="Samsung",L="Sharp",U="Sony",R="Xiaomi",q="Zebra",F="Facebook",z="Chromium OS",K="Mac OS",$=function(e){for(var t={},n=0;n0?2===s.length?typeof s[1]==o?this[s[0]]=s[1].call(this,l):this[s[0]]=s[1]:3===s.length?typeof s[1]!==o||s[1].exec&&s[1].test?this[s[0]]=l?l.replace(s[1],s[2]):a:this[s[0]]=l?s[1].call(this,l,s[2]):a:4===s.length&&(this[s[0]]=l?s[3].call(this,l.replace(s[1],s[2])):a):this[s]=l||a;d+=2}},J=function(e,t){for(var n in t)if(typeof t[n]===c&&t[n].length>0){for(var r=0;r2&&(e[d]="iPad",e[m]=w),e},this.getEngine=function(){var e={};return e[p]=a,e[v]=a,V.call(e,r,y.engine),e},this.getOS=function(){var e={};return e[p]=a,e[v]=a,V.call(e,r,y.os),T&&!e[p]&&b&&"Unknown"!=b.platform&&(e[p]=b.platform.replace(/chrome os/i,z).replace(/macos/i,K)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return r},this.setUA=function(e){return r=typeof e===u&&e.length>350?H(e,350):e,this},this.setUA(r),this};Z.VERSION="1.0.35",Z.BROWSER=$([p,v,l]),Z.CPU=$([g]),Z.DEVICE=$([d,f,m,b,h,y,w,T,k]),Z.ENGINE=Z.OS=$([p,v]),typeof t!==s?(e.exports&&(t=e.exports=Z),t.UAParser=Z):n.amdO?(r=function(){return Z}.call(t,n,t,e))===a||(e.exports=r):typeof i!==s&&(i.UAParser=Z);var Y=typeof i!==s&&(i.jQuery||i.Zepto);if(Y&&!Y.ua){var ee=new Z;Y.ua=ee.getResult(),Y.ua.get=function(){return ee.getUA()},Y.ua.set=function(e){ee.setUA(e);var t=ee.getResult();for(var n in t)Y.ua[n]=t[n]}}}("object"==typeof window?window:this)}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}n.amdO={},n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return(()=>{"use strict";n.r(r),n.d(r,{ActionType:()=>f,AmplitudePlatformName:()=>g,AnalyticsEventImportance:()=>l,AnalyticsQueries:()=>e,AuthStatus:()=>b,ComponentType:()=>m,IThresholdTier:()=>Jt,MetricType:()=>d,PlatformName:()=>v,SessionActions:()=>h,SessionAutomatedEvents:()=>w,SessionRank:()=>y,SubjectType:()=>p,UserTypeCommerce:()=>c,UserTypeInsto:()=>i,UserTypeRetail:()=>t,UserTypeRetailBusinessBanking:()=>s,UserTypeRetailEmployeeInternal:()=>a,UserTypeRetailEmployeePersonal:()=>o,UserTypeWallet:()=>u,automatedEvents:()=>xn,automatedMappingConfig:()=>In,clearMarkEntry:()=>Vn,clearPerformanceMarkEntries:()=>Xn,config:()=>A,createEventConfig:()=>On,createNewSpan:()=>Ln,createNewTrace:()=>Un,device:()=>W,endPerfMark:()=>Jn,exposeExperiment:()=>wn,flushQueue:()=>or,generateUUID:()=>V,getAnalyticsHeaders:()=>sr,getReferrerData:()=>le,getTracingHeaders:()=>An,getTracingId:()=>Dn,getUrlHostname:()=>pe,getUrlParams:()=>me,getUrlPathname:()=>fe,getUserContext:()=>ar,identify:()=>Tn,identifyFlow:()=>xe,identity:()=>H,identityFlow:()=>Se,incrementUjNavigation:()=>an,init:()=>yn,initNextJsTrackPageview:()=>_n,initTrackPageview:()=>kn,isEventKeyFormatValid:()=>we,isSessionEnded:()=>pt,location:()=>re,logEvent:()=>$t,logMetric:()=>Ht,logPageView:()=>on,logTrace:()=>Rn,markNTBT:()=>tn,markStep:()=>nn,markStepOnce:()=>rn,onVisibilityChange:()=>ln,optIn:()=>En,optOut:()=>Sn,perfMark:()=>Wn,persistentData:()=>oe,postMessage:()=>K,recordSessionDuration:()=>pn,removeFromIdentifyFlow:()=>Ee,savePersistentData:()=>st,sendScheduledEvents:()=>Bt,setBreadcrumbs:()=>ie,setConfig:()=>U,setLocation:()=>ae,setPagePath:()=>ve,setPageview:()=>Kt,setPersistentData:()=>se,setSessionStart:()=>dt,setTime:()=>Ue,startPerfMark:()=>Hn,timeStone:()=>Le,useEventLogger:()=>Yn,useLogEventOnMount:()=>tr,usePerformanceMarks:()=>rr});let e=function(e){return e.fbclid="fbclid",e.gclid="gclid",e.msclkid="msclkid",e.ptclid="ptclid",e.ttclid="ttclid",e.utm_source="utm_source",e.utm_medium="utm_medium",e.utm_campaign="utm_campaign",e.utm_term="utm_term",e.utm_content="utm_content",e}({});const t=0,i=1,a=2,o=3,s=4,c=5,u=6;let l=function(e){return e.low="low",e.high="high",e}({}),d=function(e){return e.count="count",e.rate="rate",e.gauge="gauge",e.distribution="distribution",e.histogram="histogram",e}({}),p=function(e){return e.commerce_merchant="commerce_merchant",e.device="device",e.edp_fingerprint_id="edp_fingerprint_id",e.nft_user="nft_user",e.user="user",e.wallet_user="wallet_user",e.uuid="user_uuid",e}({}),m=function(e){return e.unknown="unknown",e.banner="banner",e.button="button",e.card="card",e.chart="chart",e.content_script="content_script",e.dropdown="dropdown",e.link="link",e.page="page",e.modal="modal",e.table="table",e.search_bar="search_bar",e.service_worker="service_worker",e.text="text",e.text_input="text_input",e.tray="tray",e.checkbox="checkbox",e.icon="icon",e}({}),f=function(e){return e.unknown="unknown",e.blur="blur",e.click="click",e.change="change",e.dismiss="dismiss",e.focus="focus",e.hover="hover",e.select="select",e.measurement="measurement",e.move="move",e.process="process",e.render="render",e.scroll="scroll",e.view="view",e.search="search",e.keyPress="keyPress",e}({}),v=function(e){return e.unknown="unknown",e.web="web",e.android="android",e.ios="ios",e.mobile_web="mobile_web",e.tablet_web="tablet_web",e.server="server",e.windows="windows",e.macos="macos",e.extension="extension",e}({}),g=function(e){return e.web="Web",e.ios="iOS",e.android="Android",e}({}),b=function(e){return e[e.notLoggedIn=0]="notLoggedIn",e[e.loggedIn=1]="loggedIn",e}({}),h=function(e){return e.ac="ac",e.af="af",e.ah="ah",e.al="al",e.am="am",e.ar="ar",e.as="as",e}({}),w=function(e){return e.pv="pv",e}({}),y=function(e){return e.xs="xs",e.s="s",e.m="m",e.l="l",e.xl="xl",e.xxl="xxl",e}({});const T="https://analytics-service-dev.cbhq.net",k=3e5,_=5e3,S="analytics-db",E="experiment-exposure-db",x="Analytics SDK:",O=Object.values(e),j="pageview",N="session_duration",I={navigationTiming:{eventName:"perf_navigation_timing"},redirectTime:{eventName:"perf_redirect_time"},RT:{eventName:"perf_redirect_time"},TTFB:{eventName:"perf_time_to_first_byte"},networkInformation:{eventName:"perf_network_information"},storageEstimate:{eventName:"perf_storage_estimate"},FCP:{eventName:"perf_first_contentful_paint"},FID:{eventName:"perf_first_input_delay"},LCP:{eventName:"perf_largest_contentful_paint"},CLS:{eventName:"perf_cumulative_layout_shift"},TBT:{eventName:"perf_total_blocking_time"},NTBT:{eventName:"perf_navigation_total_blocking_time"},INP:{eventName:"perf_interact_to_next_paint"},ET:{eventName:"perf_element_timing"},userJourneyStep:{eventName:"perf_user_journey_step"}},P="1",M="web";function B(){return B=Object.assign?Object.assign.bind():function(e){for(var t=1;t{console.error(x,e,t)},platform:v.unknown,projectName:"",ricTimeoutScheduleEvent:1e3,ricTimeoutSetDevice:500,showDebugLogging:!1,trackUserId:!1,version:null,apiEndpoint:T},D(T),{steps:{}}),L=[].reduce(((e,t)=>n=>e(t(n))),(e=>{if(!e.isProd)return e.isInternalApplication?(e.apiEndpoint="https://analytics-service-internal-dev.cbhq.net",B({},e,D(e.apiEndpoint))):e;const t=(e=>e.apiEndpoint?C.test(e.apiEndpoint)?e.apiEndpoint:`https://${e.apiEndpoint}`:e.isInternalApplication?"https://analytics-service-internal.cbhq.net":"https://as.coinbase.com")(e);return B({},e,{apiEndpoint:t},D(t))})),U=e=>{const{batchEventsThreshold:t,batchMetricsThreshold:n,batchTracesThreshold:r}=e,i=[t,n,r];for(const e of i)if((e||0)>30){console.warn("You are setting the threshhold for the batch limit to be greater than 30. This may cause request overload.");break}Object.assign(A,L(e))},R=[v.web,v.mobile_web,v.tablet_web];function q(){return"android"===A.platform}function F(){return"ios"===A.platform}function z(){return R.includes(A.platform)}function K(e){if(z()&&navigator&&"serviceWorker"in navigator&&navigator.serviceWorker.controller)try{navigator.serviceWorker.controller.postMessage(e)}catch(e){e instanceof Error&&A.onError(e)}}var $=n(353),Q=n.n($);const W={amplitudeOSName:null,amplitudeOSVersion:null,amplitudeDeviceModel:null,amplitudePlatform:null,browserName:null,browserMajor:null,osName:null,userAgent:null,width:null,height:null},H={countryCode:null,deviceId:null,device_os:null,isOptOut:!1,languageCode:null,locale:null,jwt:null,session_lcc_id:null,userAgent:null,userId:null},V=e=>e?(e^16*Math.random()>>e/4).toString(16):"10000000-1000-4000-8000-100000000000".replace(/[018]/g,V),J=()=>A.isAlwaysAuthed||!!H.userId,X=()=>{const e={};return H.countryCode&&(e.country_code=H.countryCode),e},G=()=>{const{platform:e}=A;if(e===v.web)switch(!0){case window.matchMedia("(max-width: 560px)").matches:return v.mobile_web;case window.matchMedia("(max-width: 1024px, min-width: 561px)").matches:return v.tablet_web}return e},Z=()=>{var e,t,n,r,i;z()?("requestIdleCallback"in window?window.requestIdleCallback(ne,{timeout:A.ricTimeoutSetDevice}):ne(),W.amplitudePlatform=g.web,W.userAgent=(null==(e=window)||null==(e=e.navigator)?void 0:e.userAgent)||null,ee({height:null!=(t=null==(n=window)?void 0:n.innerHeight)?t:null,width:null!=(r=null==(i=window)?void 0:i.innerWidth)?r:null})):F()?(W.amplitudePlatform=g.ios,W.userAgent=H.userAgent,W.userAgent&&ne()):q()&&(W.userAgent=H.userAgent,W.amplitudePlatform=g.android,W.userAgent&&ne())},Y=e=>{Object.assign(H,e),z()&&K({identity:{isAuthed:!!H.userId,locale:H.locale||null}})},ee=e=>{W.height=e.height,W.width=e.width},te=()=>{U({platform:G()}),z()&&K({config:{platform:A.platform}})},ne=()=>{var e;performance.mark&&performance.mark("ua_parser_start");const t=new(Q())(null!=(e=W.userAgent)?e:"").getResult();W.browserName=t.browser.name||null,W.browserMajor=t.browser.major||null,W.osName=t.os.name||null,W.amplitudeOSName=W.browserName,W.amplitudeOSVersion=W.browserMajor,W.amplitudeDeviceModel=W.osName,K({device:{browserName:W.browserName,osName:W.osName}}),performance.mark&&(performance.mark("ua_parser_end"),performance.measure("ua_parser","ua_parser_start","ua_parser_end"))},re={breadcrumbs:[],initialUAAData:{},pageKey:"",pageKeyRegex:{},pagePath:"",prevPageKey:"",prevPagePath:""};function ie(e){Object.assign(re,{breadcrumbs:e})}function ae(e){Object.assign(re,e)}const oe={eventId:0,sequenceNumber:0,sessionId:0,lastEventTime:0,sessionStart:0,sessionUUID:null,userId:null,ac:0,af:0,ah:0,al:0,am:0,ar:0,as:0,pv:0};function se(e){Object.assign(oe,e)}function ce(){var e,t;return null!=(e=null==(t=document)?void 0:t.referrer)?e:""}function ue(){return ue=Object.assign?Object.assign.bind():function(e){for(var t=1;t{const e=ce();if(!e)return{};const t=new URL(e);return t.hostname===pe()?{}:{referrer:e,referring_domain:t.hostname}},de=()=>{const e=new URLSearchParams(me()),t={};return O.forEach((n=>{e.has(n)&&(t[n]=(e.get(n)||"").toLowerCase())})),t},pe=()=>{var e;return(null==(e=window)||null==(e=e.location)?void 0:e.hostname)||""},me=()=>{var e;return(null==(e=window)||null==(e=e.location)?void 0:e.search)||""},fe=()=>{var e;return(null==(e=window)||null==(e=e.location)?void 0:e.pathname)||""},ve=()=>{const e=A.overrideWindowLocation?re.pagePath:fe()+me();e&&e!==re.pagePath&&(e!==re.pagePath&&ge(),re.pagePath=e,re.pageKeyRegex&&Object.keys(re.pageKeyRegex).some((e=>{if(re.pageKeyRegex[e].test(re.pagePath))return re.pageKey=e,!0})))},ge=()=>{if(z()){const e=ce();if(!re.prevPagePath&&e){const t=new URL(e);if(t.hostname===pe())return void(re.prevPagePath=t.pathname)}}re.prevPagePath=re.pagePath,re.prevPageKey=re.pageKey},be=e=>{z()&&Object.assign(e,z()?(Object.keys(re.initialUAAData).length>0||(new URLSearchParams(me()),re.initialUAAData=ue({},(()=>{const e={};return O.forEach((t=>{oe[t]&&(e[t]=oe[t])})),e})(),de(),le())),re.initialUAAData):re.initialUAAData)},he=/^[a-zd]+(_[a-zd]+)*$/;function we(e){return he.test(e)}function ye(){return ye=Object.assign?Object.assign.bind():function(e){for(var t=1;t{ke.includes(e)&&delete Se[e]}))}function xe(e){var t;const n=Object.entries(e).reduce(((e,t)=>{const[n,r]=t;return!Te.includes(n)&&ke.includes(n)?we(n)?ye({},e,{[n]:r}):(A.onError(new Error("IdentityFlow property names must have snake case format"),{[n]:r}),e):e}),{});null!=(t=n.ujs)&&t.length&&(n.ujs=n.ujs.map((e=>`${_e}${e}`))),Object.assign(Se,n)}function Oe(){return A.platform!==v.unknown||(A.onError(new Error("SDK platform not initialized")),!1)}const je={eventsQueue:[],eventsScheduled:!1,metricsQueue:[],metricsScheduled:!1,tracesQueue:[],tracesScheduled:!1};function Ne(e){Object.assign(je,e)}const Ie={ac:0,af:0,ah:0,al:0,am:0,ar:0,as:0,pv:0,sqs:0},Pe={ac:20,af:5,ah:1,al:1,am:0,ar:10,as:20},Me={pv:25},Be={xs:0,s:1,m:1,l:2,xl:2,xxl:2},Ce=e=>e<15?y.xs:e<60?y.s:e<240?y.m:e<960?y.l:e<3840?y.xl:y.xxl,De=e=>{Object.assign(Ie,e)};function Ae(){return(new Date).getTime()}const Le={timeStart:Ae(),timeOnPagePath:0,timeOnPageKey:0,prevTimeOnPagePath:0,prevTimeOnPageKey:0,sessionDuration:0,sessionEnd:0,sessionStart:0,prevSessionDuration:0};function Ue(e){Object.assign(Le,e)}const Re=(e,t)=>t.some((t=>e instanceof t));let qe,Fe;const ze=new WeakMap,Ke=new WeakMap,$e=new WeakMap,Qe=new WeakMap,We=new WeakMap;let He={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Ke.get(e);if("objectStoreNames"===t)return e.objectStoreNames||$e.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Je(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Ve(e){return"function"==typeof e?(t=e)!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Fe||(Fe=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(Xe(this),e),Je(ze.get(this))}:function(...e){return Je(t.apply(Xe(this),e))}:function(e,...n){const r=t.call(Xe(this),e,...n);return $e.set(r,e.sort?e.sort():[e]),Je(r)}:(e instanceof IDBTransaction&&function(e){if(Ke.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",a),e.removeEventListener("abort",a)},i=()=>{t(),r()},a=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",a),e.addEventListener("abort",a)}));Ke.set(e,t)}(e),Re(e,qe||(qe=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,He):e);var t}function Je(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",a)},i=()=>{t(Je(e.result)),r()},a=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",a)}));return t.then((t=>{t instanceof IDBCursor&&ze.set(t,e)})).catch((()=>{})),We.set(t,e),t}(e);if(Qe.has(e))return Qe.get(e);const t=Ve(e);return t!==e&&(Qe.set(e,t),We.set(t,e)),t}const Xe=e=>We.get(e),Ge=["get","getKey","getAll","getAllKeys","count"],Ze=["put","add","delete","clear"],Ye=new Map;function et(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Ye.get(t))return Ye.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=Ze.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!Ge.includes(n))return;const a=async function(e,...t){const a=this.transaction(e,i?"readwrite":"readonly");let o=a.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&a.done]))[0]};return Ye.set(t,a),a}var tt;tt=He,He={...tt,get:(e,t,n)=>et(e,t)||tt.get(e,t,n),has:(e,t)=>!!et(e,t)||tt.has(e,t)};const nt={isReady:!1,idbKeyval:null};function rt(e){Object.assign(nt,e)}const it={},at=async e=>{if(!nt.idbKeyval)return Promise.resolve(null);try{return await nt.idbKeyval.get(e)}catch(e){return A.onError(new Error("IndexedDB:Get:InternalError")),Promise.resolve(null)}},ot=async(e,t)=>{if(nt.idbKeyval)try{await nt.idbKeyval.set(e,t)}catch(e){A.onError(new Error("IndexedDB:Set:InternalError"))}},st=()=>{"server"!==A.platform&&(se({sessionStart:Le.sessionStart,ac:Ie.ac,af:Ie.af,ah:Ie.ah,al:Ie.al,am:Ie.am,ar:Ie.ar,as:Ie.as,pv:Ie.pv}),H.userId&&se({userId:H.userId}),ot(S,oe))},ct="rgb(5,177,105)",ut=e=>{const{metricName:t,data:n}=e,r=e.importance||l.low;if(!A.showDebugLogging||!console)return;const i=`%c ${x}`,a=`color:${ct};font-size:11px;`,o=`Importance: ${r}`;console.group(i,a,t,o),n.forEach((e=>{e.event_type?console.log(e.event_type,e):console.log(e)})),console.groupEnd()},lt=e=>{const{metricName:t,data:n}=e,r=e.importance||l.low;if(!A.showDebugLogging||!console)return;const i=`color:${ct};font-size:11px;`,a=`%c ${x}`,o=`Importance: ${r}`;console.log(a,i,t,n,o)},dt=()=>{const e=Ae();oe.sessionId&&oe.lastEventTime&&oe.sessionUUID&&!pt(e)||(oe.sessionId=e,oe.sessionUUID=V(),Ue({sessionStart:e}),lt({metricName:"Started new session:",data:{persistentData:oe,timeStone:Le}})),oe.lastEventTime=e},pt=e=>e-oe.lastEventTime>18e5;function mt(){return mt=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var t;(e=>{switch(e.action){case f.click:Ie.ac+=1;break;case f.focus:Ie.af+=1;break;case f.hover:Ie.ah+=1;break;case f.move:Ie.am+=1;break;case f.scroll:Ie.al+=1;break;case f.search:Ie.ar+=1;break;case f.select:Ie.as+=1}})(t=e),t.event_type!==j?t.event_type===N&&((e=>{if(!e.session_rank)return;const t=e.session_rank;Object.values(h).forEach((e=>{Ie.sqs+=Ie[e]*Pe[e]})),Object.values(w).forEach((e=>{Ie.sqs+=Ie[e]*Me[e]})),Ie.sqs*=Be[t]})(t),Object.assign(t,Ie),De({ac:0,af:0,ah:0,al:0,am:0,ar:0,as:0,pv:0,sqs:0})):Ie.pv+=1;const n=e.event_type;delete e.event_type;const r=e.deviceId?e.deviceId:null,i=e.timestamp;return delete e.timestamp,se({eventId:oe.eventId+1}),se({sequenceNumber:oe.sequenceNumber+1}),dt(),st(),{device_id:H.deviceId||r||null,user_id:H.userId,timestamp:i,event_id:oe.eventId,session_id:oe.sessionId||-1,event_type:n,version_name:A.version||null,platform:W.amplitudePlatform,os_name:W.amplitudeOSName,os_version:W.amplitudeOSVersion,device_model:W.amplitudeDeviceModel,language:H.languageCode,event_properties:mt({},e,{session_uuid:oe.sessionUUID,height:W.height,width:W.width}),user_properties:X(),uuid:V(),library:{name:"@cbhq/client-analytics",version:"10.6.0"},sequence_number:oe.sequenceNumber,user_agent:W.userAgent||H.userAgent}},vt=e=>e.map((e=>ft(e)));function gt(){return gt=Object.assign?Object.assign.bind():function(e){for(var t=1;te.map((e=>(e=>{const t=e.tags||{},n=gt({authed:J()?"true":"false",platform:A.platform},t,{project_name:A.projectName,version_name:A.version||null});return{metric_name:e.metricName,page_path:e.pagePath||null,value:e.value,tags:n,type:e.metricType}})(e))),ht=e=>0!==je.metricsQueue.length&&(je.metricsQueue.length>=A.batchMetricsThreshold||(je.metricsScheduled||(je.metricsScheduled=!0,setTimeout((()=>{je.metricsScheduled=!1,e(bt(je.metricsQueue)),je.metricsQueue=[]}),A.batchMetricsPeriod)),!1)),wt=e=>0!==je.tracesQueue.length&&(je.tracesQueue.length>=A.batchTracesThreshold||(je.tracesScheduled||(je.tracesScheduled=!0,setTimeout((()=>{je.tracesScheduled=!1,e(je.tracesQueue),je.tracesQueue=[]}),A.batchTracesPeriod)),!1)),yt=e=>{var t;z()&&null!=(t=window)&&t.requestIdleCallback?window.requestIdleCallback(e,{timeout:A.ricTimeoutScheduleEvent}):(q()||F())&&A.interactionManager?A.interactionManager.runAfterInteractions(e):e()};function Tt(){return Tt=Object.assign?Object.assign.bind():function(e){for(var t=1;t{const{data:t,importance:n,isJSON:r,onError:i,url:a}=e,o=r?"application/json":kt,s=n||l.low,c=r?JSON.stringify(t):new URLSearchParams(t).toString();function u(){const e=new XMLHttpRequest;e.open("POST",a,!0),Object.keys(A.headers||{}).forEach((t=>{e.setRequestHeader(t,A.headers[t])})),e.setRequestHeader("Content-Type",kt),H.jwt&&e.setRequestHeader("authorization",`Bearer ${H.jwt}`),e.send(c)}if(!z()||r||!("sendBeacon"in navigator)||s!==l.low||A.headers&&0!==Object.keys(A.headers).length)if(z()&&!r)u();else{const e=Tt({},A.headers,{"Content-Type":o});H.jwt&&(e.Authorization=`Bearer ${H.jwt}`),fetch(a,{method:"POST",mode:"no-cors",headers:e,body:c}).catch((e=>{i(e,{context:"AnalyticsSDKApiError"})}))}else{const e=new Blob([c],{type:kt});try{navigator.sendBeacon.bind(navigator)(a,e)||u()}catch(e){console.error(e),u()}}};var St=n(762),Et=n.n(St);const xt=(e,t,n)=>{const r=e||"";return Et()("2"+r+t+n)};function Ot(){return Ot=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var n;e&&je.eventsQueue.push(e),nt.isReady&&(!A.trackUserId||H.userId?(t===l.high||(n=Mt,0!==je.eventsQueue.length&&(je.eventsQueue.length>=A.batchEventsThreshold||(je.eventsScheduled||(je.eventsScheduled=!0,setTimeout((()=>{je.eventsScheduled=!1,n(vt(je.eventsQueue)),je.eventsQueue=[]}),A.batchEventsPeriod)),0))))&&Bt():je.eventsQueue.length>10&&(A.trackUserId=!1,A.onError(new Error("userId not set in Logged-in"))))},Mt=(e,t=l.low)=>{if(H.isOptOut||0===e.length)return;let n;try{n=JSON.stringify(e)}catch(t){const r=e.map((e=>e.event_type)).join(", "),[i,a]=(e=>{try{const n=[];for(const r of e){const e=Ot({},r);r.event_properties&&(e.event_properties=Ot({},e.event_properties,{currentTarget:null,target:null,relatedTarget:null,_dispatchInstances:null,_targetInst:null,view:(t=r.event_properties.view,["string","number","boolean"].includes(typeof t)?r.event_properties.view:null)})),n.push(e)}return[!0,JSON.stringify(n)]}catch(e){return[!1,""]}var t})(e);if(!i)return void A.onError(new jt(t instanceof Error?t.message:"unknown"),{listEventType:r});n=a,A.onError(new Nt("Found DOM element reference"),{listEventType:r,stringifiedEventData:n})}const r=Ae().toString(),i=It({},{e:n,v:"2",upload_time:r},{client:A.amplitudeApiKey,checksum:xt(A.amplitudeApiKey,n,r)});_t({url:A.eventsEndpoint,data:i,importance:t,onError:A.onError}),ut({metricName:"Batch Events",data:e,importance:t})},Bt=()=>{Mt(vt(je.eventsQueue)),Ne({eventsQueue:[]})};function Ct(){return Ct=Object.assign?Object.assign.bind():function(e){for(var t=1;tDt.includes(e)?e:f.unknown,Ut=e=>At.includes(e)?e:m.unknown,Rt=(e,t,n)=>{const r={auth:J()?b.loggedIn:b.notLoggedIn,action:Lt(e),component_type:Ut(t),logging_id:n,platform:A.platform,project_name:A.projectName};return"number"==typeof H.userTypeEnum&&(r.user_type_enum=H.userTypeEnum),r},qt=e=>{const t=Ae();if(!e)return A.onError(new Error("missing logData")),Ct({},Rt(f.unknown,m.unknown),{locale:H.locale,session_lcc_id:H.session_lcc_id,timestamp:t,time_start:Le.timeStart});const n=Ct({},e,Rt(e.action,e.componentType,e.loggingId),{locale:H.locale,session_lcc_id:H.session_lcc_id,timestamp:t,time_start:Le.timeStart});return delete n.componentType,delete n.loggingId,n},Ft={blacklistRegex:[],isEnabled:!1};function zt(){return{page_key:re.pageKey,page_path:re.pagePath,prev_page_key:re.prevPageKey,prev_page_path:re.prevPagePath}}function Kt(e){Object.assign(Ft,e)}function $t(e,t,n=l.low){if(H.isOptOut)return;if(!Oe())return;const r=qt(t);!function(e){Ft.isEnabled&&(ve(),Object.assign(e,zt()))}(r),be(r),function(e){Object.keys(Se).length>0&&Object.assign(e,Se)}(r),r.has_double_fired=!1,r.event_type=e,n===l.high?Pt(r,n):yt((()=>{Pt(r)}))}function Qt(e,t=!1){t?_t({url:A.metricsEndPoint,data:{metrics:e},isJSON:!0,onError:A.onError}):yt((()=>{_t({url:A.metricsEndPoint,data:{metrics:e},isJSON:!0,onError:A.onError})})),ut({metricName:"Batch Metrics",data:e})}function Wt(){return Wt=Object.assign?Object.assign.bind():function(e){for(var t=1;t{null!=A&&A.onMarkStep&&A.onMarkStep(e,t),xe({ujs:t})};let Yt;const en={Perfume:()=>{},markStep:e=>{},markStepOnce:e=>{},incrementUjNavigation:()=>{}},tn=()=>{z()&&Yt&&Yt.markNTBT&&Yt.markNTBT()},nn=e=>{z()&&Yt&&en.markStep&&en.markStep(e)},rn=e=>{z()&&Yt&&en.markStepOnce&&en.markStepOnce(e)},an=()=>{z()&&Yt&&en.incrementUjNavigation&&en.incrementUjNavigation()};function on(e={callMarkNTBT:!0}){"unknown"!==A.platform&&(Ft.blacklistRegex.some((e=>e.test(fe())))||($t(j,{action:f.render,componentType:m.page}),e.callMarkNTBT&&tn()))}let sn=!1,cn=!1;const un=e=>{sn=!e.persisted},ln=(e,t="hidden",n=!1)=>{cn||(addEventListener("pagehide",un),addEventListener("beforeunload",(()=>{})),cn=!0),addEventListener("visibilitychange",(({timeStamp:n})=>{document.visibilityState===t&&e({timeStamp:n,isUnloading:sn})}),{capture:!0,once:n})},dn=36e3;function pn(){const e=pt(Ae());if(e&&(O.forEach((e=>{oe[e]&&delete oe[e]})),st()),!oe.lastEventTime||!Le.sessionStart||!e)return;const t=Math.round((oe.lastEventTime-Le.sessionStart)/1e3);if(t<1||t>dn)return;const n=Ce(t);$t(N,{action:f.measurement,componentType:m.page,session_duration:t,session_end:oe.lastEventTime,session_start:Le.sessionStart,session_rank:n})}function mn(){return mn=Object.assign?Object.assign.bind():function(e){for(var t=1;t{const e=fn.shift();e&&e()},bn=()=>{const e=vn.shift();e&&e()};let hn={};function wn(e){const t=function(e){return{test_name:e.testName,group_name:e.group,subject_id:e.subjectId,exposed_at:Ae(),subject_type:e.subjectType,platform:A.platform}}(e);hn[e.testName]=hn[e.testName]||0,hn[e.testName]+k>Ae()?lt({metricName:`Event: exposeExperiment ${e.testName} not sent`,data:t}):(hn[e.testName]=Ae(),ot(E,hn),lt({metricName:`Event: exposeExperiment ${e.testName} sent`,data:t}),_t({url:A.exposureEndpoint,data:[t],onError:(t,n)=>{hn[e.testName]=0,ot(E,hn),A.onError(t,n)},isJSON:!0,importance:l.high}))}const yn=e=>{var t,r,i;U(e),z()&&(H.languageCode=(null==(t=navigator)?void 0:t.languages[0])||(null==(r=navigator)?void 0:r.language)||""),te(),(()=>{var e;if(z()&&null!=(e=window)&&e.indexedDB){const e=function(e,t,{blocked:n,upgrade:r,blocking:i,terminated:a}={}){const o=indexedDB.open(e,t),s=Je(o);return r&&o.addEventListener("upgradeneeded",(e=>{r(Je(o.result),e.oldVersion,e.newVersion,Je(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),s.then((e=>{a&&e.addEventListener("close",(()=>a())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),s}("keyval-store",1,{upgrade(e){e.createObjectStore("keyval")}});rt({idbKeyval:{get:async t=>(await e).get("keyval",t),set:async(t,n)=>(await e).put("keyval",n,t),delete:async t=>(await e).delete("keyval",t),keys:async()=>(await e).getAllKeys("keyval")}})}else rt({idbKeyval:{get:async e=>new Promise((t=>{t(it[e])})),set:async(e,t)=>new Promise((n=>{it[e]=t,n(e)})),delete:async e=>new Promise((()=>{delete it[e]})),keys:async()=>new Promise((e=>{e(Object.keys(it))}))}})})(),lt({metricName:"Initialized Analytics:",data:{deviceId:H.deviceId}}),fn.push((()=>{Pt()})),(async()=>{const e=await at(S);rt({isReady:!0}),gn(),e&&(bn(),se({eventId:e.eventId||oe.eventId,sequenceNumber:e.sequenceNumber||oe.sequenceNumber,sessionId:e.sessionId||oe.sessionId,lastEventTime:e.lastEventTime||oe.lastEventTime,sessionUUID:e.sessionUUID||oe.sessionUUID}),function(e){se(mn({},function(e){const t={};return O.forEach((n=>{e[n]&&(t[n]=e[n])})),t}(e),de()))}(e),Ue({sessionStart:e.sessionStart||oe.sessionStart}),De({ac:e.ac||Ie.ac,af:e.af||Ie.af,ah:e.ah||Ie.ah,al:e.al||Ie.al,am:e.am||Ie.am,ar:e.ar||Ie.ar,as:e.as||Ie.as,pv:e.pv||Ie.pv}),A.trackUserId&&Y({userId:e.userId||H.userId}),pn(),lt({metricName:"Initialized Analytics IndexedDB:",data:e}))})(),async function(){at(E).then((e=>{hn=null!=e?e:{}})).catch((e=>{e instanceof Error&&A.onError(e)}))}(),Z(),z()&&(ln((()=>{se({lastEventTime:Ae()}),st(),Bt()}),"hidden"),ln((()=>{pn()}),"visible")),z()&&(i=()=>{var e,t,n,r;te(),ee({width:null!=(e=null==(t=window)?void 0:t.innerWidth)?e:null,height:null!=(n=null==(r=window)?void 0:r.innerHeight)?n:null})},addEventListener("resize",(()=>{requestAnimationFrame((()=>{i()}))}))),(()=>{if(z())try{const e=n(2);en.markStep=e.markStep,en.markStepOnce=e.markStepOnce,en.incrementUjNavigation=e.incrementUjNavigation,Yt=new e.Perfume({analyticsTracker:e=>{const{data:t,attribution:n,metricName:r,navigatorInformation:i,rating:a}=e,o=I[r],s=(null==n?void 0:n.category)||null;if(!o&&!s)return;const c=(null==i?void 0:i.deviceMemory)||0,u=(null==i?void 0:i.hardwareConcurrency)||0,l=(null==i?void 0:i.isLowEndDevice)||!1,p=(null==i?void 0:i.isLowEndExperience)||!1,v=(null==i?void 0:i.serviceWorkerStatus)||"unsupported",g=Vt({deviceMemory:c,hardwareConcurrency:u,isLowEndDevice:l,isLowEndExperience:p,serviceWorkerStatus:v},Gt),b={is_low_end_device:l,is_low_end_experience:p,page_key:re.pageKey||"",save_data:t.saveData||!1,service_worker:v,is_perf_metric:!0};if("navigationTiming"===r)t&&"number"==typeof t.redirectTime&&Ht({metricName:I.redirectTime.eventName,metricType:d.histogram,tags:b,value:t.redirectTime||0});else if("TTFB"===r)$t(o.eventName,Vt({action:f.measurement,componentType:m.page,duration:t||null,vitalsScore:a||null},g)),Ht({metricName:I.TTFB.eventName,metricType:d.histogram,tags:Vt({},b),value:t}),a&&Ht({metricName:`perf_web_vitals_ttfb_${a}`,metricType:d.count,tags:b,value:1});else if("networkInformation"===r)null!=t&&t.effectiveType&&(Gt=t,$t(o.eventName,{action:f.measurement,componentType:m.page,networkInformationDownlink:t.downlink,networkInformationEffectiveType:t.effectiveType,networkInformationRtt:t.rtt,networkInformationSaveData:t.saveData,navigatorDeviceMemory:c,navigatorHardwareConcurrency:u}));else if("storageEstimate"===r)$t(o.eventName,Vt({action:f.measurement,componentType:m.page},t,g)),Ht({metricName:"perf_storage_estimate_caches",metricType:d.histogram,tags:b,value:t.caches}),Ht({metricName:"perf_storage_estimate_indexed_db",metricType:d.histogram,tags:b,value:t.indexedDB});else if("CLS"===r)$t(o.eventName,Vt({action:f.measurement,componentType:m.page,score:100*t||null,vitalsScore:a||null},g)),a&&Ht({metricName:`perf_web_vitals_cls_${a}`,metricType:d.count,tags:b,value:1});else if("FID"===r){const e=(null==n?void 0:n.performanceEntry)||null,r=parseInt((null==e?void 0:e.processingStart)||"");$t(o.eventName,Vt({action:f.measurement,componentType:m.page,duration:t||null,processingStart:null!=e&&e.processingStart?r:null,startTime:null!=e&&e.startTime?parseInt(e.startTime):null,vitalsScore:a||null},g)),a&&Ht({metricName:`perf_web_vitals_fidVitals_${a}`,metricType:d.count,tags:b,value:1})}else"userJourneyStep"===r?($t("perf_user_journey_step",Vt({action:f.measurement,componentType:m.page,duration:t||null,rating:null!=a?a:null,step_name:(null==n?void 0:n.stepName)||""},g)),Ht({metricName:`user_journey_step.${A.projectName}.${A.platform}.${(null==n?void 0:n.stepName)||""}_vitals_${a}`,metricType:d.count,tags:b,value:1}),Ht({metricName:`user_journey_step.${A.projectName}.${A.platform}.${(null==n?void 0:n.stepName)||""}`,metricType:d.distribution,tags:b,value:t||null})):I[r]&&t&&($t(o.eventName,Vt({action:f.measurement,componentType:m.page,duration:t||null,vitalsScore:a||null},g)),a&&(Ht({metricName:`perf_web_vitals_${Xt(r)}_${a}`,metricType:d.count,tags:b,value:1}),"LCP"===r&&Ht({metricName:`perf_web_vitals_${Xt(r)}`,metricType:d.distribution,tags:b,value:t})))},maxMeasureTime:3e4,steps:A.steps,onMarkStep:Zt})}catch(e){e instanceof Error&&A.onError(e)}})()},Tn=e=>{Y(e),e.userAgent&&Z(),lt({metricName:"Identify:",data:{countryCode:H.countryCode,deviceId:H.deviceId,userId:H.userId}})},kn=({blacklistRegex:e,pageKeyRegex:t,browserHistory:n})=>{Kt({blacklistRegex:e||[],isEnabled:!0}),ae({pageKeyRegex:t}),on({callMarkNTBT:!1}),n.listen((()=>{on()}))},_n=({blacklistRegex:e,pageKeyRegex:t,nextJsRouter:n})=>{Kt({blacklistRegex:e||[],isEnabled:!0}),ae({pageKeyRegex:t}),on({callMarkNTBT:!1}),n.events.on("routeChangeComplete",(()=>{on()}))},Sn=()=>{Y({isOptOut:!0}),ot(S,{})},En=()=>{Y({isOptOut:!1})},xn={Button:{label:"cb_button",uuid:"e921a074-40e6-4371-8700-134d5cd633e6",componentType:m.button}};function On(e,t,n){return{componentName:e,actions:t,data:n}}function jn(){return jn=Object.assign?Object.assign.bind():function(e){for(var t=1;tNn(xn.Button,f.click,e),[f.hover]:e=>Nn(xn.Button,f.hover,e)}}};function Pn(e,t=!1){t?_t({url:A.tracesEndpoint,data:{traces:e},isJSON:!0,onError:A.onError}):yt((()=>{_t({url:A.tracesEndpoint,data:{traces:e},isJSON:!0,onError:A.onError})})),ut({metricName:"Batch Traces",data:e})}function Mn(){return Mn=Object.assign?Object.assign.bind():function(e){for(var t=1;t0}(e)&&(t&&function(e,t){e.forEach((e=>function(e,t){const n=Mn({},e.meta,t.meta),r={start:t.start?Cn(t.start):e.start,duration:t.duration?Cn(t.duration):e.duration};Object.assign(e,t,Mn({meta:n},r))}(e,t)))}(e,t),je.tracesQueue.push(e),wt(Pn)&&(Pn(je.tracesQueue),je.tracesQueue=[]))}function qn(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}function Fn(){return Fn=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0||(i[n]=e[n]);return i}(Qn,[n].map(qn));Qn=r}function Jn(e,t){if(!zn())return;const n=$n(e,"start",t);Qn[n]&&(Wn(e,"end",t),Vn(e,t))}function Xn(){zn()&&(performance.clearMarks(),Qn={})}var Gn=n(784);function Zn(){return Zn=Object.assign?Object.assign.bind():function(e){for(var t=1;t{r.current=t}),[t]),(0,Gn.useCallback)((t=>{$t(e,Zn({},r.current,t),n)}),[e,n])}function er(){return er=Object.assign?Object.assign.bind():function(e){for(var t=1;t{const r=er({},t,{action:f.render});$t(e,r,n)}),[])}function nr(){return nr=Object.assign?Object.assign.bind():function(e){for(var t=1;tHn(e,t)),[e,t]),markEndPerf:(0,Gn.useCallback)((n=>Jn(e,nr({},t,n))),[e,t])}};function ir(){return ir=Object.assign?Object.assign.bind():function(e){for(var t=1;t{return null!=(n=t[1])&&""!==n?ir({},e,{[t[0]]:t[1]}):e;var n}),{})}async function or(){return new Promise((e=>{Mt(vt(je.eventsQueue)),Qt(bt(je.metricsQueue),!0),Pn(je.tracesQueue,!0),Ne({eventsQueue:[],metricsQueue:[],tracesQueue:[]}),e()}))}function sr(){return{"X-CB-Device-ID":H.deviceId||"unknown","X-CB-Is-Logged-In":H.userId?"true":"false","X-CB-Pagekey":re.pageKey||"unknown","X-CB-UJS":(e=Se.ujs,void 0===e||0===e.length?"":e.join(",")),"X-CB-Platform":A.platform||"unknown","X-CB-Project-Name":A.projectName||"unknown","X-CB-Session-UUID":oe.sessionUUID||"unknown","X-CB-Version-Name":A.version?String(A.version):"unknown"};var e}})(),r})()}));',df=()=>new Promise((e,t)=>{if(window.ClientAnalytics)return e();try{const n=document.createElement("script");n.textContent=uf,n.type="text/javascript",document.head.appendChild(n),lf(),document.head.removeChild(n),e()}catch{console.error("Failed to execute inlined telemetry script"),t()}}),lf=()=>{var e,t,n;if(typeof window<"u"){const r=(n=(e=T.config.get().deviceId)!==null&&e!==void 0?e:(t=window.crypto)===null||t===void 0?void 0:t.randomUUID())!==null&&n!==void 0?n:"";if(window.ClientAnalytics){const{init:a,identify:s,PlatformName:i}=window.ClientAnalytics;a({isProd:!0,amplitudeApiKey:"c66737ad47ec354ced777935b0af822e",platform:i.web,projectName:"base_account_sdk",showDebugLogging:!1,version:"1.0.0",apiEndpoint:"https://cca-lite.coinbase.com"}),s({deviceId:r}),T.config.set({deviceId:r})}}},Q={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901,unsupportedChain:4902}},pr={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}},fi="Unspecified error message.",ff="Unspecified server error.";function Ur(e,t=fi){if(e&&Number.isInteger(e)){const n=e.toString();if(mr(pr,n))return pr[n].message;if(pi(e))return ff}return t}function pf(e){if(!Number.isInteger(e))return!1;const t=e.toString();return!!(pr[t]||pi(e))}function mf(e,{shouldIncludeStack:t=!1}={}){const n={};if(e&&typeof e=="object"&&!Array.isArray(e)&&mr(e,"code")&&pf(e.code)){const r=e;n.code=r.code,r.message&&typeof r.message=="string"?(n.message=r.message,mr(r,"data")&&(n.data=r.data)):(n.message=Ur(n.code),n.data={originalError:Sa(e)})}else n.code=Q.rpc.internal,n.message=Aa(e,"message")?e.message:fi,n.data={originalError:Sa(e)};return t&&(n.stack=Aa(e,"stack")?e.stack:void 0),n}function pi(e){return e>=-32099&&e<=-32e3}function Sa(e){return e&&typeof e=="object"&&!Array.isArray(e)?Object.assign({},e):e}function mr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Aa(e,t){return typeof e=="object"&&e!==null&&t in e&&typeof e[t]=="string"}const _={rpc:{parse:e=>fe(Q.rpc.parse,e),invalidRequest:e=>fe(Q.rpc.invalidRequest,e),invalidParams:e=>fe(Q.rpc.invalidParams,e),methodNotFound:e=>fe(Q.rpc.methodNotFound,e),internal:e=>fe(Q.rpc.internal,e),server:e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:t}=e;if(!Number.isInteger(t)||t>-32005||t<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return fe(t,e)},invalidInput:e=>fe(Q.rpc.invalidInput,e),resourceNotFound:e=>fe(Q.rpc.resourceNotFound,e),resourceUnavailable:e=>fe(Q.rpc.resourceUnavailable,e),transactionRejected:e=>fe(Q.rpc.transactionRejected,e),methodNotSupported:e=>fe(Q.rpc.methodNotSupported,e),limitExceeded:e=>fe(Q.rpc.limitExceeded,e)},provider:{userRejectedRequest:e=>et(Q.provider.userRejectedRequest,e),unauthorized:e=>et(Q.provider.unauthorized,e),unsupportedMethod:e=>et(Q.provider.unsupportedMethod,e),disconnected:e=>et(Q.provider.disconnected,e),chainDisconnected:e=>et(Q.provider.chainDisconnected,e),unsupportedChain:e=>et(Q.provider.unsupportedChain,e),custom:e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:t,message:n,data:r}=e;if(!n||typeof n!="string")throw new Error('"message" must be a nonempty string');return new hi(t,n,r)}}};function fe(e,t){const[n,r]=mi(t);return new Fr(e,n||Ur(e),r)}function et(e,t){const[n,r]=mi(t);return new hi(e,n||Ur(e),r)}function mi(e){if(e){if(typeof e=="string")return[e];if(typeof e=="object"&&!Array.isArray(e)){const{message:t,data:n}=e;if(t&&typeof t!="string")throw new Error("Must specify string message.");return[t||void 0,n]}}return[]}class Fr extends Error{constructor(t,n,r){if(!Number.isInteger(t))throw new Error('"code" must be an integer.');if(!n||typeof n!="string")throw new Error('"message" must be a nonempty string.');super(n),this.code=t,r!==void 0&&(this.data=r)}}class hi extends Fr{constructor(t,n,r){if(!hf(t))throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');super(t,n,r)}}function hf(e){return Number.isInteger(e)&&e>=1e3&&e<=4999}function _a(e){return typeof e=="object"&&e!==null&&"code"in e&&"data"in e&&e.code===-32090&&typeof e.data=="object"&&e.data!==null&&"type"in e.data&&e.data.type==="INSUFFICIENT_FUNDS"}function yi(e){return typeof e=="object"&&e!==null&&"details"in e}function yf(e){try{const t=JSON.parse(e.details);return new Fr(t.code,t.message,t.data)}catch{return null}}function gi(){return e=>e}const Tt=gi(),gf=gi();function Oe(e){return Math.floor(e)}const bi=/^[0-9]*$/,wi=/^[a-f0-9]*$/;function He(e){return $r(crypto.getRandomValues(new Uint8Array(e)))}function $r(e){return[...e].map(t=>t.toString(16).padStart(2,"0")).join("")}function Zt(e){return new Uint8Array(e.match(/.{1,2}/g).map(t=>Number.parseInt(t,16)))}function _t(e,t=!1){const n=e.toString("hex");return Tt(t?`0x${n}`:n)}function In(e){return _t(yr(e),!0)}function ve(e){return gf(e.toString(10))}function at(e){return Tt(`0x${BigInt(e).toString(16)}`)}function vi(e){return e.startsWith("0x")||e.startsWith("0X")}function Gr(e){return vi(e)?e.slice(2):e}function ki(e){return vi(e)?`0x${e.slice(2)}`:`0x${e}`}function kn(e){if(typeof e!="string")return!1;const t=Gr(e).toLowerCase();return wi.test(t)}function hr(e,t=!1){if(typeof e=="string"){const n=Gr(e).toLowerCase();if(wi.test(n))return Tt(t?`0x${n}`:n)}throw _.rpc.invalidParams(`"${String(e)}" is not a hexadecimal string`)}function Hr(e,t=!1){let n=hr(e,!1);return n.length%2===1&&(n=Tt(`0${n}`)),t?Tt(`0x${n}`):n}function Ne(e){if(typeof e=="string"){const t=Gr(e).toLowerCase();if(kn(t)&&t.length===40)return ki(t)}throw _.rpc.invalidParams(`Invalid Ethereum address: ${String(e)}`)}function yr(e){if(Buffer.isBuffer(e))return e;if(typeof e=="string"){if(kn(e)){const t=Hr(e,!1);return Buffer.from(t,"hex")}return Buffer.from(e,"utf8")}throw _.rpc.invalidParams(`Not binary data: ${String(e)}`)}function It(e){if(typeof e=="number"&&Number.isInteger(e))return Oe(e);if(typeof e=="string"){if(bi.test(e))return Oe(Number(e));if(kn(e))return Oe(Number(BigInt(Hr(e,!0))))}throw _.rpc.invalidParams(`Not an integer: ${String(e)}`)}function wt(e){if(e!==null&&(typeof e=="bigint"||wf(e)))return BigInt(e.toString(10));if(typeof e=="number")return BigInt(It(e));if(typeof e=="string"){if(bi.test(e))return BigInt(e);if(kn(e))return BigInt(Hr(e,!0))}throw _.rpc.invalidParams(`Not an integer: ${String(e)}`)}function bf(e){if(typeof e=="string")return JSON.parse(e);if(typeof e=="object")return e;throw _.rpc.invalidParams(`Not a JSON string or an object: ${String(e)}`)}function wf(e){if(e==null||typeof e.constructor!="function")return!1;const{constructor:t}=e;return typeof t.config=="function"&&typeof t.EUCLID=="number"}const vf=`Coinbase Wallet SDK requires the Cross-Origin-Opener-Policy header to not be set to 'same-origin'. This is to ensure that the SDK can communicate with the Coinbase Smart Wallet app. + +Please see https://www.smartwallet.dev/guides/tips/popup-tips#cross-origin-opener-policy for more information.`,kf=()=>{let e;return{getCrossOriginOpenerPolicy:()=>e===void 0?"undefined":e,checkCrossOriginOpenerPolicy:async()=>{if(typeof window>"u"){e="non-browser-env";return}try{const t=`${window.location.origin}${window.location.pathname}`,n=await fetch(t,{method:"HEAD"});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);const r=n.headers.get("Cross-Origin-Opener-Policy");e=r??"null",e==="same-origin"&&console.error(vf)}catch(t){console.error("Error checking Cross-Origin-Opener-Policy:",t.message),e="error"}}}},{checkCrossOriginOpenerPolicy:xf,getCrossOriginOpenerPolicy:Ef}=kf();async function Pt(e,t){const n=Object.assign(Object.assign({},e),{jsonrpc:"2.0",id:crypto.randomUUID()}),r=await window.fetch(t,{method:"POST",body:JSON.stringify(n),mode:"cors",headers:{"Content-Type":"application/json","X-Cbw-Sdk-Version":ht,"X-Cbw-Sdk-Platform":di}}),{result:a,error:s}=await r.json();if(s)throw s;return a}function Sf(){return globalThis.coinbaseWalletExtension}function Af(){var e,t;try{const n=globalThis;return(e=n.ethereum)!==null&&e!==void 0?e:(t=n.top)===null||t===void 0?void 0:t.ethereum}catch{return}}function _f({metadata:e,preference:t}){var n,r;const{appName:a,appLogoUrl:s,appChainIds:i}=e;if(t.options!=="smartWalletOnly"){const c=Sf();if(c)return(n=c.setAppInfo)===null||n===void 0||n.call(c,a,s,i,t),c}const o=Af();if(o?.isCoinbaseBrowser)return(r=o.setAppInfo)===null||r===void 0||r.call(o,a,s,i,t),o}function If(e){if(!e||typeof e!="object"||Array.isArray(e))throw _.rpc.invalidParams({message:"Expected a single, non-array, object argument.",data:e});const{method:t,params:n}=e;if(typeof t!="string"||t.length===0)throw _.rpc.invalidParams({message:"'args.method' must be a non-empty string.",data:e});if(n!==void 0&&!Array.isArray(n)&&(typeof n!="object"||n===null))throw _.rpc.invalidParams({message:"'args.params' must be an object or array if provided.",data:e});switch(t){case"eth_sign":case"eth_signTypedData_v2":case"eth_subscribe":case"eth_unsubscribe":throw _.provider.unsupportedMethod()}}function Pf(e){if(e){if(!["all","smartWalletOnly","eoaOnly"].includes(e.options))throw new Error(`Invalid options: ${e.options}`);if(e.attribution&&e.attribution.auto!==void 0&&e.attribution.dataSuffix!==void 0)throw new Error("Attribution cannot contain both auto and dataSuffix properties");if(e.telemetry&&typeof e.telemetry!="boolean")throw new Error("Telemetry must be a boolean")}}function Ia(e){if(typeof e!="function")throw new Error("toAccount is not a function")}const Of="https://keys.coinbase.com/connect",xi="https://rpc.wallet.coinbase.com",Pa="https://www.walletlink.org",Cf="https://go.cb-w.com/walletlink";var G;(function(e){e.unknown="unknown",e.banner="banner",e.button="button",e.card="card",e.chart="chart",e.content_script="content_script",e.dropdown="dropdown",e.link="link",e.page="page",e.modal="modal",e.table="table",e.search_bar="search_bar",e.service_worker="service_worker",e.text="text",e.text_input="text_input",e.tray="tray",e.checkbox="checkbox",e.icon="icon"})(G||(G={}));var H;(function(e){e.unknown="unknown",e.blur="blur",e.click="click",e.change="change",e.dismiss="dismiss",e.focus="focus",e.hover="hover",e.select="select",e.measurement="measurement",e.move="move",e.process="process",e.render="render",e.scroll="scroll",e.view="view",e.search="search",e.keyPress="keyPress",e.error="error"})(H||(H={}));var z;(function(e){e.low="low",e.high="high"})(z||(z={}));function V(e,t,n){var r,a,s,i;window.ClientAnalytics&&((r=window.ClientAnalytics)===null||r===void 0||r.logEvent(e,Object.assign(Object.assign({},t),{sdkVersion:ht,appName:(s=(a=T.config.get().metadata)===null||a===void 0?void 0:a.appName)!==null&&s!==void 0?s:"",appOrigin:window.location.origin,appPreferredSigner:(i=T.config.get().preference)===null||i===void 0?void 0:i.options}),n))}const Tf=()=>{V("communicator.popup_setup.started",{action:H.unknown,componentType:G.unknown},z.high)},Nf=()=>{V("communicator.popup_setup.completed",{action:H.unknown,componentType:G.unknown},z.high)},Bf=()=>{V("communicator.popup_unload.received",{action:H.unknown,componentType:G.unknown},z.high)},zr=({snackbarContext:e})=>{V(`snackbar.${e}.shown`,{action:H.render,componentType:G.modal,snackbarContext:e},z.high)},st=({snackbarContext:e,snackbarAction:t})=>{V(`snackbar.${e}.action_clicked`,{action:H.click,componentType:G.button,snackbarContext:e,snackbarAction:t},z.high)},Lf='@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}';function Ei(){const e=document.createElement("style");e.type="text/css",e.appendChild(document.createTextNode(Lf)),document.documentElement.appendChild(e)}function Si(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;t{this.items.delete(n),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&Nn(J("div",null,J(Ii,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([t,n])=>J($f,Object.assign({},n,{key:t}))))),this.root)}}const Ii=e=>J("div",{class:Ot("-cbwsdk-snackbar-container")},J("style",null,Df),J("div",{class:"-cbwsdk-snackbar"},e.children)),$f=({autoExpand:e,message:t,menuItems:n})=>{const[r,a]=Zr(!0),[s,i]=Zr(e??!1);jo(()=>{const c=[window.setTimeout(()=>{a(!1)},1),window.setTimeout(()=>{i(!0)},1e4)];return()=>{c.forEach(window.clearTimeout)}});const o=()=>{i(!s)};return J("div",{class:Ot("-cbwsdk-snackbar-instance",r&&"-cbwsdk-snackbar-instance-hidden",s&&"-cbwsdk-snackbar-instance-expanded")},J("div",{class:"-cbwsdk-snackbar-instance-header",onClick:o},J("img",{src:Uf,class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",J("div",{class:"-cbwsdk-snackbar-instance-header-message"},t),J("div",{class:"-gear-container"},!s&&J("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},J("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),J("img",{src:Ff,class:"-gear-icon",title:"Expand"}))),n&&n.length>0&&J("div",{class:"-cbwsdk-snackbar-instance-menu"},n.map((c,u)=>J("div",{class:Ot("-cbwsdk-snackbar-instance-menu-item",c.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:c.onClick,key:u},J("svg",{width:c.svgWidth,height:c.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},J("path",{"fill-rule":c.defaultFillRule,"clip-rule":c.defaultClipRule,d:c.path,fill:"#AAAAAA"})),J("span",{class:Ot("-cbwsdk-snackbar-instance-menu-item-info",c.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},c.info)))))},Pi="M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z";class Gf{constructor(){this.attached=!1,this.snackbar=new _i}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");const t=document.documentElement,n=document.createElement("div");n.className="-cbwsdk-css-reset",t.appendChild(n),this.snackbar.attach(n),this.attached=!0,Ei()}showConnecting(t){let n;return t.isUnlinkedErrorState?n={autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:t.onResetConnection}]}:n={message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:t.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:Pi,defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:t.onResetConnection}]},this.snackbar.presentItem(n)}}const Oa=420,Ca=700,Hf={isRed:!1,info:"Retry",svgWidth:"10",svgHeight:"11",path:Pi,defaultFillRule:"evenodd",defaultClipRule:"evenodd"},zf="Popup was blocked. Try again.";let $t=null;function qf(e){const t=(window.innerWidth-Oa)/2+window.screenX,n=(window.innerHeight-Ca)/2+window.screenY;Vf(e);function r(){const s=`wallet_${crypto.randomUUID()}`,i=window.open(e,s,`width=${Oa}, height=${Ca}, left=${t}, top=${n}`);return i?.focus(),i||null}let a=r();if(!a){const s=qr();return new Promise((i,o)=>{zr({snackbarContext:"popup_blocked"}),s.presentItem({autoExpand:!0,message:zf,menuItems:[Object.assign(Object.assign({},Hf),{onClick:()=>{st({snackbarContext:"popup_blocked",snackbarAction:"confirm"}),a=r(),a?i(a):o(_.rpc.internal("Popup window was blocked")),s.clear()}})]})})}return Promise.resolve(a)}function Wf(e){e&&!e.closed&&e.close()}function Vf(e){const t={sdkName:di,sdkVersion:ht,origin:window.location.origin,coop:Ef()};for(const[n,r]of Object.entries(t))e.searchParams.has(n)||e.searchParams.append(n,r.toString())}function qr(){if(!$t){const e=document.createElement("div");e.className="-cbwsdk-css-reset",document.body.appendChild(e),$t=new _i,$t.attach(e)}return $t}class Kf{constructor({url:t=Of,metadata:n,preference:r}){this.popup=null,this.listeners=new Map,this.postMessage=async a=>{(await this.waitForPopupLoaded()).postMessage(a,this.url.origin)},this.postRequestAndWaitForResponse=async a=>{const s=this.onMessage(({requestId:i})=>i===a.id);return this.postMessage(a),await s},this.onMessage=async a=>new Promise((s,i)=>{const o=c=>{if(c.origin!==this.url.origin)return;const u=c.data;a(u)&&(s(u),window.removeEventListener("message",o),this.listeners.delete(o))};window.addEventListener("message",o),this.listeners.set(o,{reject:i})}),this.disconnect=()=>{Wf(this.popup),this.popup=null,this.listeners.forEach(({reject:a},s)=>{a(_.provider.userRejectedRequest("Request rejected")),window.removeEventListener("message",s)}),this.listeners.clear()},this.waitForPopupLoaded=async()=>this.popup&&!this.popup.closed?(this.popup.focus(),this.popup):(Tf(),this.popup=await qf(this.url),this.onMessage(({event:a})=>a==="PopupUnload").then(()=>{this.disconnect(),Bf()}).catch(()=>{}),this.onMessage(({event:a})=>a==="PopupLoaded").then(a=>{this.postMessage({requestId:a.id,data:{version:ht,metadata:this.metadata,preference:this.preference,location:window.location.toString()}})}).then(()=>{if(!this.popup)throw _.rpc.internal();return Nf(),this.popup})),this.url=new URL(t),this.metadata=n,this.preference=r}}function ae(e){return e.errorMessage!==void 0}function Jf(e){const t=mf(Zf(e),{shouldIncludeStack:!0}),n=new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors");return n.searchParams.set("version",ht),n.searchParams.set("code",t.code.toString()),n.searchParams.set("message",t.message),Object.assign(Object.assign({},t),{docUrl:n.href})}function Zf(e){var t;if(typeof e=="string")return{message:e,code:Q.rpc.internal};if(ae(e)){const n=e.errorMessage,r=(t=e.errorCode)!==null&&t!==void 0?t:n.match(/(denied|rejected)/i)?Q.provider.userRejectedRequest:void 0;return Object.assign(Object.assign({},e),{message:n,code:r,data:{method:e.method}})}return e}var Oi={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function a(c,u,d){this.fn=c,this.context=u,this.once=d||!1}function s(c,u,d,l,p){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new a(d,l||c,p),y=n?n+u:u;return c._events[y]?c._events[y].fn?c._events[y]=[c._events[y],f]:c._events[y].push(f):(c._events[y]=f,c._eventsCount++),c}function i(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],d,l;if(this._eventsCount===0)return u;for(l in d=this._events)t.call(d,l)&&u.push(n?l.slice(1):l);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},o.prototype.listeners=function(u){var d=n?n+u:u,l=this._events[d];if(!l)return[];if(l.fn)return[l.fn];for(var p=0,f=l.length,y=new Array(f);plocalStorage.removeItem(r))}scopedKey(t){return`-${this.scope}${this.module?`:${this.module}`:""}:${t}`}static clearAll(){new Ze("CBWSDK").clear(),new Ze("walletlink").clear()}}const ep=({signerType:e})=>{V("provider.signer.loaded_from_storage",{action:H.measurement,componentType:G.unknown,signerType:e},z.low)},tp=({method:e,correlationId:t})=>{V("provider.request.started",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t},z.high)},np=({method:e,correlationId:t,signerType:n,errorMessage:r})=>{V("provider.request.error",{action:H.error,componentType:G.unknown,method:e,signerType:n,correlationId:t,errorMessage:r},z.high)},rp=({method:e,signerType:t,correlationId:n})=>{V("provider.request.responded",{action:H.unknown,componentType:G.unknown,method:e,signerType:t,correlationId:n},z.high)},ap=()=>{V("provider.enable_function.called",{action:H.measurement,componentType:G.unknown},z.high)},sp=()=>{V("signer.selection.requested",{action:H.unknown,componentType:G.unknown},z.high)},ip=e=>{V("signer.selection.responded",{action:H.unknown,componentType:G.unknown,signerType:e},z.high)},Gt=Br(()=>({correlationIds:new Map})),ge={get:e=>Gt.getState().correlationIds.get(e),set:(e,t)=>{Gt.setState(n=>{const r=new Map(n.correlationIds);return r.set(e,t),{correlationIds:r}})},delete:e=>{Gt.setState(t=>{const n=new Map(t.correlationIds);return n.delete(e),{correlationIds:n}})},clear:()=>{Gt.setState({correlationIds:new Map})}},op=({method:e,correlationId:t})=>{var n;V("scw_signer.handshake.started",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t,enableAutoSubAccounts:(n=T.subAccountsConfig.get())===null||n===void 0?void 0:n.enableAutoSubAccounts},z.high)},cp=({method:e,correlationId:t,errorMessage:n})=>{var r;V("scw_signer.handshake.error",{action:H.error,componentType:G.unknown,method:e,correlationId:t,errorMessage:n,enableAutoSubAccounts:(r=T.subAccountsConfig.get())===null||r===void 0?void 0:r.enableAutoSubAccounts},z.high)},up=({method:e,correlationId:t})=>{var n;V("scw_signer.handshake.completed",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t,enableAutoSubAccounts:(n=T.subAccountsConfig.get())===null||n===void 0?void 0:n.enableAutoSubAccounts},z.high)},dp=({method:e,correlationId:t})=>{var n;V("scw_signer.request.started",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t,enableAutoSubAccounts:(n=T.subAccountsConfig.get())===null||n===void 0?void 0:n.enableAutoSubAccounts},z.high)},lp=({method:e,correlationId:t,errorMessage:n})=>{var r;V("scw_signer.request.error",{action:H.error,componentType:G.unknown,method:e,correlationId:t,errorMessage:n,enableAutoSubAccounts:(r=T.subAccountsConfig.get())===null||r===void 0?void 0:r.enableAutoSubAccounts},z.high)},fp=({method:e,correlationId:t})=>{var n;V("scw_signer.request.completed",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t,enableAutoSubAccounts:(n=T.subAccountsConfig.get())===null||n===void 0?void 0:n.enableAutoSubAccounts},z.high)},pp=({method:e,correlationId:t})=>{var n;V("scw_sub_account.request.started",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t,enableAutoSubAccounts:(n=T.subAccountsConfig.get())===null||n===void 0?void 0:n.enableAutoSubAccounts},z.high)},mp=({method:e,correlationId:t})=>{var n;V("scw_sub_account.request.completed",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t,enableAutoSubAccounts:(n=T.subAccountsConfig.get())===null||n===void 0?void 0:n.enableAutoSubAccounts},z.high)},hp=({method:e,correlationId:t,errorMessage:n})=>{var r;V("scw_sub_account.request.error",{action:H.error,componentType:G.unknown,method:e,correlationId:t,errorMessage:n,enableAutoSubAccounts:(r=T.subAccountsConfig.get())===null||r===void 0?void 0:r.enableAutoSubAccounts},z.high)},yp=({method:e,correlationId:t})=>{var n;V("scw_sub_account.add_owner.started",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t,enableAutoSubAccounts:(n=T.subAccountsConfig.get())===null||n===void 0?void 0:n.enableAutoSubAccounts},z.high)},gp=({method:e,correlationId:t})=>{var n;V("scw_sub_account.add_owner.completed",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t,enableAutoSubAccounts:(n=T.subAccountsConfig.get())===null||n===void 0?void 0:n.enableAutoSubAccounts},z.high)},bp=({method:e,correlationId:t,errorMessage:n})=>{var r;V("scw_sub_account.add_owner.error",{action:H.error,componentType:G.unknown,method:e,correlationId:t,errorMessage:n,enableAutoSubAccounts:(r=T.subAccountsConfig.get())===null||r===void 0?void 0:r.enableAutoSubAccounts},z.high)},wp=({method:e,correlationId:t})=>{var n;V("scw_sub_account.insufficient_balance.error_handling.started",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t,enableAutoSubAccounts:(n=T.subAccountsConfig.get())===null||n===void 0?void 0:n.enableAutoSubAccounts},z.high)},vp=({method:e,correlationId:t})=>{var n;V("scw_sub_account.insufficient_balance.error_handling.completed",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t,enableAutoSubAccounts:(n=T.subAccountsConfig.get())===null||n===void 0?void 0:n.enableAutoSubAccounts},z.high)},kp=({method:e,correlationId:t,errorMessage:n})=>{var r;V("scw_sub_account.insufficient_balance.error_handling.error",{action:H.error,componentType:G.unknown,method:e,correlationId:t,errorMessage:n,enableAutoSubAccounts:(r=T.subAccountsConfig.get())===null||r===void 0?void 0:r.enableAutoSubAccounts},z.high)},ze=e=>"message"in e&&typeof e.message=="string"?e.message:"",Ci=Br(()=>({}));function Ta(e){e.forEach(t=>{var n,r,a,s,i,o,c,u;if(!t.rpcUrl)return;const d=Yc({id:t.id,rpcUrls:{default:{http:[t.rpcUrl]}},name:(r=(n=t.nativeCurrency)===null||n===void 0?void 0:n.name)!==null&&r!==void 0?r:"",nativeCurrency:{name:(s=(a=t.nativeCurrency)===null||a===void 0?void 0:a.name)!==null&&s!==void 0?s:"",symbol:(o=(i=t.nativeCurrency)===null||i===void 0?void 0:i.symbol)!==null&&o!==void 0?o:"",decimals:(u=(c=t.nativeCurrency)===null||c===void 0?void 0:c.decimal)!==null&&u!==void 0?u:18}}),l=hd({chain:d,transport:ia(t.rpcUrl)}),p=zd({client:l,transport:ia(t.rpcUrl)});Ci.setState({[t.id]:{client:l,bundlerClient:p}})})}function Ti(e){var t;return(t=Ci.getState()[e])===null||t===void 0?void 0:t.client}function le(e,t,n){if(e==null)throw t??_.rpc.invalidParams({message:"value must be present",data:e})}function Re(e,t){if(!Array.isArray(e))throw _.rpc.invalidParams({message:t??"value must be an array",data:e})}function Ht(e){if(typeof e!="object"||e===null)throw _.rpc.internal("sub account info is not an object");if(!("address"in e))throw _.rpc.internal("sub account is invalid");if("address"in e&&typeof e.address=="string"&&!ct(e.address))throw _.rpc.internal("sub account address is invalid");if("factory"in e&&typeof e.factory=="string"&&!ct(e.factory))throw _.rpc.internal("sub account factory address is invalid");if("factoryData"in e&&typeof e.factoryData=="string"&&!Ge(e.factoryData))throw _.rpc.internal("sub account factory data is invalid")}async function xp(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"])}async function Ep(e,t){return crypto.subtle.deriveKey({name:"ECDH",public:t},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Sp(e,t){const n=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,new TextEncoder().encode(t));return{iv:n,cipherText:r}}async function Ap(e,{iv:t,cipherText:n}){const r=await crypto.subtle.decrypt({name:"AES-GCM",iv:t},e,n);return new TextDecoder().decode(r)}function Ni(e){switch(e){case"public":return"spki";case"private":return"pkcs8"}}async function Bi(e,t){const n=Ni(e),r=await crypto.subtle.exportKey(n,t);return $r(new Uint8Array(r))}async function Li(e,t){const n=Ni(e),r=Zt(t).buffer;return await crypto.subtle.importKey(n,new Uint8Array(r),{name:"ECDH",namedCurve:"P-256"},!0,e==="private"?["deriveKey"]:[])}async function _p(e,t){const n=JSON.stringify(e,(r,a)=>{if(!(a instanceof Error))return a;const s=a;return Object.assign(Object.assign({},s.code?{code:s.code}:{}),{message:s.message})});return Sp(t,n)}async function Ip(e,t){return JSON.parse(await Ap(t,e))}function Pp(e,t){const n=typeof indexedDB<"u"?Qc(e,t):void 0;return{getItem:async r=>{const a=await Xc(r,n);return a||null},removeItem:async r=>eu(r,n),setItem:async(r,a)=>tu(r,a,n)}}const Op="cbwsdk",Cp="keys",Wr="activeId",mt=Pp(Op,Cp);async function Tp(){const e=await Wl({extractable:!1}),t=me(jr(e.publicKey),1);return await mt.setItem(t,e),await mt.setItem(Wr,t),e}async function Np(){const e=await mt.getItem(Wr);if(!e)return null;const t=await mt.getItem(e);return t||null}async function Bp(){const e=await Np();if(!e){const t=await Tp(),n=me(jr(t.publicKey),1);return await mt.setItem(n,t),await mt.setItem(Wr,n),t}return e}async function Lp(){const e=await Bp(),t=me(jr(e.publicKey),1),n=async r=>{const{payload:a,metadata:s}=ql({challenge:r,origin:"https://keys.coinbase.com",userVerification:"preferred"}),i=await Vl({payload:a,privateKey:e.privateKey});return{signature:wl(i),raw:{},webauthn:s}};return{id:t,publicKey:t,async sign({hash:r}){return n(r)},async signMessage({message:r}){return n(Pr(r))},async signTypedData(r){return n(Lt(r))},type:"webAuthn"}}async function gr(){return{account:await Lp()}}const Na={storageKey:"ownPrivateKey",keyType:"private"},Ba={storageKey:"ownPublicKey",keyType:"public"},La={storageKey:"peerPublicKey",keyType:"public"};class Rp{constructor(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null}async getOwnPublicKey(){return await this.loadKeysIfNeeded(),this.ownPublicKey}async getSharedSecret(){return await this.loadKeysIfNeeded(),this.sharedSecret}async setPeerPublicKey(t){this.sharedSecret=null,this.peerPublicKey=t,await this.storeKey(La,t),await this.loadKeysIfNeeded()}async clear(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null,T.keys.clear()}async generateKeyPair(){const t=await xp();this.ownPrivateKey=t.privateKey,this.ownPublicKey=t.publicKey,await this.storeKey(Na,t.privateKey),await this.storeKey(Ba,t.publicKey)}async loadKeysIfNeeded(){if(this.ownPrivateKey===null&&(this.ownPrivateKey=await this.loadKey(Na)),this.ownPublicKey===null&&(this.ownPublicKey=await this.loadKey(Ba)),(this.ownPrivateKey===null||this.ownPublicKey===null)&&await this.generateKeyPair(),this.peerPublicKey===null&&(this.peerPublicKey=await this.loadKey(La)),this.sharedSecret===null){if(this.ownPrivateKey===null||this.peerPublicKey===null)return;this.sharedSecret=await Ep(this.ownPrivateKey,this.peerPublicKey)}}async loadKey(t){const n=T.keys.get(t.storageKey);return n?Li(t.keyType,n):null}async storeKey(t,n){const r=await Bi(t.keyType,n);T.keys.set(t.storageKey,r)}}function Et(e,t){if(!(typeof e!="object"||e===null))return t.split(/[.[\]]+/).filter(Boolean).reduce((n,r)=>{if(typeof n=="object"&&n!==null)return n[r]},e)}const Ri="0x0ba5ed0c6aa8c49038f819e587e2633c4a9f428a",ji="0xf85210B21cC50302F477BA56686d2019dC9b67Ad",be=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"owner",type:"bytes"}],name:"AlreadyOwner",type:"error"},{inputs:[],name:"Initialized",type:"error"},{inputs:[{name:"owner",type:"bytes"}],name:"InvalidEthereumAddressOwner",type:"error"},{inputs:[{name:"key",type:"uint256"}],name:"InvalidNonceKey",type:"error"},{inputs:[{name:"owner",type:"bytes"}],name:"InvalidOwnerBytesLength",type:"error"},{inputs:[],name:"LastOwner",type:"error"},{inputs:[{name:"index",type:"uint256"}],name:"NoOwnerAtIndex",type:"error"},{inputs:[{name:"ownersRemaining",type:"uint256"}],name:"NotLastOwner",type:"error"},{inputs:[{name:"selector",type:"bytes4"}],name:"SelectorNotAllowed",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{inputs:[],name:"UnauthorizedCallContext",type:"error"},{inputs:[],name:"UpgradeFailed",type:"error"},{inputs:[{name:"index",type:"uint256"},{name:"expectedOwner",type:"bytes"},{name:"actualOwner",type:"bytes"}],name:"WrongOwnerAtIndex",type:"error"},{anonymous:!1,inputs:[{indexed:!0,name:"index",type:"uint256"},{indexed:!1,name:"owner",type:"bytes"}],name:"AddOwner",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"index",type:"uint256"},{indexed:!1,name:"owner",type:"bytes"}],name:"RemoveOwner",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{stateMutability:"payable",type:"fallback"},{inputs:[],name:"REPLAYABLE_NONCE_KEY",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"addOwnerAddress",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],name:"addOwnerPublicKey",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"functionSelector",type:"bytes4"}],name:"canSkipChainIdValidation",outputs:[{name:"",type:"bool"}],stateMutability:"pure",type:"function"},{inputs:[],name:"domainSeparator",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"entryPoint",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],name:"execute",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{components:[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"executeBatch",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{name:"calls",type:"bytes[]"}],name:"executeWithoutChainIdValidation",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{components:[{name:"sender",type:"address"},{name:"nonce",type:"uint256"},{name:"initCode",type:"bytes"},{name:"callData",type:"bytes"},{name:"callGasLimit",type:"uint256"},{name:"verificationGasLimit",type:"uint256"},{name:"preVerificationGas",type:"uint256"},{name:"maxFeePerGas",type:"uint256"},{name:"maxPriorityFeePerGas",type:"uint256"},{name:"paymasterAndData",type:"bytes"},{name:"signature",type:"bytes"}],name:"userOp",type:"tuple"}],name:"getUserOpHashWithoutChainId",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"implementation",outputs:[{name:"$",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"owners",type:"bytes[]"}],name:"initialize",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{name:"account",type:"address"}],name:"isOwnerAddress",outputs:[{name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{name:"account",type:"bytes"}],name:"isOwnerBytes",outputs:[{name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],name:"isOwnerPublicKey",outputs:[{name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],name:"isValidSignature",outputs:[{name:"result",type:"bytes4"}],stateMutability:"view",type:"function"},{inputs:[],name:"nextOwnerIndex",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"index",type:"uint256"}],name:"ownerAtIndex",outputs:[{name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"ownerCount",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{name:"index",type:"uint256"},{name:"owner",type:"bytes"}],name:"removeLastOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"index",type:"uint256"},{name:"owner",type:"bytes"}],name:"removeOwnerAtIndex",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"removedOwnersCount",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"hash",type:"bytes32"}],name:"replaySafeHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{name:"newImplementation",type:"address"},{name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{components:[{name:"sender",type:"address"},{name:"nonce",type:"uint256"},{name:"initCode",type:"bytes"},{name:"callData",type:"bytes"},{name:"callGasLimit",type:"uint256"},{name:"verificationGasLimit",type:"uint256"},{name:"preVerificationGas",type:"uint256"},{name:"maxFeePerGas",type:"uint256"},{name:"maxPriorityFeePerGas",type:"uint256"},{name:"paymasterAndData",type:"bytes"},{name:"signature",type:"bytes"}],name:"userOp",type:"tuple"},{name:"userOpHash",type:"bytes32"},{name:"missingAccountFunds",type:"uint256"}],name:"validateUserOp",outputs:[{name:"validationData",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{stateMutability:"payable",type:"receive"}],Mi=[{inputs:[{name:"implementation_",type:"address"}],stateMutability:"payable",type:"constructor"},{inputs:[],name:"OwnerRequired",type:"error"},{inputs:[{name:"owners",type:"bytes[]"},{name:"nonce",type:"uint256"}],name:"createAccount",outputs:[{name:"account",type:"address"}],stateMutability:"payable",type:"function"},{inputs:[{name:"owners",type:"bytes[]"},{name:"nonce",type:"uint256"}],name:"getAddress",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"implementation",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"initCodeHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}];function Ra(e){var t;if(!Array.isArray(e.params))return null;switch(e.method){case"personal_sign":return e.params[1];case"eth_signTypedData_v4":return e.params[0];case"eth_signTransaction":case"eth_sendTransaction":case"wallet_sendCalls":return(t=e.params[0])===null||t===void 0?void 0:t.from;default:return null}}function jp(e,t){if(!Array.isArray(e.params))throw _.rpc.invalidParams();const n=[...e.params];switch(e.method){case"eth_signTransaction":case"eth_sendTransaction":case"wallet_sendCalls":n[0].from=t;break;case"eth_signTypedData_v4":n[0]=t;break;case"personal_sign":n[1]=t;break}return Object.assign(Object.assign({},e),{params:n})}function ja(e){var t;if(!e||!Array.isArray(e)||!(!((t=e[0])===null||t===void 0)&&t.chainId)||typeof e[0].chainId!="string"&&typeof e[0].chainId!="number")throw _.rpc.invalidParams()}function Mp(e){if(!e||!Array.isArray(e)||e.length!==1&&e.length!==2||typeof e[0]!="string"||!ct(e[0]))throw _.rpc.invalidParams();if(e.length===2){if(!Array.isArray(e[1]))throw _.rpc.invalidParams();for(const t of e[1])if(typeof t!="string"||!t.startsWith("0x"))throw _.rpc.invalidParams()}}function ln(e,t){const n=Object.assign({},e);if(t&&e.method.startsWith("wallet_")){let r=Et(n,"params.0.capabilities");if(typeof r>"u"&&(r={}),typeof r!="object")throw _.rpc.invalidParams();r=Object.assign(Object.assign({},t),r),n.params&&Array.isArray(n.params)&&(n.params[0]=Object.assign(Object.assign({},n.params[0]),{capabilities:r}))}return n}async function Pn(){var e;const t=(e=T.subAccountsConfig.get())!==null&&e!==void 0?e:{},n={};if(t.enableAutoSubAccounts){const{account:r}=t.toOwnerAccount?await t.toOwnerAccount():await gr();if(!r)throw _.provider.unauthorized("No owner account found");n.addSubAccount={account:{type:"create",keys:[{type:r.address?"address":"webauthn-p256",publicKey:r.address||r.publicKey}]}}}T.subAccountsConfig.set({capabilities:n})}function Dp(e){if(!(e.method==="coinbase_fetchPermissions"&&e.params===void 0)){if(e.method==="coinbase_fetchPermissions"&&Array.isArray(e.params)&&e.params.length===1&&typeof e.params[0]=="object"){if(typeof e.params[0].account!="string"||!e.params[0].chainId.startsWith("0x"))throw _.rpc.invalidParams("FetchPermissions - Invalid params: params[0].account must be a hex string");if(typeof e.params[0].chainId!="string"||!e.params[0].chainId.startsWith("0x"))throw _.rpc.invalidParams("FetchPermissions - Invalid params: params[0].chainId must be a hex string");if(typeof e.params[0].spender!="string"||!e.params[0].spender.startsWith("0x"))throw _.rpc.invalidParams("FetchPermissions - Invalid params: params[0].spender must be a hex string");return}throw _.rpc.invalidParams()}}function Up(e){var t,n,r;if(e.params!==void 0)return e;const a=(t=T.getState().account.accounts)===null||t===void 0?void 0:t[0],s=(n=T.getState().account.chain)===null||n===void 0?void 0:n.id,i=(r=T.getState().subAccount)===null||r===void 0?void 0:r.address;if(!a||!i||!s)throw _.rpc.invalidParams("FetchPermissions - one or more of account, sub account, or chain id is missing, connect to sub account via wallet_connect first");return{method:"coinbase_fetchPermissions",params:[{account:a,chainId:M(s),spender:i}]}}function Fp({spendPermission:e,chainId:t}){return{domain:{name:"Spend Permission Manager",version:"1",chainId:t,verifyingContract:ji},types:{SpendPermission:[{name:"account",type:"address"},{name:"spender",type:"address"},{name:"token",type:"address"},{name:"allowance",type:"uint160"},{name:"period",type:"uint48"},{name:"start",type:"uint48"},{name:"end",type:"uint48"},{name:"salt",type:"uint256"},{name:"extraData",type:"bytes"}]},primaryType:"SpendPermission",message:{account:e.account,spender:e.spender,token:e.token,allowance:e.allowance,period:e.period,start:e.start,end:e.end,salt:e.salt,extraData:e.extraData}}}function $p({spendPermissionBatch:e,chainId:t}){return{domain:{name:"Spend Permission Manager",version:"1",chainId:t,verifyingContract:ji},types:{SpendPermissionBatch:[{name:"account",type:"address"},{name:"period",type:"uint48"},{name:"start",type:"uint48"},{name:"end",type:"uint48"},{name:"permissions",type:"PermissionDetails[]"}],PermissionDetails:[{name:"spender",type:"address"},{name:"token",type:"address"},{name:"allowance",type:"uint160"},{name:"salt",type:"uint256"},{name:"extraData",type:"bytes"}]},primaryType:"SpendPermissionBatch",message:{account:e.account,period:e.period,start:e.start,end:e.end,permissions:e.permissions.map(n=>({spender:n.spender,token:n.token,allowance:n.allowance,salt:n.salt,extraData:n.extraData}))}}}async function Di({client:e,id:t}){var n;const r=await Ds(e,{id:t});if(r.status==="success")return(n=r.receipts)===null||n===void 0?void 0:n[0].transactionHash;throw _.rpc.internal("failed to send transaction")}function Ui({calls:e,from:t,chainId:n,capabilities:r}){const a=li.get().paymasterUrls;let s={method:"wallet_sendCalls",params:[{version:"1.0",calls:e,chainId:M(n),from:t,atomicRequired:!0,capabilities:r}]};return a?.[n]&&(s=ln(s,{paymasterService:{url:a?.[n]}})),s}async function Gp(){const e=qr();return await new Promise(n=>{zr({snackbarContext:"sub_account_insufficient_balance"}),e.presentItem({autoExpand:!0,message:"Insufficient spend permission. Choose how to proceed:",menuItems:[{isRed:!1,info:"Create new Spend Permission",svgWidth:"10",svgHeight:"11",path:"",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:()=>{st({snackbarContext:"sub_account_insufficient_balance",snackbarAction:"create_permission"}),e.clear(),n("update_permission")}},{isRed:!1,info:"Continue in Popup",svgWidth:"10",svgHeight:"11",path:"",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:()=>{st({snackbarContext:"sub_account_insufficient_balance",snackbarAction:"continue_in_popup"}),e.clear(),n("continue_popup")}},{isRed:!0,info:"Cancel",svgWidth:"10",svgHeight:"11",path:"",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:()=>{st({snackbarContext:"sub_account_insufficient_balance",snackbarAction:"cancel"}),e.clear(),n("cancel")}}]})})}function Hp({errorData:e,sourceAddress:t}){var n;const r=[];for(const[a,{amount:s,sources:i}]of Object.entries((n=e?.required)!==null&&n!==void 0?n:{})){if(i.filter(c=>he(c.balance)>=he(s)&&c.address.toLowerCase()===t?.toLowerCase()).length===0)throw new Error("Source address has insufficient balance for a token");r.push({token:a,requiredAmount:he(s)})}return r}function zp(e){return typeof e=="object"&&e!==null&&"calls"in e}function qp(e){return Array.isArray(e)&&e.length===1&&typeof e[0]=="object"&&e[0]!==null&&"to"in e[0]}function Wp(e){return nu(ce(Te(e)),0,16)}function Vp({attribution:e,dappOrigin:t}){if(e){if("auto"in e&&e.auto&&t)return Wp(t);if("dataSuffix"in e)return e.dataSuffix}}function Kp(e,t){var n;if(!Array.isArray(e?.params))return!1;const r=(n=e.params[0])===null||n===void 0?void 0:n.capabilities;return!r||typeof r!="object"?!1:t in r}function zt(e,t){const n=e.filter(r=>r!==t);return[t,...n]}function qt(e,t){return[...e.filter(r=>r!==t),t]}async function Jp(){const e=T.spendPermissions.get(),t=T.subAccounts.get(),n=T.account.get().accounts;return n?{accounts:n?.map(a=>({address:a,capabilities:{subAccounts:t?[t]:void 0,spendPermissions:e.length>0?{permissions:e}:void 0}}))}:null}function Zp(e){return e.replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function Wt(e){const t=btoa(String.fromCharCode(...new Uint8Array(e)));return Zp(t)}function Yp({webauthn:e,signature:t,id:n}){const r=ai(t);return{id:n,rawId:Wt(Ve(n)),response:{authenticatorData:Wt(Qt(e.authenticatorData)),clientDataJSON:Wt(Ve(e.clientDataJSON)),signature:Wt(Qp(r.r,r.s))},type:JSON.parse(e.clientDataJSON).type}}function Qp(e,t){const n=Qt(Yt(M(e))),r=Qt(Yt(M(t))),a=n.length,s=r.length,i=a+s+4,o=new Uint8Array(i+2);return o[0]=48,o[1]=i,o[2]=2,o[3]=a,o.set(n,4),o[a+4]=2,o[a+5]=s,o.set(r,a+6),o}var Xp=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(e);a({to:d.target,value:d.value,data:d.data}));throw new D(`unable to decode calls for "${u.functionName}"`)},async encodeCalls(c){var u,d;return c.length===1?oe({abi:be,functionName:"execute",args:[c[0].to,(u=c[0].value)!==null&&u!==void 0?u:BigInt(0),(d=c[0].data)!==null&&d!==void 0?d:"0x"]}):oe({abi:be,functionName:"executeBatch",args:[c.map(l=>{var p,f;return{data:(p=l.data)!==null&&p!==void 0?p:"0x",target:l.to,value:(f=l.value)!==null&&f!==void 0?f:BigInt(0)}})]})},async getAddress(){return r},async getFactoryArgs(){return s?{factory:o.address,factoryData:s}:{factory:o.address,factoryData:s}},async getStubSignature(){return t.type==="webAuthn"?"0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000170000000000000000000000000000000000000000000000000000000000000001949fc7c88032b9fcb5f6efc7a7b8c63668eae9871b765e23123bb473ff57aa831a7c0d9276168ebcc29f2875a0239cffdf2a9cd1c2007c5c77c071db9264df1d000000000000000000000000000000000000000000000000000000000000002549960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d97630500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008a7b2274797065223a22776562617574686e2e676574222c226368616c6c656e6765223a2273496a396e6164474850596759334b7156384f7a4a666c726275504b474f716d59576f4d57516869467773222c226f726967696e223a2268747470733a2f2f7369676e2e636f696e626173652e636f6d222c2263726f73734f726967696e223a66616c73657d00000000000000000000000000000000000000000000":vt({ownerIndex:n,signature:"0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c"})},async sign(c){const u=await this.getAddress(),d=On({address:u,chainId:a.chain.id,hash:c.hash}),l=await Vt({hash:d,owner:t});return vt({ownerIndex:n,signature:l})},async signMessage(c){const{message:u}=c,d=await this.getAddress(),l=On({address:d,chainId:a.chain.id,hash:Pr(u)}),p=await Vt({hash:l,owner:t});return vt({ownerIndex:n,signature:p})},async signTypedData(c){const{domain:u,types:d,primaryType:l,message:p}=c,f=await this.getAddress(),y=On({address:f,chainId:a.chain.id,hash:Lt({domain:u,message:p,primaryType:l,types:d})}),g=await Vt({hash:y,owner:t});return vt({ownerIndex:n,signature:g})},async signUserOperation(c){const{chainId:u=a.chain.id}=c,d=Xp(c,["chainId"]),l=await this.getAddress(),p=xd({chainId:u,entryPointAddress:i.address,entryPointVersion:i.version,userOperation:Object.assign(Object.assign({},d),{sender:l})}),f=await Vt({hash:p,owner:t});return vt({ownerIndex:n,signature:f})},userOperation:{async estimateGas(c){var u;if(t.type==="webAuthn")return{verificationGasLimit:BigInt(Math.max(Number((u=c.verificationGasLimit)!==null&&u!==void 0?u:BigInt(0)),8e5))}}}})}async function Vt({hash:e,owner:t}){if(t.type==="webAuthn"){const{signature:n,webauthn:r}=await t.sign({hash:e});return tm({signature:n,webauthn:r})}if(t.sign)return t.sign({hash:e});throw new D("`owner` does not support raw sign.")}function On({address:e,chainId:t,hash:n}){return Lt({domain:{chainId:t,name:"Coinbase Smart Wallet",verifyingContract:e,version:"1"},types:{CoinbaseSmartWalletMessage:[{name:"hash",type:"bytes32"}]},primaryType:"CoinbaseSmartWalletMessage",message:{hash:n}})}function tm({webauthn:e,signature:t}){const{r:n,s:r}=ai(t);return Ke([{components:[{name:"authenticatorData",type:"bytes"},{name:"clientDataJSON",type:"bytes"},{name:"challengeIndex",type:"uint256"},{name:"typeIndex",type:"uint256"},{name:"r",type:"uint256"},{name:"s",type:"uint256"}],type:"tuple"}],[{authenticatorData:e.authenticatorData,clientDataJSON:is(e.clientDataJSON),challengeIndex:BigInt(e.challengeIndex),typeIndex:BigInt(e.typeIndex),r:n,s:r}])}function vt(e){const{ownerIndex:t=0}=e,n=(()=>{if(ru(e.signature)!==65)return e.signature;const r=yd(e.signature);return Bu(["bytes32","bytes32","uint8"],[r.r,r.s,r.yParity===0?27:28])})();return Ke([{components:[{name:"ownerIndex",type:"uint8"},{name:"signatureData",type:"bytes"}],type:"tuple"}],[{ownerIndex:t,signatureData:n}])}async function nm({address:e,client:t,factory:n,factoryData:r,owner:a,ownerIndex:s,parentAddress:i,attribution:o}){var c;const u={address:e,factory:n,factoryData:r},d=(c=t.chain)===null||c===void 0?void 0:c.id;if(!d)throw _.rpc.internal("chainId not found");const l=await em({owner:a,ownerIndex:s??1,address:e,client:t,factoryData:r}),p=async f=>{var y,g,h,w,E,b;try{switch(f.method){case"wallet_addSubAccount":return u;case"eth_accounts":return[u.address];case"eth_coinbase":return u.address;case"net_version":return d.toString();case"eth_chainId":return M(d);case"eth_sendTransaction":{Re(f.params);const A=f.params[0];le(A.to,_.rpc.invalidParams("to is required"));const I={to:A.to,data:hr((y=A.data)!==null&&y!==void 0?y:"0x",!0),value:hr((g=A.value)!==null&&g!==void 0?g:"0x",!0),from:(h=A.from)!==null&&h!==void 0?h:u.address},N=Ui({calls:[I],chainId:d,from:I.from}),B=await p(N);return Di({client:t,id:B})}case"wallet_sendCalls":{Re(f.params);const A=Et(f.params[0],"chainId");if(!A)throw _.rpc.invalidParams("chainId is required");if(!Ge(A))throw _.rpc.invalidParams("chainId must be a hex encoded integer");if(!f.params[0])throw _.rpc.invalidParams("params are required");if(!("calls"in f.params[0]))throw _.rpc.invalidParams("calls are required");let I={method:"wallet_prepareCalls",params:[{version:"1.0",calls:f.params[0].calls,chainId:A,from:u.address,capabilities:"capabilities"in f.params[0]?f.params[0].capabilities:{}}]};i&&(I=ln(I,{funding:[{type:"spendPermission",data:{autoApply:!0,sources:[i],preference:"PREFER_DIRECT_BALANCE"}}]}));let N=await p(I);const B=await((E=(w=a).sign)===null||E===void 0?void 0:E.call(w,{hash:oa(N.signatureRequest.hash)}));let j;if(!B)throw _.rpc.internal("signature not found");return Ge(B)?j={type:"secp256k1",data:{address:a.address,signature:B}}:j={type:"webauthn",data:{signature:JSON.stringify(Yp(Object.assign({id:(b=a.id)!==null&&b!==void 0?b:"1"},B))),publicKey:a.publicKey}},(await p({method:"wallet_sendPreparedCalls",params:[{version:"1.0",type:N.type,data:N.userOp,chainId:N.chainId,signature:j}]}))[0]}case"wallet_sendPreparedCalls":{Re(f.params);const A=Et(f.params[0],"chainId");if(!A)throw _.rpc.invalidParams("chainId is required");if(!Ge(A))throw _.rpc.invalidParams("chainId must be a hex encoded integer");return await t.request({method:"wallet_sendPreparedCalls",params:f.params})}case"wallet_prepareCalls":{Re(f.params);const A=Et(f.params[0],"chainId");if(!A)throw _.rpc.invalidParams("chainId is required");if(!Ge(A))throw _.rpc.invalidParams("chainId must be a hex encoded integer");if(!f.params[0])throw _.rpc.invalidParams("params are required");if(!Et(f.params[0],"calls"))throw _.rpc.invalidParams("calls are required");const I=f.params[0];return o&&I.capabilities&&!("attribution"in I.capabilities)&&(I.capabilities.attribution=o),await t.request({method:"wallet_prepareCalls",params:[Object.assign(Object.assign({},f.params[0]),{chainId:A})]})}case"personal_sign":{if(Re(f.params),!Ge(f.params[0]))throw _.rpc.invalidParams("message must be a hex encoded string");const A=oa(f.params[0]);return l.signMessage({message:A})}case"eth_signTypedData_v4":{Re(f.params);const A=typeof f.params[1]=="string"?JSON.parse(f.params[1]):f.params[1];return l.signTypedData(A)}case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"wallet_addEthereumChain":case"wallet_switchEthereumChain":default:throw _.rpc.methodNotSupported()}}catch(A){if(yi(A)){const I=yf(A);if(I)throw I}throw A}};return{request:p}}async function Fi({address:e,client:t,publicKey:n,factory:r,factoryData:a}){if(!await Xt(t,{address:e})&&r&&a){if(ca(r)!==ca(Ri))throw _.rpc.internal("unknown factory address");const o=Ss({abi:Mi,data:a});if(o.functionName!=="createAccount")throw _.rpc.internal("unknown factory function");const[c]=o.args;return c.findIndex(u=>u.toLowerCase()===Ma(n).toLowerCase())}const i=await Se(t,{address:e,abi:be,functionName:"ownerCount"});for(let o=Number(i)-1;o>=0;o--){const c=await Se(t,{address:e,abi:be,functionName:"ownerAtIndex",args:[BigInt(o)]}),u=Ma(n);if(c.toLowerCase()===u.toLowerCase())return o}return-1}function Ma(e){return ct(e)?de(e):e}async function rm(){const e=qr();return new Promise(t=>{zr({snackbarContext:"sub_account_add_owner"}),e.presentItem({autoExpand:!0,message:"App requires a signer update",menuItems:[{isRed:!1,info:"Confirm",svgWidth:"10",svgHeight:"11",path:"",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:()=>{st({snackbarContext:"sub_account_add_owner",snackbarAction:"confirm"}),e.clear(),t("authenticate")}},{isRed:!0,info:"Cancel",svgWidth:"10",svgHeight:"11",path:"",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:()=>{st({snackbarContext:"sub_account_add_owner",snackbarAction:"cancel"}),e.clear(),t("cancel")}}]})})}async function am({ownerAccount:e,globalAccountRequest:t}){var n,r;const a=T.account.get(),s=T.subAccounts.get(),i=(n=a.accounts)===null||n===void 0?void 0:n.find(y=>y.toLowerCase()!==s?.address.toLowerCase());le(i,_.provider.unauthorized("no global account")),le((r=a.chain)===null||r===void 0?void 0:r.id,_.provider.unauthorized("no chain id")),le(s?.address,_.provider.unauthorized("no sub account"));const o=[];if(e.type==="local"&&e.address&&o.push({to:s.address,data:oe({abi:be,functionName:"addOwnerAddress",args:[e.address]}),value:Te(0)}),e.publicKey){const[y,g]=As([{type:"bytes32"},{type:"bytes32"}],e.publicKey);o.push({to:s.address,data:oe({abi:be,functionName:"addOwnerPublicKey",args:[y,g]}),value:Te(0)})}const c={method:"wallet_sendCalls",params:[{version:"1",calls:o,chainId:M(84532),from:i}]};if(await rm()==="cancel")throw _.provider.unauthorized("user cancelled");const d=await t(c),l=Ti(a.chain.id);if(le(l,_.rpc.internal(`client not found for chainId ${a.chain.id}`)),(await Ds(l,{id:d})).status!=="success")throw _.rpc.internal("add owner call failed");const f=await Fi({address:s.address,publicKey:e.type==="local"&&e.address?e.address:e.publicKey,client:l});if(f===-1)throw _.rpc.internal("failed to find owner index");return f}async function sm({errorData:e,globalAccountAddress:t,subAccountAddress:n,client:r,request:a,subAccountRequest:s,globalAccountRequest:i}){var o;const c=(o=r.chain)===null||o===void 0?void 0:o.id;le(c,_.rpc.internal("invalid chainId"));const u=Hp({errorData:e,sourceAddress:t}),d=await Gp();if(d==="cancel")throw new Error("User cancelled funding");let l;const p=60*60*24,f=3;if(d==="update_permission"){if(u.length===1){const b=u[0],A=Fp({spendPermission:{token:b.token,allowance:M(b.requiredAmount*BigInt(f)),period:p,account:t,spender:n,start:0,end:0xffffffffffff,salt:M(BigInt(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER))),extraData:"0x"},chainId:c});l={method:"eth_signTypedData_v4",params:[t,A]}}else{const b=$p({spendPermissionBatch:{account:t,period:p,start:0,end:0xffffffffffff,permissions:u.map(A=>({token:A.token,allowance:M(A.requiredAmount*BigInt(f)),period:p,account:t,spender:n,salt:"0x0",extraData:"0x"}))},chainId:c});l={method:"eth_signTypedData_v4",params:[t,b]}}try{await i(l)}catch(b){throw console.error(b),new Error("User denied spend permission request")}return s(a)}const y=u.map(b=>b.token.toLowerCase()==="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE".toLowerCase()?{to:n,value:M(b.requiredAmount),data:"0x"}:{to:b.token,value:"0x0",data:oe({abi:au,functionName:"transfer",args:[n,b.requiredAmount]})});let g;if(a.method==="wallet_sendCalls"&&zp(a.params))g=a.params[0];else if(a.method==="eth_sendTransaction"&&qp(a.params))g=Ui({calls:[a.params[0]],chainId:c,from:a.params[0].from}).params[0];else throw new Error("Could not get original call");const h=oe({abi:be,functionName:"executeBatch",args:[g.calls.map(b=>{var A,I;return{target:b.to,value:he((A=b.value)!==null&&A!==void 0?A:"0x0"),data:(I=b.data)!==null&&I!==void 0?I:"0x"}})]}),w=[...y,{data:h,to:n,value:"0x0"}],E=await i({method:"wallet_sendCalls",params:[Object.assign(Object.assign({},g),{calls:w,from:t})]});return a.method==="eth_sendTransaction"?Di({client:r,id:E}):E}class $i{constructor(t){var n,r,a,s;this.communicator=t.communicator,this.callback=t.callback,this.keyManager=new Rp;const{account:i,chains:o}=T.getState();this.accounts=(n=i.accounts)!==null&&n!==void 0?n:[],this.chain=(r=i.chain)!==null&&r!==void 0?r:{id:(s=(a=t.metadata.appChainIds)===null||a===void 0?void 0:a[0])!==null&&s!==void 0?s:1},o&&Ta(o)}async handshake(t){var n,r,a;const s=ge.get(t);op({method:t.method,correlationId:s});try{await((r=(n=this.communicator).waitForPopupLoaded)===null||r===void 0?void 0:r.call(n));const i=await this.createRequestMessage({handshake:{method:t.method,params:(a=t.params)!==null&&a!==void 0?a:[]}},s),o=await this.communicator.postRequestAndWaitForResponse(i);if("failure"in o.content)throw o.content.failure;const c=await Li("public",o.sender);await this.keyManager.setPeerPublicKey(c);const u=await this.decryptResponseMessage(o);this.handleResponse(t,u),up({method:t.method,correlationId:s})}catch(i){throw cp({method:t.method,correlationId:s,errorMessage:ze(i)}),i}}async request(t){const n=ge.get(t);dp({method:t.method,correlationId:n});try{const r=await this._request(t);return fp({method:t.method,correlationId:n}),r}catch(r){throw lp({method:t.method,correlationId:n,errorMessage:ze(r)}),r}}async _request(t){var n,r,a,s,i,o,c,u,d,l,p,f,y,g;if(this.accounts.length===0)switch(t.method){case"eth_requestAccounts":return await((r=(n=this.communicator).waitForPopupLoaded)===null||r===void 0?void 0:r.call(n)),await Pn(),await this.request({method:"wallet_connect",params:[{version:"1",capabilities:Object.assign({},(s=(a=T.subAccountsConfig.get())===null||a===void 0?void 0:a.capabilities)!==null&&s!==void 0?s:{})}]}),this.accounts;case"wallet_switchEthereumChain":{ja(t.params),this.chain.id=Number(t.params[0].chainId);return}case"wallet_connect":{await((o=(i=this.communicator).waitForPopupLoaded)===null||o===void 0?void 0:o.call(i)),await Pn();let h={};Kp(t,"addSubAccount")&&(h=(u=(c=T.subAccountsConfig.get())===null||c===void 0?void 0:c.capabilities)!==null&&u!==void 0?u:{});const w=ln(t,h);return this.sendRequestToPopup(w)}case"wallet_sendCalls":case"wallet_sign":return this.sendRequestToPopup(t);default:throw _.provider.unauthorized()}if(this.shouldRequestUseSubAccountSigner(t)){const h=ge.get(t);pp({method:t.method,correlationId:h});try{const w=await this.sendRequestToSubAccountSigner(t);return mp({method:t.method,correlationId:h}),w}catch(w){throw hp({method:t.method,correlationId:h,errorMessage:ze(w)}),w}}switch(t.method){case"eth_requestAccounts":case"eth_accounts":{const h=T.subAccounts.get(),w=T.subAccountsConfig.get();return h?.address&&(this.accounts=w?.enableAutoSubAccounts?zt(this.accounts,h.address):qt(this.accounts,h.address)),(d=this.callback)===null||d===void 0||d.call(this,"connect",{chainId:M(this.chain.id)}),this.accounts}case"eth_coinbase":return this.accounts[0];case"net_version":return this.chain.id;case"eth_chainId":return M(this.chain.id);case"wallet_getCapabilities":return this.handleGetCapabilitiesRequest(t);case"wallet_switchEthereumChain":return this.handleSwitchChainRequest(t);case"eth_ecRecover":case"personal_sign":case"wallet_sign":case"personal_ecRecover":case"eth_signTransaction":case"eth_sendTransaction":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":case"eth_signTypedData":case"wallet_addEthereumChain":case"wallet_watchAsset":case"wallet_sendCalls":case"wallet_showCallsStatus":case"wallet_grantPermissions":return this.sendRequestToPopup(t);case"wallet_connect":{const h=await Jp();if(h)return h;await((p=(l=this.communicator).waitForPopupLoaded)===null||p===void 0?void 0:p.call(l)),await Pn();const w=T.subAccountsConfig.get(),E=ln(t,(f=w?.capabilities)!==null&&f!==void 0?f:{});return(y=this.callback)===null||y===void 0||y.call(this,"connect",{chainId:M(this.chain.id)}),this.sendRequestToPopup(E)}case"wallet_getSubAccounts":{const h=T.subAccounts.get();if(h?.address)return{subAccounts:[h]};if(!this.chain.rpcUrl)throw _.rpc.internal("No RPC URL set for chain");const w=await Pt(t,this.chain.rpcUrl);if(Re(w.subAccounts,"subAccounts"),w.subAccounts.length>0){Ht(w.subAccounts[0]);const E=w.subAccounts[0];T.subAccounts.set({address:E.address,factory:E.factory,factoryData:E.factoryData})}return w}case"wallet_addSubAccount":return this.addSubAccount(t);case"coinbase_fetchPermissions":{Dp(t);const h=Up(t),w=await Pt(h,xi),E=Je((g=h.params)===null||g===void 0?void 0:g[0].chainId);return T.spendPermissions.set(w.permissions.map(b=>Object.assign(Object.assign({},b),{chainId:E}))),w}default:if(!this.chain.rpcUrl)throw _.rpc.internal("No RPC URL set for chain");return Pt(t,this.chain.rpcUrl)}}async sendRequestToPopup(t){var n,r;await((r=(n=this.communicator).waitForPopupLoaded)===null||r===void 0?void 0:r.call(n));const a=await this.sendEncryptedRequest(t),s=await this.decryptResponseMessage(a);return this.handleResponse(t,s)}async handleResponse(t,n){var r,a,s,i,o;const c=n.result;if("error"in c)throw c.error;switch(t.method){case"eth_requestAccounts":{const u=c.value;this.accounts=u,T.account.set({accounts:u,chain:this.chain}),(r=this.callback)===null||r===void 0||r.call(this,"accountsChanged",u);break}case"wallet_connect":{const u=c.value,d=u.accounts.map(w=>w.address);this.accounts=d,T.account.set({accounts:d});const l=u.accounts.at(0),p=l?.capabilities;if(p?.subAccounts){const w=p?.subAccounts;Re(w,"subAccounts"),Ht(w[0]),T.subAccounts.set({address:w[0].address,factory:w[0].factory,factoryData:w[0].factoryData})}let f=[this.accounts[0]];const y=T.subAccounts.get(),g=T.subAccountsConfig.get();y?.address&&(this.accounts=g?.enableAutoSubAccounts?zt(this.accounts,y.address):qt(this.accounts,y.address));const h=(s=(a=u?.accounts)===null||a===void 0?void 0:a[0].capabilities)===null||s===void 0?void 0:s.spendPermissions;h&&"permissions"in h&&T.spendPermissions.set(h?.permissions),(i=this.callback)===null||i===void 0||i.call(this,"accountsChanged",f);break}case"wallet_addSubAccount":{Ht(c.value);const u=c.value;T.subAccounts.set(u);const d=T.subAccountsConfig.get();this.accounts=d?.enableAutoSubAccounts?zt(this.accounts,u.address):qt(this.accounts,u.address),(o=this.callback)===null||o===void 0||o.call(this,"accountsChanged",this.accounts);break}}return c.value}async cleanup(){var t,n;const r=T.config.get().metadata;await this.keyManager.clear(),T.account.clear(),T.subAccounts.clear(),T.spendPermissions.clear(),T.chains.clear(),this.accounts=[],this.chain={id:(n=(t=r?.appChainIds)===null||t===void 0?void 0:t[0])!==null&&n!==void 0?n:1}}async handleSwitchChainRequest(t){ja(t.params);const n=It(t.params[0].chainId);if(this.updateChain(n))return null;const a=await this.sendRequestToPopup(t);return a===null&&this.updateChain(n),a}async handleGetCapabilitiesRequest(t){Mp(t.params);const n=t.params[0],r=t.params[1];if(!this.accounts.some(o=>Ir(o,n)))throw _.provider.unauthorized("no active account found when getting capabilities");const a=T.getState().account.capabilities;if(!a)return{};if(!r||r.length===0)return a;const s=new Set(r.map(o=>Je(o)));return Object.fromEntries(Object.entries(a).filter(([o])=>{try{const c=Je(o);return s.has(c)}catch{return!1}}))}async sendEncryptedRequest(t){const n=await this.keyManager.getSharedSecret();if(!n)throw _.provider.unauthorized("No shared secret found when encrypting request");const r=await _p({action:t,chainId:this.chain.id},n),a=ge.get(t),s=await this.createRequestMessage({encrypted:r},a);return this.communicator.postRequestAndWaitForResponse(s)}async createRequestMessage(t,n){const r=await Bi("public",await this.keyManager.getOwnPublicKey());return{id:crypto.randomUUID(),correlationId:n,sender:r,content:t,timestamp:new Date}}async decryptResponseMessage(t){var n,r,a;const s=t.content;if("failure"in s)throw s.failure;const i=await this.keyManager.getSharedSecret();if(!i)throw _.provider.unauthorized("Invalid session: no shared secret found when decrypting response");const o=await Ip(s.encrypted,i),c=(n=o.data)===null||n===void 0?void 0:n.chains;if(c){const d=(r=o.data)===null||r===void 0?void 0:r.nativeCurrencies,l=Object.entries(c).map(([p,f])=>{const y=d?.[Number(p)];return Object.assign({id:Number(p),rpcUrl:f},y?{nativeCurrency:y}:{})});T.chains.set(l),this.updateChain(this.chain.id,l),Ta(l)}const u=(a=o.data)===null||a===void 0?void 0:a.capabilities;return u&&T.account.set({capabilities:u}),o}updateChain(t,n){var r;const a=T.getState(),s=n??a.chains,i=s?.find(o=>o.id===t);return i?(i!==this.chain&&(this.chain=i,T.account.set({chain:i}),(r=this.callback)===null||r===void 0||r.call(this,"chainChanged",at(i.id))),!0):!1}async addSubAccount(t){var n,r,a,s;const o=T.getState().subAccount,c=T.subAccountsConfig.get();if(o?.address)return this.accounts=c?.enableAutoSubAccounts?zt(this.accounts,o.address):qt(this.accounts,o.address),(n=this.callback)===null||n===void 0||n.call(this,"accountsChanged",this.accounts),o;if(await((a=(r=this.communicator).waitForPopupLoaded)===null||a===void 0?void 0:a.call(r)),Array.isArray(t.params)&&t.params.length>0&&t.params[0].account&&t.params[0].account.type==="create"){let d;if(t.params[0].account.keys&&t.params[0].account.keys.length>0)d=t.params[0].account.keys;else{const l=(s=T.subAccountsConfig.get())!==null&&s!==void 0?s:{},{account:p}=l.toOwnerAccount?await l.toOwnerAccount():await gr();if(!p)throw _.provider.unauthorized("could not get subaccount owner account when adding sub account");d=[{type:p.address?"address":"webauthn-p256",publicKey:p.address||p.publicKey}]}t.params[0].account.keys=d}const u=await this.sendRequestToPopup(t);return Ht(u),u}shouldRequestUseSubAccountSigner(t){const n=Ra(t),r=T.subAccounts.get();return n?n.toLowerCase()===r?.address.toLowerCase():!1}async sendRequestToSubAccountSigner(t){var n;const r=T.subAccounts.get(),a=T.subAccountsConfig.get(),s=T.config.get();le(r?.address,_.provider.unauthorized("no active sub account when sending request to sub account signer"));const i=a?.toOwnerAccount?await a.toOwnerAccount():await gr();le(i?.account,_.provider.unauthorized("no active sub account owner when sending request to sub account signer")),Ra(t)===void 0&&(t=jp(t,r.address));const c=Ti(this.chain.id);le(c,_.rpc.internal(`client not found for chainId ${this.chain.id} when sending request to sub account signer`));const u=this.accounts.find(y=>y.toLowerCase()!==r.address.toLowerCase());le(u,_.provider.unauthorized("no global account found when sending request to sub account signer"));const d=Vp({attribution:(n=s.preference)===null||n===void 0?void 0:n.attribution,dappOrigin:window.location.origin}),l=i.account.type==="local"?i.account.address:i.account.publicKey;let p=await Fi({address:r.address,factory:r.factory,factoryData:r.factoryData,publicKey:l,client:c});if(p===-1){const y=ge.get(t);yp({method:t.method,correlationId:y});try{p=await am({ownerAccount:i.account,globalAccountRequest:this.sendRequestToPopup.bind(this)}),gp({method:t.method,correlationId:y})}catch(g){return bp({method:t.method,correlationId:y,errorMessage:ze(g)}),_.provider.unauthorized("failed to add sub account owner when sending request to sub account signer")}}const{request:f}=await nm({address:r.address,owner:i.account,client:c,factory:r.factory,factoryData:r.factoryData,parentAddress:u,attribution:d?{suffix:d}:void 0,ownerIndex:p});try{return await f(t)}catch(y){let g;if(yi(y))g=JSON.parse(y.details);else if(_a(y))g=y;else throw y;if(!(_a(g)&&g.data)||!g.data)throw y;const h=ge.get(t);wp({method:t.method,correlationId:h});try{const w=await sm({errorData:g.data,globalAccountAddress:u,subAccountAddress:r.address,client:c,request:t,subAccountRequest:f,globalAccountRequest:this.request.bind(this)});return vp({method:t.method,correlationId:h}),w}catch(w){throw console.error(w),kp({method:t.method,correlationId:h,errorMessage:ze(w)}),y}}}}const im=({method:e,correlationId:t})=>{V("walletlink_signer.handshake.started",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t},z.high)},om=({method:e,correlationId:t,errorMessage:n})=>{V("walletlink_signer.handshake.error",{action:H.error,componentType:G.unknown,method:e,correlationId:t,errorMessage:n},z.high)},cm=({method:e,correlationId:t})=>{V("walletlink_signer.handshake.completed",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t},z.high)},um=({method:e,correlationId:t})=>{V("walletlink_signer.request.started",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t},z.high)},dm=({method:e,correlationId:t,errorMessage:n})=>{V("walletlink_signer.request.error",{action:H.error,componentType:G.unknown,method:e,correlationId:t,errorMessage:n},z.high)},lm=({method:e,correlationId:t})=>{V("walletlink_signer.request.completed",{action:H.unknown,componentType:G.unknown,method:e,correlationId:t},z.high)},Da=()=>{V("walletlink_signer.walletlink_connection.connection_failed",{action:H.measurement,componentType:G.unknown},z.high)},fm=()=>{V("walletlink_signer.walletlink_connection.fetch_unseen_events_failed",{action:H.measurement,componentType:G.unknown},z.high)};var Z={},re={};Object.defineProperty(re,"__esModule",{value:!0});re.output=re.exists=re.hash=re.bytes=re.bool=re.number=re.isBytes=void 0;function fn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}re.number=fn;function Gi(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}re.bool=Gi;function Hi(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}re.isBytes=Hi;function Vr(e,...t){if(!Hi(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}re.bytes=Vr;function zi(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");fn(e.outputLen),fn(e.blockLen)}re.hash=zi;function qi(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}re.exists=qi;function Wi(e,t){Vr(e);const n=t.outputLen;if(e.length>br&Kt)}:{h:Number(e>>br&Kt)|0,l:Number(e&Kt)|0}}U.fromBig=Kr;function Vi(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let a=0;aBigInt(e>>>0)<>>0);U.toBig=Ki;const Ji=(e,t,n)=>e>>>n;U.shrSH=Ji;const Zi=(e,t,n)=>e<<32-n|t>>>n;U.shrSL=Zi;const Yi=(e,t,n)=>e>>>n|t<<32-n;U.rotrSH=Yi;const Qi=(e,t,n)=>e<<32-n|t>>>n;U.rotrSL=Qi;const Xi=(e,t,n)=>e<<64-n|t>>>n-32;U.rotrBH=Xi;const eo=(e,t,n)=>e>>>n-32|t<<64-n;U.rotrBL=eo;const to=(e,t)=>t;U.rotr32H=to;const no=(e,t)=>e;U.rotr32L=no;const ro=(e,t,n)=>e<>>32-n;U.rotlSH=ro;const ao=(e,t,n)=>t<>>32-n;U.rotlSL=ao;const so=(e,t,n)=>t<>>64-n;U.rotlBH=so;const io=(e,t,n)=>e<>>64-n;U.rotlBL=io;function oo(e,t,n,r){const a=(t>>>0)+(r>>>0);return{h:e+n+(a/2**32|0)|0,l:a|0}}U.add=oo;const co=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);U.add3L=co;const uo=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;U.add3H=uo;const lo=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);U.add4L=lo;const fo=(e,t,n,r,a)=>t+n+r+a+(e/2**32|0)|0;U.add4H=fo;const po=(e,t,n,r,a)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(a>>>0);U.add5L=po;const mo=(e,t,n,r,a,s)=>t+n+r+a+s+(e/2**32|0)|0;U.add5H=mo;const mm={fromBig:Kr,split:Vi,toBig:Ki,shrSH:Ji,shrSL:Zi,rotrSH:Yi,rotrSL:Qi,rotrBH:Xi,rotrBL:eo,rotr32H:to,rotr32L:no,rotlSH:ro,rotlSL:ao,rotlBH:so,rotlBL:io,add:oo,add3L:co,add3H:uo,add4L:lo,add4H:fo,add5H:mo,add5L:po};U.default=mm;var ho={},xn={};Object.defineProperty(xn,"__esModule",{value:!0});xn.crypto=void 0;xn.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(e){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(e,"__esModule",{value:!0}),e.randomBytes=e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.checkOpts=e.Hash=e.concatBytes=e.toBytes=e.utf8ToBytes=e.asyncLoop=e.nextTick=e.hexToBytes=e.bytesToHex=e.byteSwap32=e.byteSwapIfBE=e.byteSwap=e.isLE=e.rotl=e.rotr=e.createView=e.u32=e.u8=e.isBytes=void 0;const t=xn,n=re;function r(m){return m instanceof Uint8Array||m!=null&&typeof m=="object"&&m.constructor.name==="Uint8Array"}e.isBytes=r;const a=m=>new Uint8Array(m.buffer,m.byteOffset,m.byteLength);e.u8=a;const s=m=>new Uint32Array(m.buffer,m.byteOffset,Math.floor(m.byteLength/4));e.u32=s;const i=m=>new DataView(m.buffer,m.byteOffset,m.byteLength);e.createView=i;const o=(m,k)=>m<<32-k|m>>>k;e.rotr=o;const c=(m,k)=>m<>>32-k>>>0;e.rotl=c,e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;const u=m=>m<<24&4278190080|m<<8&16711680|m>>>8&65280|m>>>24&255;e.byteSwap=u,e.byteSwapIfBE=e.isLE?m=>m:m=>(0,e.byteSwap)(m);function d(m){for(let k=0;kk.toString(16).padStart(2,"0"));function p(m){(0,n.bytes)(m);let k="";for(let C=0;C=f._0&&m<=f._9)return m-f._0;if(m>=f._A&&m<=f._F)return m-(f._A-10);if(m>=f._a&&m<=f._f)return m-(f._a-10)}function g(m){if(typeof m!="string")throw new Error("hex string expected, got "+typeof m);const k=m.length,C=k/2;if(k%2)throw new Error("padded hex string expected, got unpadded hex of length "+k);const O=new Uint8Array(C);for(let L=0,R=0;L{};e.nextTick=h;async function w(m,k,C){let O=Date.now();for(let L=0;L=0&&Rm().update(b(O)).digest(),C=m();return k.outputLen=C.outputLen,k.blockLen=C.blockLen,k.create=()=>m(),k}e.wrapConstructor=j;function v(m){const k=(O,L)=>m(L).update(b(O)).digest(),C=m({});return k.outputLen=C.outputLen,k.blockLen=C.blockLen,k.create=O=>m(O),k}e.wrapConstructorWithOpts=v;function P(m){const k=(O,L)=>m(L).update(b(O)).digest(),C=m({});return k.outputLen=C.outputLen,k.blockLen=C.blockLen,k.create=O=>m(O),k}e.wrapXOFConstructorWithOpts=P;function x(m=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(m));throw new Error("crypto.getRandomValues must be defined")}e.randomBytes=x})(ho);Object.defineProperty(Z,"__esModule",{value:!0});Z.shake256=Z.shake128=Z.keccak_512=Z.keccak_384=Z.keccak_256=Z.keccak_224=Z.sha3_512=Z.sha3_384=Z.sha3_256=Z.sha3_224=Z.Keccak=Z.keccakP=void 0;const tt=re,Nt=U,Ie=ho,yo=[],go=[],bo=[],hm=BigInt(0),kt=BigInt(1),ym=BigInt(2),gm=BigInt(7),bm=BigInt(256),wm=BigInt(113);for(let e=0,t=kt,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],yo.push(2*(5*r+n)),go.push((e+1)*(e+2)/2%64);let a=hm;for(let s=0;s<7;s++)t=(t<>gm)*wm)%bm,t&ym&&(a^=kt<<(kt<n>32?(0,Nt.rotlBH)(e,t,n):(0,Nt.rotlSH)(e,t,n),Fa=(e,t,n)=>n>32?(0,Nt.rotlBL)(e,t,n):(0,Nt.rotlSL)(e,t,n);function wo(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)n[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){const o=(i+8)%10,c=(i+2)%10,u=n[c],d=n[c+1],l=Ua(u,d,1)^n[o],p=Fa(u,d,1)^n[o+1];for(let f=0;f<50;f+=10)e[i+f]^=l,e[i+f+1]^=p}let a=e[2],s=e[3];for(let i=0;i<24;i++){const o=go[i],c=Ua(a,s,o),u=Fa(a,s,o),d=yo[i];a=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let o=0;o<10;o++)n[o]=e[i+o];for(let o=0;o<10;o++)e[i+o]^=~n[(o+2)%10]&n[(o+4)%10]}e[0]^=vm[r],e[1]^=km[r]}n.fill(0)}Z.keccakP=wo;class jt extends Ie.Hash{constructor(t,n,r,a=!1,s=24){if(super(),this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=a,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,tt.number)(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,Ie.u32)(this.state)}keccak(){Ie.isLE||(0,Ie.byteSwap32)(this.state32),wo(this.state32,this.rounds),Ie.isLE||(0,Ie.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(t){(0,tt.exists)(this);const{blockLen:n,state:r}=this;t=(0,Ie.toBytes)(t);const a=t.length;for(let s=0;s=r&&this.keccak();const i=Math.min(r-this.posOut,s-a);t.set(n.subarray(this.posOut,this.posOut+i),a),this.posOut+=i,a+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return(0,tt.number)(t),this.xofInto(new Uint8Array(t))}digestInto(t){if((0,tt.output)(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){const{blockLen:n,suffix:r,outputLen:a,rounds:s,enableXOF:i}=this;return t||(t=new jt(n,r,a,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=r,t.outputLen=a,t.enableXOF=i,t.destroyed=this.destroyed,t}}Z.Keccak=jt;const Fe=(e,t,n)=>(0,Ie.wrapConstructor)(()=>new jt(t,e,n));Z.sha3_224=Fe(6,144,224/8);Z.sha3_256=Fe(6,136,256/8);Z.sha3_384=Fe(6,104,384/8);Z.sha3_512=Fe(6,72,512/8);Z.keccak_224=Fe(1,144,224/8);Z.keccak_256=Fe(1,136,256/8);Z.keccak_384=Fe(1,104,384/8);Z.keccak_512=Fe(1,72,512/8);const vo=(e,t,n)=>(0,Ie.wrapXOFConstructorWithOpts)((r={})=>new jt(t,e,r.dkLen===void 0?n:r.dkLen,!0));Z.shake128=vo(31,168,128/8);Z.shake256=vo(31,136,256/8);const{keccak_256:xm}=Z;function ko(e){return Buffer.allocUnsafe(e).fill(0)}function Em(e){return`0x${e.toString(16)}`}function Sm(e){const t=Em(e);return new Buffer(So(t.slice(2)),"hex")}function Am(e){return e.toString(2).length}function xo(e,t){let n=e.toString(16);n.length%2!==0&&(n="0"+n);const r=n.match(/.{1,2}/g).map(a=>parseInt(a,16));for(;r.length"u")throw new Error("Not an array?");if(n=Oo(e),n!=="dynamic"&&n!==0&&t.length>n)throw new Error("Elements exceed array size: "+n);a=[],e=e.slice(0,e.lastIndexOf("[")),typeof t=="string"&&(t=JSON.parse(t));for(s in t)a.push(xe(e,t[s]));if(n==="dynamic"){var i=xe("uint256",t.length);a.unshift(i)}return Buffer.concat(a)}else{if(e==="bytes")return t=new Buffer(t),a=Buffer.concat([xe("uint256",t.length),t]),t.length%32!==0&&(a=Buffer.concat([a,ie.zeros(32-t.length%32)])),a;if(e.startsWith("bytes")){if(n=it(e),n<1||n>32)throw new Error("Invalid bytes width: "+n);return ie.setLengthRight(t,32)}else if(e.startsWith("uint")){if(n=it(e),n%8||n<8||n>256)throw new Error("Invalid uint width: "+n);r=qe(t);const o=ie.bitLengthFromBigInt(r);if(o>n)throw new Error("Supplied uint exceeds width: "+n+" vs "+o);if(r<0)throw new Error("Supplied uint is negative");return ie.bufferBEFromBigInt(r,32)}else if(e.startsWith("int")){if(n=it(e),n%8||n<8||n>256)throw new Error("Invalid int width: "+n);r=qe(t);const o=ie.bitLengthFromBigInt(r);if(o>n)throw new Error("Supplied int exceeds width: "+n+" vs "+o);const c=ie.twosFromBigInt(r,256);return ie.bufferBEFromBigInt(c,32)}else if(e.startsWith("ufixed")){if(n=$a(e),r=qe(t),r<0)throw new Error("Supplied ufixed is negative");return xe("uint256",r*BigInt(2)**BigInt(n[1]))}else if(e.startsWith("fixed"))return n=$a(e),xe("int256",qe(t)*BigInt(2)**BigInt(n[1]))}throw new Error("Unsupported or invalid type: "+e)}function Cm(e){return e==="string"||e==="bytes"||Oo(e)==="dynamic"}function Tm(e){return e.lastIndexOf("]")===e.length-1}function Nm(e,t){var n=[],r=[],a=32*e.length;for(var s in e){var i=Po(e[s]),o=t[s],c=xe(i,o);Cm(i)?(n.push(xe("uint256",a)),r.push(c),a+=c.length):n.push(c)}return Buffer.concat(n.concat(r))}function Co(e,t){if(e.length!==t.length)throw new Error("Number of types are not matching the values");for(var n,r,a=[],s=0;s32)throw new Error("Invalid bytes width: "+n);a.push(ie.setLengthRight(o,n))}else if(i.startsWith("uint")){if(n=it(i),n%8||n<8||n>256)throw new Error("Invalid uint width: "+n);r=qe(o);const c=ie.bitLengthFromBigInt(r);if(c>n)throw new Error("Supplied uint exceeds width: "+n+" vs "+c);a.push(ie.bufferBEFromBigInt(r,n/8))}else if(i.startsWith("int")){if(n=it(i),n%8||n<8||n>256)throw new Error("Invalid int width: "+n);r=qe(o);const c=ie.bitLengthFromBigInt(r);if(c>n)throw new Error("Supplied int exceeds width: "+n+" vs "+c);const u=ie.twosFromBigInt(r,n);a.push(ie.bufferBEFromBigInt(u,n/8))}else throw new Error("Unsupported or invalid type: "+i)}return Buffer.concat(a)}function Bm(e,t){return ie.keccak(Co(e,t))}var Lm={rawEncode:Nm,solidityPack:Co,soliditySHA3:Bm};const ye=Io,Ct=Lm,To={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},Cn={encodeData(e,t,n,r=!0){const a=["bytes32"],s=[this.hashType(e,n)];if(r){const i=(o,c,u)=>{if(n[c]!==void 0)return["bytes32",u==null?"0x0000000000000000000000000000000000000000000000000000000000000000":ye.keccak(this.encodeData(c,u,n,r))];if(u===void 0)throw new Error(`missing value for field ${o} of type ${c}`);if(c==="bytes")return["bytes32",ye.keccak(u)];if(c==="string")return typeof u=="string"&&(u=Buffer.from(u,"utf8")),["bytes32",ye.keccak(u)];if(c.lastIndexOf("]")===c.length-1){const d=c.slice(0,c.lastIndexOf("[")),l=u.map(p=>i(o,d,p));return["bytes32",ye.keccak(Ct.rawEncode(l.map(([p])=>p),l.map(([,p])=>p)))]}return[c,u]};for(const o of n[e]){const[c,u]=i(o.name,o.type,t[o.name]);a.push(c),s.push(u)}}else for(const i of n[e]){let o=t[i.name];if(o!==void 0)if(i.type==="bytes")a.push("bytes32"),o=ye.keccak(o),s.push(o);else if(i.type==="string")a.push("bytes32"),typeof o=="string"&&(o=Buffer.from(o,"utf8")),o=ye.keccak(o),s.push(o);else if(n[i.type]!==void 0)a.push("bytes32"),o=ye.keccak(this.encodeData(i.type,o,n,r)),s.push(o);else{if(i.type.lastIndexOf("]")===i.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");a.push(i.type),s.push(o)}}return Ct.rawEncode(a,s)},encodeType(e,t){let n="",r=this.findTypeDependencies(e,t).filter(a=>a!==e);r=[e].concat(r.sort());for(const a of r){if(!t[a])throw new Error("No type definition specified: "+a);n+=a+"("+t[a].map(({name:i,type:o})=>o+" "+i).join(",")+")"}return n},findTypeDependencies(e,t,n=[]){if(e=e.match(/^\w*/)[0],n.includes(e)||t[e]===void 0)return n;n.push(e);for(const r of t[e])for(const a of this.findTypeDependencies(r.type,t,n))!n.includes(a)&&n.push(a);return n},hashStruct(e,t,n,r=!0){return ye.keccak(this.encodeData(e,t,n,r))},hashType(e,t){return ye.keccak(this.encodeType(e,t))},sanitizeData(e){const t={};for(const n in To.properties)e[n]&&(t[n]=e[n]);return t.types&&(t.types=Object.assign({EIP712Domain:[]},t.types)),t},hash(e,t=!0){const n=this.sanitizeData(e),r=[Buffer.from("1901","hex")];return r.push(this.hashStruct("EIP712Domain",n.domain,n.types,t)),n.primaryType!=="EIP712Domain"&&r.push(this.hashStruct(n.primaryType,n.message,n.types,t)),ye.keccak(Buffer.concat(r))}};var Rm={TYPED_MESSAGE_SCHEMA:To,TypedDataUtils:Cn,hashForSignTypedDataLegacy:function(e){return jm(e.data)},hashForSignTypedData_v3:function(e){return Cn.hash(e.data,!1)},hashForSignTypedData_v4:function(e){return Cn.hash(e.data)}};function jm(e){const t=new Error("Expect argument to be non-empty array");if(typeof e!="object"||!e.length)throw t;const n=e.map(function(s){return s.type==="bytes"?ye.toBuffer(s.value):s.value}),r=e.map(function(s){return s.type}),a=e.map(function(s){if(!s.name)throw t;return s.type+" "+s.name});return Ct.soliditySHA3(["bytes32","bytes32"],[Ct.soliditySHA3(new Array(e.length).fill("string"),a),Ct.soliditySHA3(r,n)])}const Jt=Es(Rm),Mm="walletUsername",wr="Addresses",Dm="AppVersion";class Um{constructor(t){this.secret=t}async encrypt(t){const n=this.secret;if(n.length!==64)throw new Error("secret must be 256 bits");const r=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.importKey("raw",Zt(n),{name:"aes-gcm"},!1,["encrypt","decrypt"]),s=new TextEncoder,i=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},a,s.encode(t)),o=16,c=i.slice(i.byteLength-o),u=i.slice(0,i.byteLength-o),d=new Uint8Array(c),l=new Uint8Array(u),p=new Uint8Array([...r,...d,...l]);return $r(p)}async decrypt(t){const n=this.secret;if(n.length!==64)throw new Error("secret must be 256 bits");return new Promise((r,a)=>{(async()=>{const s=await crypto.subtle.importKey("raw",Zt(n),{name:"aes-gcm"},!1,["encrypt","decrypt"]),i=Zt(t),o=i.slice(0,12),c=i.slice(12,28),u=i.slice(28),d=new Uint8Array([...u,...c]),l={name:"AES-GCM",iv:new Uint8Array(o)};try{const p=await window.crypto.subtle.decrypt(l,s,d),f=new TextDecoder;r(f.decode(p))}catch(p){a(p)}})()})}}class Fm{constructor(t,n,r){this.linkAPIUrl=t,this.sessionId=n;const a=`${n}:${r}`;this.auth=`Basic ${btoa(a)}`}async markUnseenEventsAsSeen(t){return Promise.all(t.map(n=>fetch(`${this.linkAPIUrl}/events/${n.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(n=>console.error("Unable to mark events as seen:",n))}async fetchUnseenEvents(){var t;const n=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(n.ok){const{events:r,error:a}=await n.json();if(a)throw new Error(`Check unseen events failed: ${a}`);const s=(t=r?.filter(i=>i.event==="Web3Response").map(i=>({type:"Event",sessionId:this.sessionId,eventId:i.id,event:i.event,data:i.data})))!==null&&t!==void 0?t:[];return this.markUnseenEventsAsSeen(s),s}throw new Error(`Check unseen events failed: ${n.status}`)}}var Ee;(function(e){e[e.DISCONNECTED=0]="DISCONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED"})(Ee||(Ee={}));class ue{setConnectionStateListener(t){this.connectionStateListener=t}setIncomingDataListener(t){this.incomingDataListener=t}constructor(t,n=WebSocket){this.WebSocketClass=n,this.webSocket=null,this.isDisconnecting=!1,this.url=t.replace(/^http/,"ws"),this.instanceId=ue.instanceCounter++,ue.activeInstances.add(this.instanceId)}async connect(){if(this.webSocket)throw new Error("webSocket object is not null");if(this.isDisconnecting)throw new Error("WebSocket is disconnecting, cannot reconnect on same instance");return new Promise((t,n)=>{var r;let a;try{this.webSocket=a=new this.WebSocketClass(this.url)}catch(s){n(s);return}(r=this.connectionStateListener)===null||r===void 0||r.call(this,Ee.CONNECTING),a.onclose=s=>{var i;this.clearWebSocket(),a.readyState!==WebSocket.OPEN&&n(new Error(`websocket error ${s.code}: ${s.reason}`)),(i=this.connectionStateListener)===null||i===void 0||i.call(this,Ee.DISCONNECTED)},a.onopen=s=>{var i;t(),(i=this.connectionStateListener)===null||i===void 0||i.call(this,Ee.CONNECTED),ue.pendingData.length>0&&([...ue.pendingData].forEach(c=>this.sendData(c)),ue.pendingData=[])},a.onmessage=s=>{var i,o;if(s.data==="h")(i=this.incomingDataListener)===null||i===void 0||i.call(this,{type:"Heartbeat"});else try{const c=JSON.parse(s.data);(o=this.incomingDataListener)===null||o===void 0||o.call(this,c)}catch{}}})}disconnect(){var t;const{webSocket:n}=this;if(n){this.isDisconnecting=!0,this.clearWebSocket(),(t=this.connectionStateListener)===null||t===void 0||t.call(this,Ee.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{n.close()}catch{}}}sendData(t){const{webSocket:n}=this;if(!n){ue.pendingData.push(t),this.isDisconnecting||this.connect();return}if(n.readyState!==WebSocket.OPEN){ue.pendingData.push(t);return}n.send(t)}clearWebSocket(){const{webSocket:t}=this;t&&(this.webSocket=null,t.onclose=null,t.onerror=null,t.onmessage=null,t.onopen=null)}cleanup(){ue.activeInstances.delete(this.instanceId)}}ue.instanceCounter=0;ue.activeInstances=new Set;ue.pendingData=[];const Ga=1e4,$m=6e4;class Gm{constructor({session:t,linkAPIUrl:n,listener:r}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=Oe(1),this.reconnectAttempts=0,this.isReconnecting=!1,this._connected=!1,this._linked=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=s=>{if(!s)return;new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",o=>s.JsonRpcUrl&&this.handleChainUpdated(o,s.JsonRpcUrl)]]).forEach((o,c)=>{const u=s[c];u!==void 0&&o(u)})},this.handleDestroyed=s=>{var i;s==="1"&&((i=this.listener)===null||i===void 0||i.resetAndReload())},this.handleAccountUpdated=async s=>{var i;try{const o=await this.cipher.decrypt(s);(i=this.listener)===null||i===void 0||i.accountUpdated(o)}catch{}},this.handleMetadataUpdated=async(s,i)=>{var o;try{const c=await this.cipher.decrypt(i);(o=this.listener)===null||o===void 0||o.metadataUpdated(s,c)}catch{}},this.handleWalletUsernameUpdated=async s=>{this.handleMetadataUpdated(Mm,s)},this.handleAppVersionUpdated=async s=>{this.handleMetadataUpdated(Dm,s)},this.handleChainUpdated=async(s,i)=>{var o;try{const c=await this.cipher.decrypt(s),u=await this.cipher.decrypt(i);(o=this.listener)===null||o===void 0||o.chainUpdated(c,u)}catch{}},this.session=t,this.cipher=new Um(t.secret),this.listener=r,this.linkAPIUrl=n,this.WebSocketClass=WebSocket;const a=this.createWebSocket();this.ws=a,this.http=new Fm(n,t.id,t.key),this.setupVisibilityChangeHandler()}createWebSocket(){const t=new ue(`${this.linkAPIUrl}/rpc`,this.WebSocketClass);return this.activeWsInstance=t,t.setConnectionStateListener(async n=>{if(t!==this.activeWsInstance)return;let r=!1;switch(n){case Ee.DISCONNECTED:this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=void 0),this.lastHeartbeatResponse=0,r=!1,this.destroyed||(async()=>{if(this.isReconnecting)return;this.isReconnecting=!0;const s=this.reconnectAttempts===0?0:3e3;await new Promise(i=>setTimeout(i,s)),!this.destroyed&&t===this.activeWsInstance?(this.reconnectAttempts++,"cleanup"in this.ws&&typeof this.ws.cleanup=="function"&&this.ws.cleanup(),this.ws=this.createWebSocket(),this.ws.connect().catch(()=>{Da()}).finally(()=>{this.isReconnecting=!1})):this.isReconnecting=!1})();break;case Ee.CONNECTED:this.reconnectAttempts=0;try{r=await this.handleConnected(),this.fetchUnseenEventsAPI().catch(()=>{})}catch{break}this.connected=r,this.updateLastHeartbeat(),this.heartbeatIntervalId&&clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=window.setInterval(()=>{this.heartbeat()},Ga),setTimeout(()=>{this.heartbeat()},100);break;case Ee.CONNECTING:break}n!==Ee.CONNECTED&&(this.connected=r)}),t.setIncomingDataListener(n=>{var r;switch(n.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{const a=n.type==="IsLinkedOK"?n.linked:void 0;this.linked=a||n.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":{this.handleSessionMetadataUpdated(n.metadata);break}case"Event":{this.handleIncomingEvent(n);break}}n.id!==void 0&&((r=this.requestResolutions.get(n.id))===null||r===void 0||r(n))}),t}setupVisibilityChangeHandler(){this.visibilityChangeHandler=()=>{!document.hidden&&!this.destroyed&&(this.connected?this.heartbeat():this.reconnectWithFreshWebSocket())},this.focusHandler=()=>{!this.destroyed&&!this.connected&&this.reconnectWithFreshWebSocket()},document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.addEventListener("focus",this.focusHandler),window.addEventListener("pageshow",t=>{t.persisted&&this.focusHandler&&this.focusHandler()})}reconnectWithFreshWebSocket(){if(this.destroyed)return;const t=this.ws;this.activeWsInstance=void 0,t.disconnect(),"cleanup"in t&&typeof t.cleanup=="function"&&t.cleanup(),this.ws=this.createWebSocket(),this.ws.connect().catch(()=>{Da()})}connect(){if(this.destroyed)throw new Error("instance is destroyed");this.ws.connect()}async destroy(){this.destroyed||(await this.makeRequest({type:"SetSessionConfig",id:Oe(this.nextReqId++),sessionId:this.session.id,metadata:{__destroyed:"1"}},{timeout:1e3}),this.destroyed=!0,this.activeWsInstance=void 0,this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=void 0),this.visibilityChangeHandler&&document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.focusHandler&&window.removeEventListener("focus",this.focusHandler),this.ws.disconnect(),"cleanup"in this.ws&&typeof this.ws.cleanup=="function"&&this.ws.cleanup(),this.listener=void 0)}get connected(){return this._connected}set connected(t){this._connected=t}get linked(){return this._linked}set linked(t){var n,r;this._linked=t,t&&((n=this.onceLinked)===null||n===void 0||n.call(this)),(r=this.listener)===null||r===void 0||r.linkedUpdated(t)}setOnceLinked(t){return new Promise(n=>{this.linked?t().then(n):this.onceLinked=()=>{t().then(n),this.onceLinked=void 0}})}async handleIncomingEvent(t){var n;if(!(t.type!=="Event"||t.event!=="Web3Response"))try{const r=await this.cipher.decrypt(t.data),a=JSON.parse(r);if(a.type!=="WEB3_RESPONSE")return;(n=this.listener)===null||n===void 0||n.handleWeb3ResponseMessage(a.id,a.response)}catch{}}async checkUnseenEvents(){await new Promise(t=>setTimeout(t,250));try{await this.fetchUnseenEventsAPI()}catch(t){console.error("Unable to check for unseen events",t)}}async fetchUnseenEventsAPI(){try{(await this.http.fetchUnseenEvents()).forEach(n=>{this.handleIncomingEvent(n)})}catch{fm()}}async publishEvent(t,n,r=!1){const a=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},n),{origin:location.origin,location:location.href,relaySource:"coinbaseWalletExtension"in window&&window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),s={type:"PublishEvent",id:Oe(this.nextReqId++),sessionId:this.session.id,event:t,data:a,callWebhook:r};return this.setOnceLinked(async()=>{const i=await this.makeRequest(s);if(i.type==="Fail")throw new Error(i.error||"failed to publish event");return i.eventId})}sendData(t){this.ws.sendData(JSON.stringify(t))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>Ga*2){this.ws.disconnect();return}if(this.connected)try{this.ws.sendData("h")}catch{}}async makeRequest(t,n={timeout:$m}){const r=t.id;this.sendData(t);let a;return Promise.race([new Promise((s,i)=>{a=window.setTimeout(()=>{i(new Error(`request ${r} timed out`))},n.timeout)}),new Promise(s=>{this.requestResolutions.set(r,i=>{clearTimeout(a),s(i),this.requestResolutions.delete(r)})})])}async handleConnected(){return(await this.makeRequest({type:"HostSession",id:Oe(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key})).type==="Fail"?!1:(this.sendData({type:"IsLinked",id:Oe(this.nextReqId++),sessionId:this.session.id}),this.sendData({type:"GetSessionConfig",id:Oe(this.nextReqId++),sessionId:this.session.id}),!0)}}class Hm{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%2147483647;const t=this._nextRequestId,n=ki(t.toString(16));return this.callbacks.get(n)&&this.callbacks.delete(n),t}}function zm(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function Jr(e,...t){if(!zm(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Ha(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function qm(e,t){Jr(e);const n=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),ke=(e,t)=>e<<32-t|e>>>t;new Uint8Array(new Uint32Array([287454020]).buffer)[0];const Wm=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Vm(e){Jr(e);let t="";for(let n=0;ne().update(No(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Ym(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const a=BigInt(32),s=BigInt(4294967295),i=Number(n>>a&s),o=Number(n&s),c=r?4:0,u=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+u,o,r)}const Qm=(e,t,n)=>e&t^~e&n,Xm=(e,t,n)=>e&t^e&n^t&n;class eh extends Jm{constructor(t,n,r,a){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=a,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Tn(this.buffer)}update(t){Ha(this);const{view:n,buffer:r,blockLen:a}=this;t=No(t);const s=t.length;for(let i=0;ia-i&&(this.process(r,0),i=0);for(let l=i;ld.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l>>3,g=ke(f,17)^ke(f,19)^f>>>10;Le[l]=g+Le[l-7]+y+Le[l-16]|0}let{A:r,B:a,C:s,D:i,E:o,F:c,G:u,H:d}=this;for(let l=0;l<64;l++){const p=ke(o,6)^ke(o,11)^ke(o,25),f=d+p+Qm(o,c,u)+th[l]+Le[l]|0,g=(ke(r,2)^ke(r,13)^ke(r,22))+Xm(r,a,s)|0;d=u,u=c,c=o,o=i+f|0,i=s,s=a,a=r,r=f+g|0}r=r+this.A|0,a=a+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(r,a,s,i,o,c,u,d)}roundClean(){Le.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const rh=Zm(()=>new nh),za="session:id",qa="session:secret",Wa="session:linked";class ot{constructor(t,n,r,a=!1){this.storage=t,this.id=n,this.secret=r,this.key=Vm(rh(`${n}, ${r} WalletLink`)),this._linked=!!a}static create(t){const n=He(16),r=He(32);return new ot(t,n,r).save()}static load(t){const n=t.getItem(za),r=t.getItem(Wa),a=t.getItem(qa);return n&&a?new ot(t,n,a,r==="1"):null}get linked(){return this._linked}set linked(t){this._linked=t,this.persistLinked()}save(){return this.storage.setItem(za,this.id),this.storage.setItem(qa,this.secret),this.persistLinked(),this}persistLinked(){this.storage.setItem(Wa,this._linked?"1":"0")}}const ah=".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}";class sh{constructor(){this.root=null,this.darkMode=Ai()}attach(){const t=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",t.appendChild(this.root),Ei()}present(t){this.render(t)}clear(){this.render(null)}render(t){this.root&&(Nn(null,this.root),t&&Nn(J(ih,Object.assign({},t,{onDismiss:()=>{this.clear()},darkMode:this.darkMode})),this.root))}}const ih=({title:e,buttonText:t,darkMode:n,onButtonClick:r,onDismiss:a})=>{const s=n?"dark":"light";return J(Ii,{darkMode:n},J("div",{class:"-cbwsdk-redirect-dialog"},J("style",null,ah),J("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:a}),J("div",{class:Ot("-cbwsdk-redirect-dialog-box",s)},J("p",null,e),J("button",{onClick:r},t))))};class Va{constructor(){this.attached=!1,this.redirectDialog=new sh}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}redirectToCoinbaseWallet(t){const n=new URL(Cf);n.searchParams.append("redirect_url",jf().href),t&&n.searchParams.append("wl_url",t);const r=document.createElement("a");r.target="cbw-opener",r.href=n.href,r.rel="noreferrer noopener",r.click()}openCoinbaseWalletDeeplink(t){this.redirectToCoinbaseWallet(t),setTimeout(()=>{this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",onButtonClick:()=>{this.redirectToCoinbaseWallet(t)}})},99)}showConnecting(t){return()=>{this.redirectDialog.clear()}}}class Ce{constructor(t){this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.isMobileWeb=Mf(),this.linkedUpdated=s=>{this.isLinked=s;const i=this.storage.getItem(wr);if(s&&(this._session.linked=s),this.isUnlinkedErrorState=!1,i){const o=i.split(" "),c=this.storage.getItem("IsStandaloneSigning")==="true";o[0]!==""&&!s&&this._session.linked&&!c&&(this.isUnlinkedErrorState=!0)}},this.metadataUpdated=(s,i)=>{this.storage.setItem(s,i)},this.chainUpdated=(s,i)=>{this.chainCallbackParams.chainId===s&&this.chainCallbackParams.jsonRpcUrl===i||(this.chainCallbackParams={chainId:s,jsonRpcUrl:i},this.chainCallback&&this.chainCallback(i,Number.parseInt(s,10)))},this.accountUpdated=s=>{this.accountsCallback&&this.accountsCallback([s]),Ce.accountRequestCallbackIds.size>0&&(Array.from(Ce.accountRequestCallbackIds.values()).forEach(i=>{this.invokeCallback(i,{method:"requestEthereumAccounts",result:[s]})}),Ce.accountRequestCallbackIds.clear())},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=t.linkAPIUrl,this.storage=t.storage,this.metadata=t.metadata,this.accountsCallback=t.accountsCallback,this.chainCallback=t.chainCallback;const{session:n,ui:r,connection:a}=this.subscribe();this._session=n,this.connection=a,this.relayEventManager=new Hm,this.ui=r,this.ui.attach()}subscribe(){const t=ot.load(this.storage)||ot.create(this.storage),{linkAPIUrl:n}=this,r=new Gm({session:t,linkAPIUrl:n,listener:this}),a=this.isMobileWeb?new Va:new Gf;return r.connect(),{session:t,ui:a,connection:r}}resetAndReload(){this.connection.destroy().then(()=>{const t=ot.load(this.storage);t?.id===this._session.id&&Ze.clearAll(),document.location.reload()}).catch(t=>{})}signEthereumTransaction(t){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:t.fromAddress,toAddress:t.toAddress,weiValue:ve(t.weiValue),data:_t(t.data,!0),nonce:t.nonce,gasPriceInWei:t.gasPriceInWei?ve(t.gasPriceInWei):null,maxFeePerGas:t.gasPriceInWei?ve(t.gasPriceInWei):null,maxPriorityFeePerGas:t.gasPriceInWei?ve(t.gasPriceInWei):null,gasLimit:t.gasLimit?ve(t.gasLimit):null,chainId:t.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(t){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:t.fromAddress,toAddress:t.toAddress,weiValue:ve(t.weiValue),data:_t(t.data,!0),nonce:t.nonce,gasPriceInWei:t.gasPriceInWei?ve(t.gasPriceInWei):null,maxFeePerGas:t.maxFeePerGas?ve(t.maxFeePerGas):null,maxPriorityFeePerGas:t.maxPriorityFeePerGas?ve(t.maxPriorityFeePerGas):null,gasLimit:t.gasLimit?ve(t.gasLimit):null,chainId:t.chainId,shouldSubmit:!0}})}submitEthereumTransaction(t,n){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:_t(t,!0),chainId:n}})}getWalletLinkSession(){return this._session}sendRequest(t){let n=null;const r=He(8),a=s=>{this.publishWeb3RequestCanceledEvent(r),this.handleErrorResponse(r,t.method,s),n?.()};return new Promise((s,i)=>{n=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:a,onResetConnection:this.resetAndReload}),this.relayEventManager.callbacks.set(r,o=>{if(n?.(),ae(o))return i(new Error(o.errorMessage));s(o)}),this.publishWeb3RequestEvent(r,t)})}publishWeb3RequestEvent(t,n){const r={type:"WEB3_REQUEST",id:t,request:n};this.publishEvent("Web3Request",r,!0).then(a=>{}).catch(a=>{this.handleWeb3ResponseMessage(r.id,{method:n.method,errorMessage:a.message})}),this.isMobileWeb&&this.openCoinbaseWalletDeeplink(n.method)}openCoinbaseWalletDeeplink(t){if(this.ui instanceof Va)switch(t){case"requestEthereumAccounts":case"switchEthereumChain":return;default:window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0}),this.ui.openCoinbaseWalletDeeplink();break}}publishWeb3RequestCanceledEvent(t){const n={type:"WEB3_REQUEST_CANCELED",id:t};this.publishEvent("Web3RequestCanceled",n,!1).then()}publishEvent(t,n,r){return this.connection.publishEvent(t,n,r)}handleWeb3ResponseMessage(t,n){if(n.method==="requestEthereumAccounts"){Ce.accountRequestCallbackIds.forEach(r=>this.invokeCallback(r,n)),Ce.accountRequestCallbackIds.clear();return}this.invokeCallback(t,n)}handleErrorResponse(t,n,r){var a;const s=(a=r?.message)!==null&&a!==void 0?a:"Unspecified error message.";this.handleWeb3ResponseMessage(t,{method:n,errorMessage:s})}invokeCallback(t,n){const r=this.relayEventManager.callbacks.get(t);r&&(r(n),this.relayEventManager.callbacks.delete(t))}requestEthereumAccounts(){const{appName:t,appLogoUrl:n}=this.metadata,r={method:"requestEthereumAccounts",params:{appName:t,appLogoUrl:n}},a=He(8);return new Promise((s,i)=>{this.relayEventManager.callbacks.set(a,o=>{if(ae(o))return i(new Error(o.errorMessage));s(o)}),Ce.accountRequestCallbackIds.add(a),this.publishWeb3RequestEvent(a,r)})}watchAsset(t,n,r,a,s,i){const o={method:"watchAsset",params:{type:t,options:{address:n,symbol:r,decimals:a,image:s},chainId:i}};let c=null;const u=He(8),d=l=>{this.publishWeb3RequestCanceledEvent(u),this.handleErrorResponse(u,o.method,l),c?.()};return c=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:d,onResetConnection:this.resetAndReload}),new Promise((l,p)=>{this.relayEventManager.callbacks.set(u,f=>{if(c?.(),ae(f))return p(new Error(f.errorMessage));l(f)}),this.publishWeb3RequestEvent(u,o)})}addEthereumChain(t,n,r,a,s,i){const o={method:"addEthereumChain",params:{chainId:t,rpcUrls:n,blockExplorerUrls:a,chainName:s,iconUrls:r,nativeCurrency:i}};let c=null;const u=He(8),d=l=>{this.publishWeb3RequestCanceledEvent(u),this.handleErrorResponse(u,o.method,l),c?.()};return c=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:d,onResetConnection:this.resetAndReload}),new Promise((l,p)=>{this.relayEventManager.callbacks.set(u,f=>{if(c?.(),ae(f))return p(new Error(f.errorMessage));l(f)}),this.publishWeb3RequestEvent(u,o)})}switchEthereumChain(t,n){const r={method:"switchEthereumChain",params:Object.assign({chainId:t},{address:n})};let a=null;const s=He(8),i=o=>{this.publishWeb3RequestCanceledEvent(s),this.handleErrorResponse(s,r.method,o),a?.()};return a=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:i,onResetConnection:this.resetAndReload}),new Promise((o,c)=>{this.relayEventManager.callbacks.set(s,u=>{if(a?.(),ae(u)&&u.errorCode)return c(_.provider.custom({code:u.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."}));if(ae(u))return c(new Error(u.errorMessage));o(u)}),this.publishWeb3RequestEvent(s,r)})}}Ce.accountRequestCallbackIds=new Set;const Ka="DefaultChainId",Ja="DefaultJsonRpcUrl";class Bo{constructor(t){this._relay=null,this._addresses=[],this.metadata=t.metadata,this._storage=new Ze("walletlink",Pa),this.callback=t.callback||null;const n=this._storage.getItem(wr);if(n){const r=n.split(" ");r[0]!==""&&(this._addresses=r.map(a=>Ne(a)))}this.initializeRelay()}getSession(){const t=this.initializeRelay(),{id:n,secret:r}=t.getWalletLinkSession();return{id:n,secret:r}}async handshake(t){const n="eth_requestAccounts",r=ge.get(t);im({method:n,correlationId:r});try{await this._eth_requestAccounts(),cm({method:n,correlationId:r})}catch(a){throw om({method:n,correlationId:r,errorMessage:ze(a)}),a}}get selectedAddress(){return this._addresses[0]||void 0}get jsonRpcUrl(){var t;return(t=this._storage.getItem(Ja))!==null&&t!==void 0?t:void 0}set jsonRpcUrl(t){this._storage.setItem(Ja,t)}updateProviderInfo(t,n){var r;this.jsonRpcUrl=t;const a=this.getChainId();this._storage.setItem(Ka,n.toString(10)),It(n)!==a&&((r=this.callback)===null||r===void 0||r.call(this,"chainChanged",at(n)))}async watchAsset(t){const n=Array.isArray(t)?t[0]:t;if(!n.type)throw _.rpc.invalidParams("Type is required");if(n?.type!=="ERC20")throw _.rpc.invalidParams(`Asset of type '${n.type}' is not supported`);if(!n?.options)throw _.rpc.invalidParams("Options are required");if(!n?.options.address)throw _.rpc.invalidParams("Address is required");const r=this.getChainId(),{address:a,symbol:s,image:i,decimals:o}=n.options,u=await this.initializeRelay().watchAsset(n.type,a,s,o,i,r?.toString());return ae(u)?!1:!!u.result}async addEthereumChain(t){var n,r;const a=t[0];if(((n=a.rpcUrls)===null||n===void 0?void 0:n.length)===0)throw _.rpc.invalidParams("please pass in at least 1 rpcUrl");if(!a.chainName||a.chainName.trim()==="")throw _.rpc.invalidParams("chainName is a required field");if(!a.nativeCurrency)throw _.rpc.invalidParams("nativeCurrency is a required field");const s=Number.parseInt(a.chainId,16);if(s===this.getChainId())return!1;const i=this.initializeRelay(),{rpcUrls:o=[],blockExplorerUrls:c=[],chainName:u,iconUrls:d=[],nativeCurrency:l}=a,p=await i.addEthereumChain(s.toString(),o,d,c,u,l);if(ae(p))return!1;if(((r=p.result)===null||r===void 0?void 0:r.isApproved)===!0)return this.updateProviderInfo(o[0],s),null;throw _.rpc.internal("unable to add ethereum chain")}async switchEthereumChain(t){const n=t[0],r=Number.parseInt(n.chainId,16),s=await this.initializeRelay().switchEthereumChain(r.toString(10),this.selectedAddress||void 0);if(ae(s))throw s;const i=s.result;return i.isApproved&&i.rpcUrl.length>0&&this.updateProviderInfo(i.rpcUrl,r),null}async cleanup(){this.callback=null,this._relay&&this._relay.resetAndReload(),this._storage.clear()}_setAddresses(t,n){var r;if(!Array.isArray(t))throw new Error("addresses is not an array");const a=t.map(s=>Ne(s));JSON.stringify(a)!==JSON.stringify(this._addresses)&&(this._addresses=a,(r=this.callback)===null||r===void 0||r.call(this,"accountsChanged",a),this._storage.setItem(wr,a.join(" ")))}async request(t){const n=ge.get(t);um({method:t.method,correlationId:n});try{const r=await this._request(t);return lm({method:t.method,correlationId:n}),r}catch(r){throw dm({method:t.method,correlationId:n,errorMessage:ze(r)}),r}}async _request(t){const n=t.params||[];switch(t.method){case"eth_accounts":return[...this._addresses];case"eth_coinbase":return this.selectedAddress||null;case"net_version":return this.getChainId().toString(10);case"eth_chainId":return at(this.getChainId());case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_ecRecover":case"personal_ecRecover":return this.ecRecover(t);case"personal_sign":return this.personalSign(t);case"eth_signTransaction":return this._eth_signTransaction(n);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(n);case"eth_sendTransaction":return this._eth_sendTransaction(n);case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":case"eth_signTypedData":return this.signTypedData(t);case"wallet_addEthereumChain":return this.addEthereumChain(n);case"wallet_switchEthereumChain":return this.switchEthereumChain(n);case"wallet_watchAsset":return this.watchAsset(n);default:if(!this.jsonRpcUrl)throw _.rpc.internal("No RPC URL set for chain");return Pt(t,this.jsonRpcUrl)}}_ensureKnownAddress(t){const n=Ne(t);if(!this._addresses.map(a=>Ne(a)).includes(n))throw new Error("Unknown Ethereum address")}_prepareTransactionParams(t){const n=t.from?Ne(t.from):this.selectedAddress;if(!n)throw new Error("Ethereum address is unavailable");this._ensureKnownAddress(n);const r=t.to?Ne(t.to):null,a=t.value!=null?wt(t.value):BigInt(0),s=t.data?yr(t.data):Buffer.alloc(0),i=t.nonce!=null?It(t.nonce):null,o=t.gasPrice!=null?wt(t.gasPrice):null,c=t.maxFeePerGas!=null?wt(t.maxFeePerGas):null,u=t.maxPriorityFeePerGas!=null?wt(t.maxPriorityFeePerGas):null,d=t.gas!=null?wt(t.gas):null,l=t.chainId?It(t.chainId):this.getChainId();return{fromAddress:n,toAddress:r,weiValue:a,data:s,nonce:i,gasPriceInWei:o,maxFeePerGas:c,maxPriorityFeePerGas:u,gasLimit:d,chainId:l}}async ecRecover(t){const{method:n,params:r}=t;if(!Array.isArray(r))throw _.rpc.invalidParams();const s=await this.initializeRelay().sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:In(r[0]),signature:In(r[1]),addPrefix:n==="personal_ecRecover"}});if(ae(s))throw s;return s.result}getChainId(){var t;return Number.parseInt((t=this._storage.getItem(Ka))!==null&&t!==void 0?t:"1",10)}async _eth_requestAccounts(){var t,n;if(this._addresses.length>0)return(t=this.callback)===null||t===void 0||t.call(this,"connect",{chainId:at(this.getChainId())}),this._addresses;const a=await this.initializeRelay().requestEthereumAccounts();if(ae(a))throw a;if(!a.result)throw new Error("accounts received is empty");return this._setAddresses(a.result),(n=this.callback)===null||n===void 0||n.call(this,"connect",{chainId:at(this.getChainId())}),this._addresses}async personalSign({params:t}){if(!Array.isArray(t))throw _.rpc.invalidParams();const n=t[1],r=t[0];this._ensureKnownAddress(n);const s=await this.initializeRelay().sendRequest({method:"signEthereumMessage",params:{address:Ne(n),message:In(r),addPrefix:!0,typedDataJson:null}});if(ae(s))throw s;return s.result}async _eth_signTransaction(t){const n=this._prepareTransactionParams(t[0]||{}),a=await this.initializeRelay().signEthereumTransaction(n);if(ae(a))throw a;return a.result}async _eth_sendRawTransaction(t){const n=yr(t[0]),a=await this.initializeRelay().submitEthereumTransaction(n,this.getChainId());if(ae(a))throw a;return a.result}async _eth_sendTransaction(t){const n=this._prepareTransactionParams(t[0]||{}),a=await this.initializeRelay().signAndSubmitEthereumTransaction(n);if(ae(a))throw a;return a.result}async signTypedData(t){const{method:n,params:r}=t;if(!Array.isArray(r))throw _.rpc.invalidParams();const a=u=>{const d={eth_signTypedData_v1:Jt.hashForSignTypedDataLegacy,eth_signTypedData_v3:Jt.hashForSignTypedData_v3,eth_signTypedData_v4:Jt.hashForSignTypedData_v4,eth_signTypedData:Jt.hashForSignTypedData_v4};return _t(d[n]({data:bf(u)}),!0)},s=r[n==="eth_signTypedData_v1"?1:0],i=r[n==="eth_signTypedData_v1"?0:1];this._ensureKnownAddress(s);const c=await this.initializeRelay().sendRequest({method:"signEthereumMessage",params:{address:Ne(s),message:a(i),typedDataJson:JSON.stringify(i,null,2),addPrefix:!1}});if(ae(c))throw c;return c.result}initializeRelay(){return this._relay||(this._relay=new Ce({linkAPIUrl:Pa,storage:this._storage,metadata:this.metadata,accountsCallback:this._setAddresses.bind(this),chainCallback:this.updateProviderInfo.bind(this)})),this._relay}}const Lo="SignerType",Ro=new Ze("CBWSDK","SignerConfigurator");function oh(){return Ro.getItem(Lo)}function ch(e){Ro.setItem(Lo,e)}function Za(e){if(e)return e instanceof $i?"scw":"walletlink"}async function uh(e){const{communicator:t,metadata:n,handshakeRequest:r,callback:a}=e;lh(t,n,a,r).catch(()=>{});const s={id:crypto.randomUUID(),event:"selectSignerType",data:Object.assign(Object.assign({},e.preference),{handshakeRequest:r})},{data:i}=await t.postRequestAndWaitForResponse(s);return i}function dh(e){const{signerType:t,metadata:n,communicator:r,callback:a}=e;switch(t){case"scw":return new $i({metadata:n,callback:a,communicator:r});case"walletlink":return new Bo({metadata:n,callback:a})}}async function lh(e,t,n,r){await e.onMessage(({event:s})=>s==="WalletLinkSessionRequest");const a=new Bo({metadata:t,callback:n});e.postMessage({event:"WalletLinkUpdate",data:{session:a.getSession()}}),await a.handshake(r),e.postMessage({event:"WalletLinkUpdate",data:{connected:!0}})}var fh=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(e);as.address===n)?.quantity?.numeric;return u.bigNumber(a||"0").lt(o)},getToTokenAmount({sourceToken:o,toToken:n,sourceTokenPrice:t,toTokenPrice:a,sourceTokenAmount:i}){if(i==="0"||!o||!n)return"0";const s=o.decimals,c=t,d=n.decimals,k=a;if(k<=0)return"0";const S=u.bigNumber(i).times(.0085),P=u.bigNumber(i).minus(S).times(u.bigNumber(10).pow(s)),F=u.bigNumber(c).div(k),L=s-d;return P.times(F).div(u.bigNumber(10).pow(L)).div(u.bigNumber(10).pow(d)).toFixed(d).toString()}},B=15e4,J=6,l={initializing:!1,initialized:!1,loadingPrices:!1,loadingQuote:!1,loadingApprovalTransaction:!1,loadingBuildTransaction:!1,loadingTransaction:!1,fetchError:!1,approvalTransaction:void 0,swapTransaction:void 0,transactionError:void 0,sourceToken:void 0,sourceTokenAmount:"",sourceTokenPriceInUSD:0,toToken:void 0,toTokenAmount:"",toTokenPriceInUSD:0,networkPrice:"0",networkBalanceInUSD:"0",networkTokenSymbol:"",inputError:void 0,slippage:x.CONVERT_SLIPPAGE_TOLERANCE,tokens:void 0,popularTokens:void 0,suggestedTokens:void 0,foundTokens:void 0,myTokensWithBalance:void 0,tokensPriceMap:{},gasFee:"0",gasPriceInUSD:0,priceImpact:void 0,maxSlippage:void 0,providerFee:void 0},e=W(l),h={state:e,subscribe(o){return O(e,()=>o(e))},subscribeKey(o,n){return R(e,o,n)},getParams(){const o=f.state.activeCaipAddress,n=y.getPlainAddress(o),t=G(),a=z.getConnectorId(f.state.activeChain);if(!n)throw new Error("No address found to swap the tokens from.");const i=!e.toToken?.address||!e.toToken?.decimals,s=!e.sourceToken?.address||!e.sourceToken?.decimals||!u.bigNumber(e.sourceTokenAmount).gt(0),c=!e.sourceTokenAmount;return{networkAddress:t,fromAddress:n,fromCaipAddress:o,sourceTokenAddress:e.sourceToken?.address,toTokenAddress:e.toToken?.address,toTokenAmount:e.toTokenAmount,toTokenDecimals:e.toToken?.decimals,sourceTokenAmount:e.sourceTokenAmount,sourceTokenDecimals:e.sourceToken?.decimals,invalidToToken:i,invalidSourceToken:s,invalidSourceTokenAmount:c,availableToSwap:o&&!i&&!s&&!c,isAuthConnector:a===p.CONNECTOR_ID.AUTH}},setSourceToken(o){if(!o){e.sourceToken=o,e.sourceTokenAmount="",e.sourceTokenPriceInUSD=0;return}e.sourceToken=o,r.setTokenPrice(o.address,"sourceToken")},setSourceTokenAmount(o){e.sourceTokenAmount=o},setToToken(o){if(!o){e.toToken=o,e.toTokenAmount="",e.toTokenPriceInUSD=0;return}e.toToken=o,r.setTokenPrice(o.address,"toToken")},setToTokenAmount(o){e.toTokenAmount=o?u.formatNumberToLocalString(o,J):""},async setTokenPrice(o,n){let t=e.tokensPriceMap[o]||0;t||(e.loadingPrices=!0,t=await r.getAddressPrice(o)),n==="sourceToken"?e.sourceTokenPriceInUSD=t:n==="toToken"&&(e.toTokenPriceInUSD=t),e.loadingPrices&&(e.loadingPrices=!1),r.getParams().availableToSwap&&r.swapTokens()},switchTokens(){if(e.initializing||!e.initialized)return;const o=e.toToken?{...e.toToken}:void 0,n=e.sourceToken?{...e.sourceToken}:void 0,t=o&&e.toTokenAmount===""?"1":e.toTokenAmount;r.setSourceToken(o),r.setToToken(n),r.setSourceTokenAmount(t),r.setToTokenAmount(""),r.swapTokens()},resetState(){e.myTokensWithBalance=l.myTokensWithBalance,e.tokensPriceMap=l.tokensPriceMap,e.initialized=l.initialized,e.sourceToken=l.sourceToken,e.sourceTokenAmount=l.sourceTokenAmount,e.sourceTokenPriceInUSD=l.sourceTokenPriceInUSD,e.toToken=l.toToken,e.toTokenAmount=l.toTokenAmount,e.toTokenPriceInUSD=l.toTokenPriceInUSD,e.networkPrice=l.networkPrice,e.networkTokenSymbol=l.networkTokenSymbol,e.networkBalanceInUSD=l.networkBalanceInUSD,e.inputError=l.inputError,e.myTokensWithBalance=l.myTokensWithBalance},resetValues(){const{networkAddress:o}=r.getParams(),n=e.tokens?.find(t=>t.address===o);r.setSourceToken(n),r.setToToken(void 0)},getApprovalLoadingState(){return e.loadingApprovalTransaction},clearError(){e.transactionError=void 0},async initializeState(){if(!e.initializing){if(e.initializing=!0,!e.initialized)try{await r.fetchTokens(),e.initialized=!0}catch{e.initialized=!1,T.showError("Failed to initialize swap"),m.goBack()}e.initializing=!1}},async fetchTokens(){const{networkAddress:o}=r.getParams();await r.getTokenList(),await r.getNetworkTokenPrice(),await r.getMyTokensWithBalance();const n=e.tokens?.find(t=>t.address===o);n&&(e.networkTokenSymbol=n.symbol,r.setSourceToken(n),r.setSourceTokenAmount("0"))},async getTokenList(){const o=await b.getTokenList();e.tokens=o,e.popularTokens=o.sort((n,t)=>n.symbolt.symbol?1:0),e.suggestedTokens=o.filter(n=>!!x.SWAP_SUGGESTED_TOKENS.includes(n.symbol),{})},async getAddressPrice(o){const n=e.tokensPriceMap[o];if(n)return n;const a=(await w.fetchTokenPrice({addresses:[o]}))?.fungibles||[],s=[...e.tokens||[],...e.myTokensWithBalance||[]]?.find(k=>k.address===o)?.symbol,c=a.find(k=>k.symbol.toLowerCase()===s?.toLowerCase())?.price||0,d=parseFloat(c.toString());return e.tokensPriceMap[o]=d,d},async getNetworkTokenPrice(){const{networkAddress:o}=r.getParams(),t=(await w.fetchTokenPrice({addresses:[o]}).catch(()=>(T.showError("Failed to fetch network token price"),{fungibles:[]}))).fungibles?.[0],a=t?.price.toString()||"0";e.tokensPriceMap[o]=parseFloat(a),e.networkTokenSymbol=t?.symbol||"",e.networkPrice=a},async getMyTokensWithBalance(o){const n=await V.getMyTokensWithBalance(o),t=b.mapBalancesToSwapTokens(n);t&&(await r.getInitialGasPrice(),r.setBalances(t))},setBalances(o){const{networkAddress:n}=r.getParams(),t=f.state.activeCaipNetwork;if(!t)return;const a=o.find(i=>i.address===n);o.forEach(i=>{e.tokensPriceMap[i.address]=i.price||0}),e.myTokensWithBalance=o.filter(i=>i.address.startsWith(t.caipNetworkId)),e.networkBalanceInUSD=a?u.multiply(a.quantity.numeric,a.price).toString():"0"},async getInitialGasPrice(){const o=await b.fetchGasPrice();if(!o)return{gasPrice:null,gasPriceInUSD:null};switch(f.state?.activeCaipNetwork?.chainNamespace){case p.CHAIN.SOLANA:return e.gasFee=o.standard??"0",e.gasPriceInUSD=u.multiply(o.standard,e.networkPrice).div(1e9).toNumber(),{gasPrice:BigInt(e.gasFee),gasPriceInUSD:Number(e.gasPriceInUSD)};case p.CHAIN.EVM:default:const n=o.standard??"0",t=BigInt(n),a=BigInt(B),i=g.getGasPriceInUSD(e.networkPrice,a,t);return e.gasFee=n,e.gasPriceInUSD=i,{gasPrice:t,gasPriceInUSD:i}}},async swapTokens(){const o=$.state.address,n=e.sourceToken,t=e.toToken,a=u.bigNumber(e.sourceTokenAmount).gt(0);if(a||r.setToTokenAmount(""),!t||!n||e.loadingPrices||!a)return;e.loadingQuote=!0;const i=u.bigNumber(e.sourceTokenAmount).times(10**n.decimals).round(0);try{const s=await w.fetchSwapQuote({userAddress:o,from:n.address,to:t.address,gasPrice:e.gasFee,amount:i.toString()});e.loadingQuote=!1;const c=s?.quotes?.[0]?.toAmount;if(!c){H.open({displayMessage:"Incorrect amount",debugMessage:"Please enter a valid amount"},"error");return}const d=u.bigNumber(c).div(10**t.decimals).toString();r.setToTokenAmount(d),r.hasInsufficientToken(e.sourceTokenAmount,n.address)?e.inputError="Insufficient balance":(e.inputError=void 0,r.setTransactionDetails())}catch{e.loadingQuote=!1,e.inputError="Insufficient balance"}},async getTransaction(){const{fromCaipAddress:o,availableToSwap:n}=r.getParams(),t=e.sourceToken,a=e.toToken;if(!(!o||!n||!t||!a||e.loadingQuote))try{e.loadingBuildTransaction=!0;const i=await b.fetchSwapAllowance({userAddress:o,tokenAddress:t.address,sourceTokenAmount:e.sourceTokenAmount,sourceTokenDecimals:t.decimals});let s;return i?s=await r.createSwapTransaction():s=await r.createAllowanceTransaction(),e.loadingBuildTransaction=!1,e.fetchError=!1,s}catch{m.goBack(),T.showError("Failed to check allowance"),e.loadingBuildTransaction=!1,e.approvalTransaction=void 0,e.swapTransaction=void 0,e.fetchError=!0;return}},async createAllowanceTransaction(){const{fromCaipAddress:o,sourceTokenAddress:n,toTokenAddress:t}=r.getParams();if(!(!o||!t)){if(!n)throw new Error("createAllowanceTransaction - No source token address found.");try{const a=await w.generateApproveCalldata({from:n,to:t,userAddress:o}),i=y.getPlainAddress(a.tx.from);if(!i)throw new Error("SwapController:createAllowanceTransaction - address is required");const s={data:a.tx.data,to:i,gasPrice:BigInt(a.tx.eip155.gasPrice),value:BigInt(a.tx.value),toAmount:e.toTokenAmount};return e.swapTransaction=void 0,e.approvalTransaction={data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount},{data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount}}catch{m.goBack(),T.showError("Failed to create approval transaction"),e.approvalTransaction=void 0,e.swapTransaction=void 0,e.fetchError=!0;return}}},async createSwapTransaction(){const{networkAddress:o,fromCaipAddress:n,sourceTokenAmount:t}=r.getParams(),a=e.sourceToken,i=e.toToken;if(!n||!t||!a||!i)return;const s=v.parseUnits(t,a.decimals)?.toString();try{const c=await w.generateSwapCalldata({userAddress:n,from:a.address,to:i.address,amount:s,disableEstimate:!0}),d=a.address===o,k=BigInt(c.tx.eip155.gas),S=BigInt(c.tx.eip155.gasPrice),I=y.getPlainAddress(c.tx.to);if(!I)throw new Error("SwapController:createSwapTransaction - address is required");const P={data:c.tx.data,to:I,gas:k,gasPrice:S,value:BigInt(d?s??"0":"0"),toAmount:e.toTokenAmount};return e.gasPriceInUSD=g.getGasPriceInUSD(e.networkPrice,k,S),e.approvalTransaction=void 0,e.swapTransaction=P,P}catch{m.goBack(),T.showError("Failed to create transaction"),e.approvalTransaction=void 0,e.swapTransaction=void 0,e.fetchError=!0;return}},onEmbeddedWalletApprovalSuccess(){T.showLoading("Approve limit increase in your wallet"),m.replace("SwapPreview")},async sendTransactionForApproval(o){const{fromAddress:n,isAuthConnector:t}=r.getParams();e.loadingApprovalTransaction=!0,t?m.pushTransactionStack({onSuccess:r.onEmbeddedWalletApprovalSuccess}):T.showLoading("Approve limit increase in your wallet");try{await v.sendTransaction({address:n,to:o.to,data:o.data,value:o.value,chainNamespace:p.CHAIN.EVM}),await r.swapTokens(),await r.getTransaction(),e.approvalTransaction=void 0,e.loadingApprovalTransaction=!1}catch(i){const s=i;e.transactionError=s?.displayMessage,e.loadingApprovalTransaction=!1,T.showError(s?.displayMessage||"Transaction error"),C.sendEvent({type:"track",event:"SWAP_APPROVAL_ERROR",properties:{message:s?.displayMessage||s?.message||"Unknown",network:f.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:r.state.sourceToken?.symbol||"",swapToToken:r.state.toToken?.symbol||"",swapFromAmount:r.state.sourceTokenAmount||"",swapToAmount:r.state.toTokenAmount||"",isSmartAccount:N(p.CHAIN.EVM)===E.ACCOUNT_TYPES.SMART_ACCOUNT}})}},async sendTransactionForSwap(o){if(!o)return;const{fromAddress:n,toTokenAmount:t,isAuthConnector:a}=r.getParams();e.loadingTransaction=!0;const i=`Swapping ${e.sourceToken?.symbol} to ${u.formatNumberToLocalString(t,3)} ${e.toToken?.symbol}`,s=`Swapped ${e.sourceToken?.symbol} to ${u.formatNumberToLocalString(t,3)} ${e.toToken?.symbol}`;a?m.pushTransactionStack({onSuccess(){m.replace("Account"),T.showLoading(i),h.resetState()}}):T.showLoading("Confirm transaction in your wallet");try{const c=[e.sourceToken?.address,e.toToken?.address].join(","),d=await v.sendTransaction({address:n,to:o.to,data:o.data,value:o.value,chainNamespace:p.CHAIN.EVM});return e.loadingTransaction=!1,T.showSuccess(s),C.sendEvent({type:"track",event:"SWAP_SUCCESS",properties:{network:f.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:r.state.sourceToken?.symbol||"",swapToToken:r.state.toToken?.symbol||"",swapFromAmount:r.state.sourceTokenAmount||"",swapToAmount:r.state.toTokenAmount||"",isSmartAccount:N(p.CHAIN.EVM)===E.ACCOUNT_TYPES.SMART_ACCOUNT}}),h.resetState(),a||m.replace("Account"),h.getMyTokensWithBalance(c),d}catch(c){const d=c;e.transactionError=d?.displayMessage,e.loadingTransaction=!1,T.showError(d?.displayMessage||"Transaction error"),C.sendEvent({type:"track",event:"SWAP_ERROR",properties:{message:d?.displayMessage||d?.message||"Unknown",network:f.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:r.state.sourceToken?.symbol||"",swapToToken:r.state.toToken?.symbol||"",swapFromAmount:r.state.sourceTokenAmount||"",swapToAmount:r.state.toTokenAmount||"",isSmartAccount:N(p.CHAIN.EVM)===E.ACCOUNT_TYPES.SMART_ACCOUNT}});return}},hasInsufficientToken(o,n){return g.isInsufficientSourceTokenForSwap(o,n,e.myTokensWithBalance)},setTransactionDetails(){const{toTokenAddress:o,toTokenDecimals:n}=r.getParams();!o||!n||(e.gasPriceInUSD=g.getGasPriceInUSD(e.networkPrice,BigInt(e.gasFee),BigInt(B)),e.priceImpact=g.getPriceImpact({sourceTokenAmount:e.sourceTokenAmount,sourceTokenPriceInUSD:e.sourceTokenPriceInUSD,toTokenPriceInUSD:e.toTokenPriceInUSD,toTokenAmount:e.toTokenAmount}),e.maxSlippage=g.getMaxSlippage(e.slippage,e.toTokenAmount),e.providerFee=g.getProviderFee(e.sourceTokenAmount))}},r=_(h),X=q` + :host { + display: block; + } + + :host > button { + gap: var(--wui-spacing-xxs); + padding: var(--wui-spacing-xs); + padding-right: var(--wui-spacing-1xs); + height: 40px; + border-radius: var(--wui-border-radius-l); + background: var(--wui-color-gray-glass-002); + border-width: 0px; + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-002); + } + + :host > button wui-image { + width: 24px; + height: 24px; + border-radius: var(--wui-border-radius-s); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + } +`;var D=function(o,n,t,a){var i=arguments.length,s=i<3?n:a===null?a=Object.getOwnPropertyDescriptor(n,t):a,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,n,t,a);else for(var d=o.length-1;d>=0;d--)(c=o[d])&&(s=(i<3?c(s):i>3?c(n,t,s):c(n,t))||s);return i>3&&s&&Object.defineProperty(n,t,s),s};let A=class extends Y{constructor(){super(...arguments),this.text=""}render(){return U` + + `}tokenTemplate(){return this.imageSrc?U``:U` + + `}};A.styles=[Q,j,X];D([M()],A.prototype,"imageSrc",void 0);D([M()],A.prototype,"text",void 0);A=D([K("wui-token-button")],A);export{r as S}; diff --git a/dist/assets/index-Dl0F4g05.js b/dist/assets/index-Dl0F4g05.js new file mode 100644 index 0000000..7f0c114 --- /dev/null +++ b/dist/assets/index-Dl0F4g05.js @@ -0,0 +1,7 @@ +import{aS as Fc,aO as B,ag as rn,ah as sa,d1 as Hc,d2 as Uc,ai as Vc}from"./index-Cr5N_0pd.js";import{b as zc,r as ia}from"./index-COonna6N.js";import{p as Wc,a as qc}from"./hooks.module-Dz_XB4AG.js";var oa={},Yr={},zn={};Object.defineProperty(zn,"__esModule",{value:!0});zn.walletLogo=void 0;const Jc=(e,t)=>{let r;switch(e){case"standard":return r=t,`data:image/svg+xml,%3Csvg width='${t}' height='${r}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `;case"circle":return r=t,`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${t}' height='${r}' viewBox='0 0 999.81 999.81'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052fe;%7D.cls-2%7Bfill:%23fefefe;%7D.cls-3%7Bfill:%230152fe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M655-115.9h56c.83,1.59,2.36.88,3.56,1a478,478,0,0,1,75.06,10.42C891.4-81.76,978.33-32.58,1049.19,44q116.7,126,131.94,297.61c.38,4.14-.34,8.53,1.78,12.45v59c-1.58.84-.91,2.35-1,3.56a482.05,482.05,0,0,1-10.38,74.05c-24,106.72-76.64,196.76-158.83,268.93s-178.18,112.82-287.2,122.6c-4.83.43-9.86-.25-14.51,1.77H654c-1-1.68-2.69-.91-4.06-1a496.89,496.89,0,0,1-105.9-18.59c-93.54-27.42-172.78-77.59-236.91-150.94Q199.34,590.1,184.87,426.58c-.47-5.19.25-10.56-1.77-15.59V355c1.68-1,.91-2.7,1-4.06a498.12,498.12,0,0,1,18.58-105.9c26-88.75,72.64-164.9,140.6-227.57q126-116.27,297.21-131.61C645.32-114.57,650.35-113.88,655-115.9Zm377.92,500c0-192.44-156.31-349.49-347.56-350.15-194.13-.68-350.94,155.13-352.29,347.42-1.37,194.55,155.51,352.1,348.56,352.47C876.15,734.23,1032.93,577.84,1032.93,384.11Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-2' d='M1032.93,384.11c0,193.73-156.78,350.12-351.29,349.74-193-.37-349.93-157.92-348.56-352.47C334.43,189.09,491.24,33.28,685.37,34,876.62,34.62,1032.94,191.67,1032.93,384.11ZM683,496.81q43.74,0,87.48,0c15.55,0,25.32-9.72,25.33-25.21q0-87.48,0-175c0-15.83-9.68-25.46-25.59-25.46H595.77c-15.88,0-25.57,9.64-25.58,25.46q0,87.23,0,174.45c0,16.18,9.59,25.7,25.84,25.71Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-3' d='M683,496.81H596c-16.25,0-25.84-9.53-25.84-25.71q0-87.23,0-174.45c0-15.82,9.7-25.46,25.58-25.46H770.22c15.91,0,25.59,9.63,25.59,25.46q0,87.47,0,175c0,15.49-9.78,25.2-25.33,25.21Q726.74,496.84,683,496.81Z' transform='translate(-183.1 115.9)'/%3E%3C/svg%3E`;case"text":return r=(.1*t).toFixed(2),`data:image/svg+xml,%3Csvg width='${t}' height='${r}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogo":return r=(.25*t).toFixed(2),`data:image/svg+xml,%3Csvg width='${t}' height='${r}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;case"textLight":return r=(.1*t).toFixed(2),`data:image/svg+xml,%3Csvg width='${t}' height='${r}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`;case"textWithLogoLight":return r=(.25*t).toFixed(2),`data:image/svg+xml,%3Csvg width='${t}' height='${r}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`;default:return r=t,`data:image/svg+xml,%3Csvg width='${t}' height='${r}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `}};zn.walletLogo=Jc;var Wn={};Object.defineProperty(Wn,"__esModule",{value:!0});Wn.LINK_API_URL=void 0;Wn.LINK_API_URL="https://www.walletlink.org";var T={},ui={exports:{}};ui.exports;(function(e){(function(t,r){function n(_,o){if(!_)throw new Error(o||"Assertion failed")}function s(_,o){_.super_=o;var l=function(){};l.prototype=o.prototype,_.prototype=new l,_.prototype.constructor=_}function i(_,o,l){if(i.isBN(_))return _;this.negative=0,this.words=null,this.length=0,this.red=null,_!==null&&((o==="le"||o==="be")&&(l=o,o=10),this._init(_||0,o||10,l||"be"))}typeof t=="object"?t.exports=i:r.BN=i,i.BN=i,i.wordSize=26;var c;try{typeof window<"u"&&typeof window.Buffer<"u"?c=window.Buffer:c=Fc.Buffer}catch{}i.isBN=function(o){return o instanceof i?!0:o!==null&&typeof o=="object"&&o.constructor.wordSize===i.wordSize&&Array.isArray(o.words)},i.max=function(o,l){return o.cmp(l)>0?o:l},i.min=function(o,l){return o.cmp(l)<0?o:l},i.prototype._init=function(o,l,d){if(typeof o=="number")return this._initNumber(o,l,d);if(typeof o=="object")return this._initArray(o,l,d);l==="hex"&&(l=16),n(l===(l|0)&&l>=2&&l<=36),o=o.toString().replace(/\s+/g,"");var p=0;o[0]==="-"&&(p++,this.negative=1),p=0;p-=3)y=o[p]|o[p-1]<<8|o[p-2]<<16,this.words[v]|=y<>>26-S&67108863,S+=24,S>=26&&(S-=26,v++);else if(d==="le")for(p=0,v=0;p>>26-S&67108863,S+=24,S>=26&&(S-=26,v++);return this._strip()};function u(_,o){var l=_.charCodeAt(o);if(l>=48&&l<=57)return l-48;if(l>=65&&l<=70)return l-55;if(l>=97&&l<=102)return l-87;n(!1,"Invalid character in "+_)}function h(_,o,l){var d=u(_,l);return l-1>=o&&(d|=u(_,l-1)<<4),d}i.prototype._parseHex=function(o,l,d){this.length=Math.ceil((o.length-l)/6),this.words=new Array(this.length);for(var p=0;p=l;p-=2)S=h(o,l,p)<=18?(v-=18,y+=1,this.words[y]|=S>>>26):v+=8;else{var m=o.length-l;for(p=m%2===0?l+1:l;p=18?(v-=18,y+=1,this.words[y]|=S>>>26):v+=8}this._strip()};function f(_,o,l,d){for(var p=0,v=0,y=Math.min(_.length,l),S=o;S=49?v=m-49+10:m>=17?v=m-17+10:v=m,n(m>=0&&v1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},i.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{i.prototype[Symbol.for("nodejs.util.inspect.custom")]=E}catch{i.prototype.inspect=E}else i.prototype.inspect=E;function E(){return(this.red?""}var b=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],k=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],C=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(o,l){o=o||10,l=l|0||1;var d;if(o===16||o==="hex"){d="";for(var p=0,v=0,y=0;y>>24-p&16777215,p+=2,p>=26&&(p-=26,y--),v!==0||y!==this.length-1?d=b[6-m.length]+m+d:d=m+d}for(v!==0&&(d=v.toString(16)+d);d.length%l!==0;)d="0"+d;return this.negative!==0&&(d="-"+d),d}if(o===(o|0)&&o>=2&&o<=36){var a=k[o],w=C[o];d="";var x=this.clone();for(x.negative=0;!x.isZero();){var N=x.modrn(w).toString(o);x=x.idivn(w),x.isZero()?d=N+d:d=b[a-N.length]+N+d}for(this.isZero()&&(d="0"+d);d.length%l!==0;)d="0"+d;return this.negative!==0&&(d="-"+d),d}n(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var o=this.words[0];return this.length===2?o+=this.words[1]*67108864:this.length===3&&this.words[2]===1?o+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-o:o},i.prototype.toJSON=function(){return this.toString(16,2)},c&&(i.prototype.toBuffer=function(o,l){return this.toArrayLike(c,o,l)}),i.prototype.toArray=function(o,l){return this.toArrayLike(Array,o,l)};var R=function(o,l){return o.allocUnsafe?o.allocUnsafe(l):new o(l)};i.prototype.toArrayLike=function(o,l,d){this._strip();var p=this.byteLength(),v=d||Math.max(1,p);n(p<=v,"byte array longer than desired length"),n(v>0,"Requested array length <= 0");var y=R(o,v),S=l==="le"?"LE":"BE";return this["_toArrayLike"+S](y,p),y},i.prototype._toArrayLikeLE=function(o,l){for(var d=0,p=0,v=0,y=0;v>8&255),d>16&255),y===6?(d>24&255),p=0,y=0):(p=S>>>24,y+=2)}if(d=0&&(o[d--]=S>>8&255),d>=0&&(o[d--]=S>>16&255),y===6?(d>=0&&(o[d--]=S>>24&255),p=0,y=0):(p=S>>>24,y+=2)}if(d>=0)for(o[d--]=p;d>=0;)o[d--]=0},Math.clz32?i.prototype._countBits=function(o){return 32-Math.clz32(o)}:i.prototype._countBits=function(o){var l=o,d=0;return l>=4096&&(d+=13,l>>>=13),l>=64&&(d+=7,l>>>=7),l>=8&&(d+=4,l>>>=4),l>=2&&(d+=2,l>>>=2),d+l},i.prototype._zeroBits=function(o){if(o===0)return 26;var l=o,d=0;return l&8191||(d+=13,l>>>=13),l&127||(d+=7,l>>>=7),l&15||(d+=4,l>>>=4),l&3||(d+=2,l>>>=2),l&1||d++,d},i.prototype.bitLength=function(){var o=this.words[this.length-1],l=this._countBits(o);return(this.length-1)*26+l};function I(_){for(var o=new Array(_.bitLength()),l=0;l>>p&1}return o}i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var o=0,l=0;lo.length?this.clone().ior(o):o.clone().ior(this)},i.prototype.uor=function(o){return this.length>o.length?this.clone().iuor(o):o.clone().iuor(this)},i.prototype.iuand=function(o){var l;this.length>o.length?l=o:l=this;for(var d=0;do.length?this.clone().iand(o):o.clone().iand(this)},i.prototype.uand=function(o){return this.length>o.length?this.clone().iuand(o):o.clone().iuand(this)},i.prototype.iuxor=function(o){var l,d;this.length>o.length?(l=this,d=o):(l=o,d=this);for(var p=0;po.length?this.clone().ixor(o):o.clone().ixor(this)},i.prototype.uxor=function(o){return this.length>o.length?this.clone().iuxor(o):o.clone().iuxor(this)},i.prototype.inotn=function(o){n(typeof o=="number"&&o>=0);var l=Math.ceil(o/26)|0,d=o%26;this._expand(l),d>0&&l--;for(var p=0;p0&&(this.words[p]=~this.words[p]&67108863>>26-d),this._strip()},i.prototype.notn=function(o){return this.clone().inotn(o)},i.prototype.setn=function(o,l){n(typeof o=="number"&&o>=0);var d=o/26|0,p=o%26;return this._expand(d+1),l?this.words[d]=this.words[d]|1<o.length?(d=this,p=o):(d=o,p=this);for(var v=0,y=0;y>>26;for(;v!==0&&y>>26;if(this.length=d.length,v!==0)this.words[this.length]=v,this.length++;else if(d!==this)for(;yo.length?this.clone().iadd(o):o.clone().iadd(this)},i.prototype.isub=function(o){if(o.negative!==0){o.negative=0;var l=this.iadd(o);return o.negative=1,l._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(o),this.negative=1,this._normSign();var d=this.cmp(o);if(d===0)return this.negative=0,this.length=1,this.words[0]=0,this;var p,v;d>0?(p=this,v=o):(p=o,v=this);for(var y=0,S=0;S>26,this.words[S]=l&67108863;for(;y!==0&&S>26,this.words[S]=l&67108863;if(y===0&&S>>26,x=m&67108863,N=Math.min(a,o.length-1),O=Math.max(0,a-_.length+1);O<=N;O++){var je=a-O|0;p=_.words[je]|0,v=o.words[O]|0,y=p*v+x,w+=y/67108864|0,x=y&67108863}l.words[a]=x|0,m=w|0}return m!==0?l.words[a]=m|0:l.length--,l._strip()}var L=function(o,l,d){var p=o.words,v=l.words,y=d.words,S=0,m,a,w,x=p[0]|0,N=x&8191,O=x>>>13,je=p[1]|0,G=je&8191,Z=je>>>13,Ur=p[2]|0,_e=Ur&8191,Ee=Ur>>>13,Vr=p[3]|0,Se=Vr&8191,ke=Vr>>>13,zr=p[4]|0,Me=zr&8191,Re=zr>>>13,Wr=p[5]|0,Ie=Wr&8191,Ce=Wr>>>13,qr=p[6]|0,Ae=qr&8191,Ne=qr>>>13,Jr=p[7]|0,Le=Jr&8191,xe=Jr>>>13,sr=p[8]|0,K=sr&8191,X=sr>>>13,ir=p[9]|0,Y=ir&8191,ee=ir>>>13,or=v[0]|0,te=or&8191,re=or>>>13,ar=v[1]|0,ne=ar&8191,se=ar>>>13,cr=v[2]|0,ie=cr&8191,oe=cr>>>13,lr=v[3]|0,ae=lr&8191,ce=lr>>>13,ur=v[4]|0,le=ur&8191,ue=ur>>>13,hr=v[5]|0,he=hr&8191,de=hr>>>13,dr=v[6]|0,fe=dr&8191,ge=dr>>>13,fr=v[7]|0,pe=fr&8191,me=fr>>>13,gr=v[8]|0,ve=gr&8191,we=gr>>>13,pr=v[9]|0,ye=pr&8191,be=pr>>>13;d.negative=o.negative^l.negative,d.length=19,m=Math.imul(N,te),a=Math.imul(N,re),a=a+Math.imul(O,te)|0,w=Math.imul(O,re);var Nt=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,m=Math.imul(G,te),a=Math.imul(G,re),a=a+Math.imul(Z,te)|0,w=Math.imul(Z,re),m=m+Math.imul(N,ne)|0,a=a+Math.imul(N,se)|0,a=a+Math.imul(O,ne)|0,w=w+Math.imul(O,se)|0;var Lt=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,m=Math.imul(_e,te),a=Math.imul(_e,re),a=a+Math.imul(Ee,te)|0,w=Math.imul(Ee,re),m=m+Math.imul(G,ne)|0,a=a+Math.imul(G,se)|0,a=a+Math.imul(Z,ne)|0,w=w+Math.imul(Z,se)|0,m=m+Math.imul(N,ie)|0,a=a+Math.imul(N,oe)|0,a=a+Math.imul(O,ie)|0,w=w+Math.imul(O,oe)|0;var xt=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(xt>>>26)|0,xt&=67108863,m=Math.imul(Se,te),a=Math.imul(Se,re),a=a+Math.imul(ke,te)|0,w=Math.imul(ke,re),m=m+Math.imul(_e,ne)|0,a=a+Math.imul(_e,se)|0,a=a+Math.imul(Ee,ne)|0,w=w+Math.imul(Ee,se)|0,m=m+Math.imul(G,ie)|0,a=a+Math.imul(G,oe)|0,a=a+Math.imul(Z,ie)|0,w=w+Math.imul(Z,oe)|0,m=m+Math.imul(N,ae)|0,a=a+Math.imul(N,ce)|0,a=a+Math.imul(O,ae)|0,w=w+Math.imul(O,ce)|0;var Tt=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,m=Math.imul(Me,te),a=Math.imul(Me,re),a=a+Math.imul(Re,te)|0,w=Math.imul(Re,re),m=m+Math.imul(Se,ne)|0,a=a+Math.imul(Se,se)|0,a=a+Math.imul(ke,ne)|0,w=w+Math.imul(ke,se)|0,m=m+Math.imul(_e,ie)|0,a=a+Math.imul(_e,oe)|0,a=a+Math.imul(Ee,ie)|0,w=w+Math.imul(Ee,oe)|0,m=m+Math.imul(G,ae)|0,a=a+Math.imul(G,ce)|0,a=a+Math.imul(Z,ae)|0,w=w+Math.imul(Z,ce)|0,m=m+Math.imul(N,le)|0,a=a+Math.imul(N,ue)|0,a=a+Math.imul(O,le)|0,w=w+Math.imul(O,ue)|0;var Pt=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,m=Math.imul(Ie,te),a=Math.imul(Ie,re),a=a+Math.imul(Ce,te)|0,w=Math.imul(Ce,re),m=m+Math.imul(Me,ne)|0,a=a+Math.imul(Me,se)|0,a=a+Math.imul(Re,ne)|0,w=w+Math.imul(Re,se)|0,m=m+Math.imul(Se,ie)|0,a=a+Math.imul(Se,oe)|0,a=a+Math.imul(ke,ie)|0,w=w+Math.imul(ke,oe)|0,m=m+Math.imul(_e,ae)|0,a=a+Math.imul(_e,ce)|0,a=a+Math.imul(Ee,ae)|0,w=w+Math.imul(Ee,ce)|0,m=m+Math.imul(G,le)|0,a=a+Math.imul(G,ue)|0,a=a+Math.imul(Z,le)|0,w=w+Math.imul(Z,ue)|0,m=m+Math.imul(N,he)|0,a=a+Math.imul(N,de)|0,a=a+Math.imul(O,he)|0,w=w+Math.imul(O,de)|0;var $t=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+($t>>>26)|0,$t&=67108863,m=Math.imul(Ae,te),a=Math.imul(Ae,re),a=a+Math.imul(Ne,te)|0,w=Math.imul(Ne,re),m=m+Math.imul(Ie,ne)|0,a=a+Math.imul(Ie,se)|0,a=a+Math.imul(Ce,ne)|0,w=w+Math.imul(Ce,se)|0,m=m+Math.imul(Me,ie)|0,a=a+Math.imul(Me,oe)|0,a=a+Math.imul(Re,ie)|0,w=w+Math.imul(Re,oe)|0,m=m+Math.imul(Se,ae)|0,a=a+Math.imul(Se,ce)|0,a=a+Math.imul(ke,ae)|0,w=w+Math.imul(ke,ce)|0,m=m+Math.imul(_e,le)|0,a=a+Math.imul(_e,ue)|0,a=a+Math.imul(Ee,le)|0,w=w+Math.imul(Ee,ue)|0,m=m+Math.imul(G,he)|0,a=a+Math.imul(G,de)|0,a=a+Math.imul(Z,he)|0,w=w+Math.imul(Z,de)|0,m=m+Math.imul(N,fe)|0,a=a+Math.imul(N,ge)|0,a=a+Math.imul(O,fe)|0,w=w+Math.imul(O,ge)|0;var Ot=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,m=Math.imul(Le,te),a=Math.imul(Le,re),a=a+Math.imul(xe,te)|0,w=Math.imul(xe,re),m=m+Math.imul(Ae,ne)|0,a=a+Math.imul(Ae,se)|0,a=a+Math.imul(Ne,ne)|0,w=w+Math.imul(Ne,se)|0,m=m+Math.imul(Ie,ie)|0,a=a+Math.imul(Ie,oe)|0,a=a+Math.imul(Ce,ie)|0,w=w+Math.imul(Ce,oe)|0,m=m+Math.imul(Me,ae)|0,a=a+Math.imul(Me,ce)|0,a=a+Math.imul(Re,ae)|0,w=w+Math.imul(Re,ce)|0,m=m+Math.imul(Se,le)|0,a=a+Math.imul(Se,ue)|0,a=a+Math.imul(ke,le)|0,w=w+Math.imul(ke,ue)|0,m=m+Math.imul(_e,he)|0,a=a+Math.imul(_e,de)|0,a=a+Math.imul(Ee,he)|0,w=w+Math.imul(Ee,de)|0,m=m+Math.imul(G,fe)|0,a=a+Math.imul(G,ge)|0,a=a+Math.imul(Z,fe)|0,w=w+Math.imul(Z,ge)|0,m=m+Math.imul(N,pe)|0,a=a+Math.imul(N,me)|0,a=a+Math.imul(O,pe)|0,w=w+Math.imul(O,me)|0;var Bt=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,m=Math.imul(K,te),a=Math.imul(K,re),a=a+Math.imul(X,te)|0,w=Math.imul(X,re),m=m+Math.imul(Le,ne)|0,a=a+Math.imul(Le,se)|0,a=a+Math.imul(xe,ne)|0,w=w+Math.imul(xe,se)|0,m=m+Math.imul(Ae,ie)|0,a=a+Math.imul(Ae,oe)|0,a=a+Math.imul(Ne,ie)|0,w=w+Math.imul(Ne,oe)|0,m=m+Math.imul(Ie,ae)|0,a=a+Math.imul(Ie,ce)|0,a=a+Math.imul(Ce,ae)|0,w=w+Math.imul(Ce,ce)|0,m=m+Math.imul(Me,le)|0,a=a+Math.imul(Me,ue)|0,a=a+Math.imul(Re,le)|0,w=w+Math.imul(Re,ue)|0,m=m+Math.imul(Se,he)|0,a=a+Math.imul(Se,de)|0,a=a+Math.imul(ke,he)|0,w=w+Math.imul(ke,de)|0,m=m+Math.imul(_e,fe)|0,a=a+Math.imul(_e,ge)|0,a=a+Math.imul(Ee,fe)|0,w=w+Math.imul(Ee,ge)|0,m=m+Math.imul(G,pe)|0,a=a+Math.imul(G,me)|0,a=a+Math.imul(Z,pe)|0,w=w+Math.imul(Z,me)|0,m=m+Math.imul(N,ve)|0,a=a+Math.imul(N,we)|0,a=a+Math.imul(O,ve)|0,w=w+Math.imul(O,we)|0;var Dt=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Dt>>>26)|0,Dt&=67108863,m=Math.imul(Y,te),a=Math.imul(Y,re),a=a+Math.imul(ee,te)|0,w=Math.imul(ee,re),m=m+Math.imul(K,ne)|0,a=a+Math.imul(K,se)|0,a=a+Math.imul(X,ne)|0,w=w+Math.imul(X,se)|0,m=m+Math.imul(Le,ie)|0,a=a+Math.imul(Le,oe)|0,a=a+Math.imul(xe,ie)|0,w=w+Math.imul(xe,oe)|0,m=m+Math.imul(Ae,ae)|0,a=a+Math.imul(Ae,ce)|0,a=a+Math.imul(Ne,ae)|0,w=w+Math.imul(Ne,ce)|0,m=m+Math.imul(Ie,le)|0,a=a+Math.imul(Ie,ue)|0,a=a+Math.imul(Ce,le)|0,w=w+Math.imul(Ce,ue)|0,m=m+Math.imul(Me,he)|0,a=a+Math.imul(Me,de)|0,a=a+Math.imul(Re,he)|0,w=w+Math.imul(Re,de)|0,m=m+Math.imul(Se,fe)|0,a=a+Math.imul(Se,ge)|0,a=a+Math.imul(ke,fe)|0,w=w+Math.imul(ke,ge)|0,m=m+Math.imul(_e,pe)|0,a=a+Math.imul(_e,me)|0,a=a+Math.imul(Ee,pe)|0,w=w+Math.imul(Ee,me)|0,m=m+Math.imul(G,ve)|0,a=a+Math.imul(G,we)|0,a=a+Math.imul(Z,ve)|0,w=w+Math.imul(Z,we)|0,m=m+Math.imul(N,ye)|0,a=a+Math.imul(N,be)|0,a=a+Math.imul(O,ye)|0,w=w+Math.imul(O,be)|0;var jt=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(jt>>>26)|0,jt&=67108863,m=Math.imul(Y,ne),a=Math.imul(Y,se),a=a+Math.imul(ee,ne)|0,w=Math.imul(ee,se),m=m+Math.imul(K,ie)|0,a=a+Math.imul(K,oe)|0,a=a+Math.imul(X,ie)|0,w=w+Math.imul(X,oe)|0,m=m+Math.imul(Le,ae)|0,a=a+Math.imul(Le,ce)|0,a=a+Math.imul(xe,ae)|0,w=w+Math.imul(xe,ce)|0,m=m+Math.imul(Ae,le)|0,a=a+Math.imul(Ae,ue)|0,a=a+Math.imul(Ne,le)|0,w=w+Math.imul(Ne,ue)|0,m=m+Math.imul(Ie,he)|0,a=a+Math.imul(Ie,de)|0,a=a+Math.imul(Ce,he)|0,w=w+Math.imul(Ce,de)|0,m=m+Math.imul(Me,fe)|0,a=a+Math.imul(Me,ge)|0,a=a+Math.imul(Re,fe)|0,w=w+Math.imul(Re,ge)|0,m=m+Math.imul(Se,pe)|0,a=a+Math.imul(Se,me)|0,a=a+Math.imul(ke,pe)|0,w=w+Math.imul(ke,me)|0,m=m+Math.imul(_e,ve)|0,a=a+Math.imul(_e,we)|0,a=a+Math.imul(Ee,ve)|0,w=w+Math.imul(Ee,we)|0,m=m+Math.imul(G,ye)|0,a=a+Math.imul(G,be)|0,a=a+Math.imul(Z,ye)|0,w=w+Math.imul(Z,be)|0;var Ft=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Ft>>>26)|0,Ft&=67108863,m=Math.imul(Y,ie),a=Math.imul(Y,oe),a=a+Math.imul(ee,ie)|0,w=Math.imul(ee,oe),m=m+Math.imul(K,ae)|0,a=a+Math.imul(K,ce)|0,a=a+Math.imul(X,ae)|0,w=w+Math.imul(X,ce)|0,m=m+Math.imul(Le,le)|0,a=a+Math.imul(Le,ue)|0,a=a+Math.imul(xe,le)|0,w=w+Math.imul(xe,ue)|0,m=m+Math.imul(Ae,he)|0,a=a+Math.imul(Ae,de)|0,a=a+Math.imul(Ne,he)|0,w=w+Math.imul(Ne,de)|0,m=m+Math.imul(Ie,fe)|0,a=a+Math.imul(Ie,ge)|0,a=a+Math.imul(Ce,fe)|0,w=w+Math.imul(Ce,ge)|0,m=m+Math.imul(Me,pe)|0,a=a+Math.imul(Me,me)|0,a=a+Math.imul(Re,pe)|0,w=w+Math.imul(Re,me)|0,m=m+Math.imul(Se,ve)|0,a=a+Math.imul(Se,we)|0,a=a+Math.imul(ke,ve)|0,w=w+Math.imul(ke,we)|0,m=m+Math.imul(_e,ye)|0,a=a+Math.imul(_e,be)|0,a=a+Math.imul(Ee,ye)|0,w=w+Math.imul(Ee,be)|0;var Ht=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Ht>>>26)|0,Ht&=67108863,m=Math.imul(Y,ae),a=Math.imul(Y,ce),a=a+Math.imul(ee,ae)|0,w=Math.imul(ee,ce),m=m+Math.imul(K,le)|0,a=a+Math.imul(K,ue)|0,a=a+Math.imul(X,le)|0,w=w+Math.imul(X,ue)|0,m=m+Math.imul(Le,he)|0,a=a+Math.imul(Le,de)|0,a=a+Math.imul(xe,he)|0,w=w+Math.imul(xe,de)|0,m=m+Math.imul(Ae,fe)|0,a=a+Math.imul(Ae,ge)|0,a=a+Math.imul(Ne,fe)|0,w=w+Math.imul(Ne,ge)|0,m=m+Math.imul(Ie,pe)|0,a=a+Math.imul(Ie,me)|0,a=a+Math.imul(Ce,pe)|0,w=w+Math.imul(Ce,me)|0,m=m+Math.imul(Me,ve)|0,a=a+Math.imul(Me,we)|0,a=a+Math.imul(Re,ve)|0,w=w+Math.imul(Re,we)|0,m=m+Math.imul(Se,ye)|0,a=a+Math.imul(Se,be)|0,a=a+Math.imul(ke,ye)|0,w=w+Math.imul(ke,be)|0;var Ut=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Ut>>>26)|0,Ut&=67108863,m=Math.imul(Y,le),a=Math.imul(Y,ue),a=a+Math.imul(ee,le)|0,w=Math.imul(ee,ue),m=m+Math.imul(K,he)|0,a=a+Math.imul(K,de)|0,a=a+Math.imul(X,he)|0,w=w+Math.imul(X,de)|0,m=m+Math.imul(Le,fe)|0,a=a+Math.imul(Le,ge)|0,a=a+Math.imul(xe,fe)|0,w=w+Math.imul(xe,ge)|0,m=m+Math.imul(Ae,pe)|0,a=a+Math.imul(Ae,me)|0,a=a+Math.imul(Ne,pe)|0,w=w+Math.imul(Ne,me)|0,m=m+Math.imul(Ie,ve)|0,a=a+Math.imul(Ie,we)|0,a=a+Math.imul(Ce,ve)|0,w=w+Math.imul(Ce,we)|0,m=m+Math.imul(Me,ye)|0,a=a+Math.imul(Me,be)|0,a=a+Math.imul(Re,ye)|0,w=w+Math.imul(Re,be)|0;var Vt=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Vt>>>26)|0,Vt&=67108863,m=Math.imul(Y,he),a=Math.imul(Y,de),a=a+Math.imul(ee,he)|0,w=Math.imul(ee,de),m=m+Math.imul(K,fe)|0,a=a+Math.imul(K,ge)|0,a=a+Math.imul(X,fe)|0,w=w+Math.imul(X,ge)|0,m=m+Math.imul(Le,pe)|0,a=a+Math.imul(Le,me)|0,a=a+Math.imul(xe,pe)|0,w=w+Math.imul(xe,me)|0,m=m+Math.imul(Ae,ve)|0,a=a+Math.imul(Ae,we)|0,a=a+Math.imul(Ne,ve)|0,w=w+Math.imul(Ne,we)|0,m=m+Math.imul(Ie,ye)|0,a=a+Math.imul(Ie,be)|0,a=a+Math.imul(Ce,ye)|0,w=w+Math.imul(Ce,be)|0;var $s=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+($s>>>26)|0,$s&=67108863,m=Math.imul(Y,fe),a=Math.imul(Y,ge),a=a+Math.imul(ee,fe)|0,w=Math.imul(ee,ge),m=m+Math.imul(K,pe)|0,a=a+Math.imul(K,me)|0,a=a+Math.imul(X,pe)|0,w=w+Math.imul(X,me)|0,m=m+Math.imul(Le,ve)|0,a=a+Math.imul(Le,we)|0,a=a+Math.imul(xe,ve)|0,w=w+Math.imul(xe,we)|0,m=m+Math.imul(Ae,ye)|0,a=a+Math.imul(Ae,be)|0,a=a+Math.imul(Ne,ye)|0,w=w+Math.imul(Ne,be)|0;var Os=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Os>>>26)|0,Os&=67108863,m=Math.imul(Y,pe),a=Math.imul(Y,me),a=a+Math.imul(ee,pe)|0,w=Math.imul(ee,me),m=m+Math.imul(K,ve)|0,a=a+Math.imul(K,we)|0,a=a+Math.imul(X,ve)|0,w=w+Math.imul(X,we)|0,m=m+Math.imul(Le,ye)|0,a=a+Math.imul(Le,be)|0,a=a+Math.imul(xe,ye)|0,w=w+Math.imul(xe,be)|0;var Bs=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Bs>>>26)|0,Bs&=67108863,m=Math.imul(Y,ve),a=Math.imul(Y,we),a=a+Math.imul(ee,ve)|0,w=Math.imul(ee,we),m=m+Math.imul(K,ye)|0,a=a+Math.imul(K,be)|0,a=a+Math.imul(X,ye)|0,w=w+Math.imul(X,be)|0;var Ds=(S+m|0)+((a&8191)<<13)|0;S=(w+(a>>>13)|0)+(Ds>>>26)|0,Ds&=67108863,m=Math.imul(Y,ye),a=Math.imul(Y,be),a=a+Math.imul(ee,ye)|0,w=Math.imul(ee,be);var js=(S+m|0)+((a&8191)<<13)|0;return S=(w+(a>>>13)|0)+(js>>>26)|0,js&=67108863,y[0]=Nt,y[1]=Lt,y[2]=xt,y[3]=Tt,y[4]=Pt,y[5]=$t,y[6]=Ot,y[7]=Bt,y[8]=Dt,y[9]=jt,y[10]=Ft,y[11]=Ht,y[12]=Ut,y[13]=Vt,y[14]=$s,y[15]=Os,y[16]=Bs,y[17]=Ds,y[18]=js,S!==0&&(y[19]=S,d.length++),d};Math.imul||(L=P);function M(_,o,l){l.negative=o.negative^_.negative,l.length=_.length+o.length;for(var d=0,p=0,v=0;v>>26)|0,p+=y>>>26,y&=67108863}l.words[v]=S,d=y,y=p}return d!==0?l.words[v]=d:l.length--,l._strip()}function j(_,o,l){return M(_,o,l)}i.prototype.mulTo=function(o,l){var d,p=this.length+o.length;return this.length===10&&o.length===10?d=L(this,o,l):p<63?d=P(this,o,l):p<1024?d=M(this,o,l):d=j(this,o,l),d},i.prototype.mul=function(o){var l=new i(null);return l.words=new Array(this.length+o.length),this.mulTo(o,l)},i.prototype.mulf=function(o){var l=new i(null);return l.words=new Array(this.length+o.length),j(this,o,l)},i.prototype.imul=function(o){return this.clone().mulTo(o,this)},i.prototype.imuln=function(o){var l=o<0;l&&(o=-o),n(typeof o=="number"),n(o<67108864);for(var d=0,p=0;p>=26,d+=v/67108864|0,d+=y>>>26,this.words[p]=y&67108863}return d!==0&&(this.words[p]=d,this.length++),this.length=o===0?1:this.length,l?this.ineg():this},i.prototype.muln=function(o){return this.clone().imuln(o)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(o){var l=I(o);if(l.length===0)return new i(1);for(var d=this,p=0;p=0);var l=o%26,d=(o-l)/26,p=67108863>>>26-l<<26-l,v;if(l!==0){var y=0;for(v=0;v>>26-l}y&&(this.words[v]=y,this.length++)}if(d!==0){for(v=this.length-1;v>=0;v--)this.words[v+d]=this.words[v];for(v=0;v=0);var p;l?p=(l-l%26)/26:p=0;var v=o%26,y=Math.min((o-v)/26,this.length),S=67108863^67108863>>>v<y)for(this.length-=y,a=0;a=0&&(w!==0||a>=p);a--){var x=this.words[a]|0;this.words[a]=w<<26-v|x>>>v,w=x&S}return m&&w!==0&&(m.words[m.length++]=w),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},i.prototype.ishrn=function(o,l,d){return n(this.negative===0),this.iushrn(o,l,d)},i.prototype.shln=function(o){return this.clone().ishln(o)},i.prototype.ushln=function(o){return this.clone().iushln(o)},i.prototype.shrn=function(o){return this.clone().ishrn(o)},i.prototype.ushrn=function(o){return this.clone().iushrn(o)},i.prototype.testn=function(o){n(typeof o=="number"&&o>=0);var l=o%26,d=(o-l)/26,p=1<=0);var l=o%26,d=(o-l)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=d)return this;if(l!==0&&d++,this.length=Math.min(d,this.length),l!==0){var p=67108863^67108863>>>l<=67108864;l++)this.words[l]-=67108864,l===this.length-1?this.words[l+1]=1:this.words[l+1]++;return this.length=Math.max(this.length,l+1),this},i.prototype.isubn=function(o){if(n(typeof o=="number"),n(o<67108864),o<0)return this.iaddn(-o);if(this.negative!==0)return this.negative=0,this.iaddn(o),this.negative=1,this;if(this.words[0]-=o,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var l=0;l>26)-(m/67108864|0),this.words[v+d]=y&67108863}for(;v>26,this.words[v+d]=y&67108863;if(S===0)return this._strip();for(n(S===-1),S=0,v=0;v>26,this.words[v]=y&67108863;return this.negative=1,this._strip()},i.prototype._wordDiv=function(o,l){var d=this.length-o.length,p=this.clone(),v=o,y=v.words[v.length-1]|0,S=this._countBits(y);d=26-S,d!==0&&(v=v.ushln(d),p.iushln(d),y=v.words[v.length-1]|0);var m=p.length-v.length,a;if(l!=="mod"){a=new i(null),a.length=m+1,a.words=new Array(a.length);for(var w=0;w=0;N--){var O=(p.words[v.length+N]|0)*67108864+(p.words[v.length+N-1]|0);for(O=Math.min(O/y|0,67108863),p._ishlnsubmul(v,O,N);p.negative!==0;)O--,p.negative=0,p._ishlnsubmul(v,1,N),p.isZero()||(p.negative^=1);a&&(a.words[N]=O)}return a&&a._strip(),p._strip(),l!=="div"&&d!==0&&p.iushrn(d),{div:a||null,mod:p}},i.prototype.divmod=function(o,l,d){if(n(!o.isZero()),this.isZero())return{div:new i(0),mod:new i(0)};var p,v,y;return this.negative!==0&&o.negative===0?(y=this.neg().divmod(o,l),l!=="mod"&&(p=y.div.neg()),l!=="div"&&(v=y.mod.neg(),d&&v.negative!==0&&v.iadd(o)),{div:p,mod:v}):this.negative===0&&o.negative!==0?(y=this.divmod(o.neg(),l),l!=="mod"&&(p=y.div.neg()),{div:p,mod:y.mod}):this.negative&o.negative?(y=this.neg().divmod(o.neg(),l),l!=="div"&&(v=y.mod.neg(),d&&v.negative!==0&&v.isub(o)),{div:y.div,mod:v}):o.length>this.length||this.cmp(o)<0?{div:new i(0),mod:this}:o.length===1?l==="div"?{div:this.divn(o.words[0]),mod:null}:l==="mod"?{div:null,mod:new i(this.modrn(o.words[0]))}:{div:this.divn(o.words[0]),mod:new i(this.modrn(o.words[0]))}:this._wordDiv(o,l)},i.prototype.div=function(o){return this.divmod(o,"div",!1).div},i.prototype.mod=function(o){return this.divmod(o,"mod",!1).mod},i.prototype.umod=function(o){return this.divmod(o,"mod",!0).mod},i.prototype.divRound=function(o){var l=this.divmod(o);if(l.mod.isZero())return l.div;var d=l.div.negative!==0?l.mod.isub(o):l.mod,p=o.ushrn(1),v=o.andln(1),y=d.cmp(p);return y<0||v===1&&y===0?l.div:l.div.negative!==0?l.div.isubn(1):l.div.iaddn(1)},i.prototype.modrn=function(o){var l=o<0;l&&(o=-o),n(o<=67108863);for(var d=(1<<26)%o,p=0,v=this.length-1;v>=0;v--)p=(d*p+(this.words[v]|0))%o;return l?-p:p},i.prototype.modn=function(o){return this.modrn(o)},i.prototype.idivn=function(o){var l=o<0;l&&(o=-o),n(o<=67108863);for(var d=0,p=this.length-1;p>=0;p--){var v=(this.words[p]|0)+d*67108864;this.words[p]=v/o|0,d=v%o}return this._strip(),l?this.ineg():this},i.prototype.divn=function(o){return this.clone().idivn(o)},i.prototype.egcd=function(o){n(o.negative===0),n(!o.isZero());var l=this,d=o.clone();l.negative!==0?l=l.umod(o):l=l.clone();for(var p=new i(1),v=new i(0),y=new i(0),S=new i(1),m=0;l.isEven()&&d.isEven();)l.iushrn(1),d.iushrn(1),++m;for(var a=d.clone(),w=l.clone();!l.isZero();){for(var x=0,N=1;!(l.words[0]&N)&&x<26;++x,N<<=1);if(x>0)for(l.iushrn(x);x-- >0;)(p.isOdd()||v.isOdd())&&(p.iadd(a),v.isub(w)),p.iushrn(1),v.iushrn(1);for(var O=0,je=1;!(d.words[0]&je)&&O<26;++O,je<<=1);if(O>0)for(d.iushrn(O);O-- >0;)(y.isOdd()||S.isOdd())&&(y.iadd(a),S.isub(w)),y.iushrn(1),S.iushrn(1);l.cmp(d)>=0?(l.isub(d),p.isub(y),v.isub(S)):(d.isub(l),y.isub(p),S.isub(v))}return{a:y,b:S,gcd:d.iushln(m)}},i.prototype._invmp=function(o){n(o.negative===0),n(!o.isZero());var l=this,d=o.clone();l.negative!==0?l=l.umod(o):l=l.clone();for(var p=new i(1),v=new i(0),y=d.clone();l.cmpn(1)>0&&d.cmpn(1)>0;){for(var S=0,m=1;!(l.words[0]&m)&&S<26;++S,m<<=1);if(S>0)for(l.iushrn(S);S-- >0;)p.isOdd()&&p.iadd(y),p.iushrn(1);for(var a=0,w=1;!(d.words[0]&w)&&a<26;++a,w<<=1);if(a>0)for(d.iushrn(a);a-- >0;)v.isOdd()&&v.iadd(y),v.iushrn(1);l.cmp(d)>=0?(l.isub(d),p.isub(v)):(d.isub(l),v.isub(p))}var x;return l.cmpn(1)===0?x=p:x=v,x.cmpn(0)<0&&x.iadd(o),x},i.prototype.gcd=function(o){if(this.isZero())return o.abs();if(o.isZero())return this.abs();var l=this.clone(),d=o.clone();l.negative=0,d.negative=0;for(var p=0;l.isEven()&&d.isEven();p++)l.iushrn(1),d.iushrn(1);do{for(;l.isEven();)l.iushrn(1);for(;d.isEven();)d.iushrn(1);var v=l.cmp(d);if(v<0){var y=l;l=d,d=y}else if(v===0||d.cmpn(1)===0)break;l.isub(d)}while(!0);return d.iushln(p)},i.prototype.invm=function(o){return this.egcd(o).a.umod(o)},i.prototype.isEven=function(){return(this.words[0]&1)===0},i.prototype.isOdd=function(){return(this.words[0]&1)===1},i.prototype.andln=function(o){return this.words[0]&o},i.prototype.bincn=function(o){n(typeof o=="number");var l=o%26,d=(o-l)/26,p=1<>>26,S&=67108863,this.words[y]=S}return v!==0&&(this.words[y]=v,this.length++),this},i.prototype.isZero=function(){return this.length===1&&this.words[0]===0},i.prototype.cmpn=function(o){var l=o<0;if(this.negative!==0&&!l)return-1;if(this.negative===0&&l)return 1;this._strip();var d;if(this.length>1)d=1;else{l&&(o=-o),n(o<=67108863,"Number is too big");var p=this.words[0]|0;d=p===o?0:po.length)return 1;if(this.length=0;d--){var p=this.words[d]|0,v=o.words[d]|0;if(p!==v){pv&&(l=1);break}}return l},i.prototype.gtn=function(o){return this.cmpn(o)===1},i.prototype.gt=function(o){return this.cmp(o)===1},i.prototype.gten=function(o){return this.cmpn(o)>=0},i.prototype.gte=function(o){return this.cmp(o)>=0},i.prototype.ltn=function(o){return this.cmpn(o)===-1},i.prototype.lt=function(o){return this.cmp(o)===-1},i.prototype.lten=function(o){return this.cmpn(o)<=0},i.prototype.lte=function(o){return this.cmp(o)<=0},i.prototype.eqn=function(o){return this.cmpn(o)===0},i.prototype.eq=function(o){return this.cmp(o)===0},i.red=function(o){return new U(o)},i.prototype.toRed=function(o){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),o.convertTo(this)._forceRed(o)},i.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(o){return this.red=o,this},i.prototype.forceRed=function(o){return n(!this.red,"Already a number in reduction context"),this._forceRed(o)},i.prototype.redAdd=function(o){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,o)},i.prototype.redIAdd=function(o){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,o)},i.prototype.redSub=function(o){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,o)},i.prototype.redISub=function(o){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,o)},i.prototype.redShl=function(o){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,o)},i.prototype.redMul=function(o){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,o),this.red.mul(this,o)},i.prototype.redIMul=function(o){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,o),this.red.imul(this,o)},i.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(o){return n(this.red&&!o.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,o)};var A={k256:null,p224:null,p192:null,p25519:null};function $(_,o){this.name=_,this.p=new i(o,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}$.prototype._tmp=function(){var o=new i(null);return o.words=new Array(Math.ceil(this.n/13)),o},$.prototype.ireduce=function(o){var l=o,d;do this.split(l,this.tmp),l=this.imulK(l),l=l.iadd(this.tmp),d=l.bitLength();while(d>this.n);var p=d0?l.isub(this.p):l.strip!==void 0?l.strip():l._strip(),l},$.prototype.split=function(o,l){o.iushrn(this.n,0,l)},$.prototype.imulK=function(o){return o.imul(this.k)};function J(){$.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}s(J,$),J.prototype.split=function(o,l){for(var d=4194303,p=Math.min(o.length,9),v=0;v>>22,y=S}y>>>=22,o.words[v-10]=y,y===0&&o.length>10?o.length-=10:o.length-=9},J.prototype.imulK=function(o){o.words[o.length]=0,o.words[o.length+1]=0,o.length+=2;for(var l=0,d=0;d>>=26,o.words[d]=v,l=p}return l!==0&&(o.words[o.length++]=l),o},i._prime=function(o){if(A[o])return A[o];var l;if(o==="k256")l=new J;else if(o==="p224")l=new De;else if(o==="p192")l=new Ve;else if(o==="p25519")l=new Q;else throw new Error("Unknown prime "+o);return A[o]=l,l};function U(_){if(typeof _=="string"){var o=i._prime(_);this.m=o.p,this.prime=o}else n(_.gtn(1),"modulus must be greater than 1"),this.m=_,this.prime=null}U.prototype._verify1=function(o){n(o.negative===0,"red works only with positives"),n(o.red,"red works only with red numbers")},U.prototype._verify2=function(o,l){n((o.negative|l.negative)===0,"red works only with positives"),n(o.red&&o.red===l.red,"red works only with red numbers")},U.prototype.imod=function(o){return this.prime?this.prime.ireduce(o)._forceRed(this):(g(o,o.umod(this.m)._forceRed(this)),o)},U.prototype.neg=function(o){return o.isZero()?o.clone():this.m.sub(o)._forceRed(this)},U.prototype.add=function(o,l){this._verify2(o,l);var d=o.add(l);return d.cmp(this.m)>=0&&d.isub(this.m),d._forceRed(this)},U.prototype.iadd=function(o,l){this._verify2(o,l);var d=o.iadd(l);return d.cmp(this.m)>=0&&d.isub(this.m),d},U.prototype.sub=function(o,l){this._verify2(o,l);var d=o.sub(l);return d.cmpn(0)<0&&d.iadd(this.m),d._forceRed(this)},U.prototype.isub=function(o,l){this._verify2(o,l);var d=o.isub(l);return d.cmpn(0)<0&&d.iadd(this.m),d},U.prototype.shl=function(o,l){return this._verify1(o),this.imod(o.ushln(l))},U.prototype.imul=function(o,l){return this._verify2(o,l),this.imod(o.imul(l))},U.prototype.mul=function(o,l){return this._verify2(o,l),this.imod(o.mul(l))},U.prototype.isqr=function(o){return this.imul(o,o.clone())},U.prototype.sqr=function(o){return this.mul(o,o)},U.prototype.sqrt=function(o){if(o.isZero())return o.clone();var l=this.m.andln(3);if(n(l%2===1),l===3){var d=this.m.add(new i(1)).iushrn(2);return this.pow(o,d)}for(var p=this.m.subn(1),v=0;!p.isZero()&&p.andln(1)===0;)v++,p.iushrn(1);n(!p.isZero());var y=new i(1).toRed(this),S=y.redNeg(),m=this.m.subn(1).iushrn(1),a=this.m.bitLength();for(a=new i(2*a*a).toRed(this);this.pow(a,m).cmp(S)!==0;)a.redIAdd(S);for(var w=this.pow(a,p),x=this.pow(o,p.addn(1).iushrn(1)),N=this.pow(o,p),O=v;N.cmp(y)!==0;){for(var je=N,G=0;je.cmp(y)!==0;G++)je=je.redSqr();n(G=0;v--){for(var w=l.words[v],x=a-1;x>=0;x--){var N=w>>x&1;if(y!==p[0]&&(y=this.sqr(y)),N===0&&S===0){m=0;continue}S<<=1,S|=N,m++,!(m!==d&&(v!==0||x!==0))&&(y=this.mul(y,p[S]),m=0,S=0)}a=26}return y},U.prototype.convertTo=function(o){var l=o.umod(this.m);return l===o?l.clone():l},U.prototype.convertFrom=function(o){var l=o.clone();return l.red=null,l},i.mont=function(o){return new q(o)};function q(_){U.call(this,_),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}s(q,U),q.prototype.convertTo=function(o){return this.imod(o.ushln(this.shift))},q.prototype.convertFrom=function(o){var l=this.imod(o.mul(this.rinv));return l.red=null,l},q.prototype.imul=function(o,l){if(o.isZero()||l.isZero())return o.words[0]=0,o.length=1,o;var d=o.imul(l),p=d.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),v=d.isub(p).iushrn(this.shift),y=v;return v.cmp(this.m)>=0?y=v.isub(this.m):v.cmpn(0)<0&&(y=v.iadd(this.m)),y._forceRed(this)},q.prototype.mul=function(o,l){if(o.isZero()||l.isZero())return new i(0)._forceRed(this);var d=o.mul(l),p=d.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),v=d.isub(p).iushrn(this.shift),y=v;return v.cmp(this.m)>=0?y=v.isub(this.m):v.cmpn(0)<0&&(y=v.iadd(this.m)),y._forceRed(this)},q.prototype.invm=function(o){var l=this.imod(o._invmp(this.m).mul(this.r2));return l._forceRed(this)}})(e,B)})(ui);var qn=ui.exports,nn={},St={};Object.defineProperty(St,"__esModule",{value:!0});St.errorValues=St.standardErrorCodes=void 0;St.standardErrorCodes={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901,unsupportedChain:4902}};St.errorValues={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}};var Jn={},Gn={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.serialize=e.getErrorCode=e.isValidCode=e.getMessageFromCode=e.JSON_RPC_SERVER_ERROR_MESSAGE=void 0;const t=St,r="Unspecified error message.";e.JSON_RPC_SERVER_ERROR_MESSAGE="Unspecified server error.";function n(b,k=r){if(b&&Number.isInteger(b)){const C=b.toString();if(g(t.errorValues,C))return t.errorValues[C].message;if(h(b))return e.JSON_RPC_SERVER_ERROR_MESSAGE}return k}e.getMessageFromCode=n;function s(b){if(!Number.isInteger(b))return!1;const k=b.toString();return!!(t.errorValues[k]||h(b))}e.isValidCode=s;function i(b){var k;if(typeof b=="number")return b;if(c(b))return(k=b.code)!==null&&k!==void 0?k:b.errorCode}e.getErrorCode=i;function c(b){return typeof b=="object"&&b!==null&&(typeof b.code=="number"||typeof b.errorCode=="number")}function u(b,{shouldIncludeStack:k=!1}={}){const C={};if(b&&typeof b=="object"&&!Array.isArray(b)&&g(b,"code")&&s(b.code)){const R=b;C.code=R.code,R.message&&typeof R.message=="string"?(C.message=R.message,g(R,"data")&&(C.data=R.data)):(C.message=n(C.code),C.data={originalError:f(b)})}else C.code=t.standardErrorCodes.rpc.internal,C.message=E(b,"message")?b.message:r,C.data={originalError:f(b)};return k&&(C.stack=E(b,"stack")?b.stack:void 0),C}e.serialize=u;function h(b){return b>=-32099&&b<=-32e3}function f(b){return b&&typeof b=="object"&&!Array.isArray(b)?Object.assign({},b):b}function g(b,k){return Object.prototype.hasOwnProperty.call(b,k)}function E(b,k){return typeof b=="object"&&b!==null&&k in b&&typeof b[k]=="string"}})(Gn);Object.defineProperty(Jn,"__esModule",{value:!0});Jn.standardErrors=void 0;const ze=St,aa=Gn;Jn.standardErrors={rpc:{parse:e=>rt(ze.standardErrorCodes.rpc.parse,e),invalidRequest:e=>rt(ze.standardErrorCodes.rpc.invalidRequest,e),invalidParams:e=>rt(ze.standardErrorCodes.rpc.invalidParams,e),methodNotFound:e=>rt(ze.standardErrorCodes.rpc.methodNotFound,e),internal:e=>rt(ze.standardErrorCodes.rpc.internal,e),server:e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:t}=e;if(!Number.isInteger(t)||t>-32005||t<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return rt(t,e)},invalidInput:e=>rt(ze.standardErrorCodes.rpc.invalidInput,e),resourceNotFound:e=>rt(ze.standardErrorCodes.rpc.resourceNotFound,e),resourceUnavailable:e=>rt(ze.standardErrorCodes.rpc.resourceUnavailable,e),transactionRejected:e=>rt(ze.standardErrorCodes.rpc.transactionRejected,e),methodNotSupported:e=>rt(ze.standardErrorCodes.rpc.methodNotSupported,e),limitExceeded:e=>rt(ze.standardErrorCodes.rpc.limitExceeded,e)},provider:{userRejectedRequest:e=>mr(ze.standardErrorCodes.provider.userRejectedRequest,e),unauthorized:e=>mr(ze.standardErrorCodes.provider.unauthorized,e),unsupportedMethod:e=>mr(ze.standardErrorCodes.provider.unsupportedMethod,e),disconnected:e=>mr(ze.standardErrorCodes.provider.disconnected,e),chainDisconnected:e=>mr(ze.standardErrorCodes.provider.chainDisconnected,e),unsupportedChain:e=>mr(ze.standardErrorCodes.provider.unsupportedChain,e),custom:e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:t,message:r,data:n}=e;if(!r||typeof r!="string")throw new Error('"message" must be a nonempty string');return new ua(t,r,n)}}};function rt(e,t){const[r,n]=ca(t);return new la(e,r||(0,aa.getMessageFromCode)(e),n)}function mr(e,t){const[r,n]=ca(t);return new ua(e,r||(0,aa.getMessageFromCode)(e),n)}function ca(e){if(e){if(typeof e=="string")return[e];if(typeof e=="object"&&!Array.isArray(e)){const{message:t,data:r}=e;if(t&&typeof t!="string")throw new Error("Must specify string message.");return[t||void 0,r]}}return[]}let la=class extends Error{constructor(t,r,n){if(!Number.isInteger(t))throw new Error('"code" must be an integer.');if(!r||typeof r!="string")throw new Error('"message" must be a nonempty string.');super(r),this.code=t,n!==void 0&&(this.data=n)}},ua=class extends la{constructor(t,r,n){if(!Gc(t))throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');super(t,r,n)}};function Gc(e){return Number.isInteger(e)&&e>=1e3&&e<=4999}var Zn={},Pr={};Object.defineProperty(Pr,"__esModule",{value:!0});Pr.isErrorResponse=void 0;function Zc(e){return e.errorMessage!==void 0}Pr.isErrorResponse=Zc;var $r={};Object.defineProperty($r,"__esModule",{value:!0});$r.LIB_VERSION=void 0;$r.LIB_VERSION="3.9.3";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.serializeError=void 0;const Qc=Pr,Kc=$r,Xc=St,Yc=Gn;function el(e,t){const r=(0,Yc.serialize)(tl(e),{shouldIncludeStack:!0}),n=new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors");n.searchParams.set("version",Kc.LIB_VERSION),n.searchParams.set("code",r.code.toString());const s=rl(r.data,t);return s&&n.searchParams.set("method",s),n.searchParams.set("message",r.message),Object.assign(Object.assign({},r),{docUrl:n.href})}Zn.serializeError=el;function tl(e){return typeof e=="string"?{message:e,code:Xc.standardErrorCodes.rpc.internal}:(0,Qc.isErrorResponse)(e)?Object.assign(Object.assign({},e),{message:e.errorMessage,code:e.errorCode,data:{method:e.method}}):e}function rl(e,t){const r=e?.method;if(r)return r;if(t!==void 0){if(typeof t=="string")return t;if(Array.isArray(t)){if(t.length>0)return t[0].method}else return t.method}}(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.standardErrors=e.standardErrorCodes=e.serializeError=e.getMessageFromCode=e.getErrorCode=void 0;const t=St;Object.defineProperty(e,"standardErrorCodes",{enumerable:!0,get:function(){return t.standardErrorCodes}});const r=Jn;Object.defineProperty(e,"standardErrors",{enumerable:!0,get:function(){return r.standardErrors}});const n=Zn;Object.defineProperty(e,"serializeError",{enumerable:!0,get:function(){return n.serializeError}});const s=Gn;Object.defineProperty(e,"getErrorCode",{enumerable:!0,get:function(){return s.getErrorCode}}),Object.defineProperty(e,"getMessageFromCode",{enumerable:!0,get:function(){return s.getMessageFromCode}})})(nn);var Fe={};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.ProviderType=Fe.RegExpString=Fe.IntNumber=Fe.BigIntString=Fe.AddressString=Fe.HexString=Fe.OpaqueType=void 0;function sn(){return e=>e}Fe.OpaqueType=sn;Fe.HexString=sn();Fe.AddressString=sn();Fe.BigIntString=sn();function nl(e){return Math.floor(e)}Fe.IntNumber=nl;Fe.RegExpString=sn();var Ji;(function(e){e.CoinbaseWallet="CoinbaseWallet",e.MetaMask="MetaMask",e.Unselected=""})(Ji||(Fe.ProviderType=Ji={}));var sl=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(T,"__esModule",{value:!0});T.isMobileWeb=T.getLocation=T.isInIFrame=T.createQrUrl=T.getFavicon=T.range=T.isBigNumber=T.ensureParsedJSONObject=T.ensureBN=T.ensureRegExpString=T.ensureIntNumber=T.ensureBuffer=T.ensureAddressString=T.ensureEvenLengthHexString=T.ensureHexString=T.isHexString=T.prepend0x=T.strip0x=T.has0xPrefix=T.hexStringFromIntNumber=T.intNumberFromHexString=T.bigIntStringFromBN=T.hexStringFromBuffer=T.hexStringToUint8Array=T.uint8ArrayToHex=T.randomBytesHex=void 0;const Rt=sl(qn),tr=nn,ot=Fe,ha=/^[0-9]*$/,da=/^[a-f0-9]*$/;function il(e){return fa(crypto.getRandomValues(new Uint8Array(e)))}T.randomBytesHex=il;function fa(e){return[...e].map(t=>t.toString(16).padStart(2,"0")).join("")}T.uint8ArrayToHex=fa;function ol(e){return new Uint8Array(e.match(/.{1,2}/g).map(t=>parseInt(t,16)))}T.hexStringToUint8Array=ol;function al(e,t=!1){const r=e.toString("hex");return(0,ot.HexString)(t?`0x${r}`:r)}T.hexStringFromBuffer=al;function cl(e){return(0,ot.BigIntString)(e.toString(10))}T.bigIntStringFromBN=cl;function ll(e){return(0,ot.IntNumber)(new Rt.default(an(e,!1),16).toNumber())}T.intNumberFromHexString=ll;function ul(e){return(0,ot.HexString)(`0x${new Rt.default(e).toString(16)}`)}T.hexStringFromIntNumber=ul;function hi(e){return e.startsWith("0x")||e.startsWith("0X")}T.has0xPrefix=hi;function Qn(e){return hi(e)?e.slice(2):e}T.strip0x=Qn;function ga(e){return hi(e)?`0x${e.slice(2)}`:`0x${e}`}T.prepend0x=ga;function on(e){if(typeof e!="string")return!1;const t=Qn(e).toLowerCase();return da.test(t)}T.isHexString=on;function pa(e,t=!1){if(typeof e=="string"){const r=Qn(e).toLowerCase();if(da.test(r))return(0,ot.HexString)(t?`0x${r}`:r)}throw tr.standardErrors.rpc.invalidParams(`"${String(e)}" is not a hexadecimal string`)}T.ensureHexString=pa;function an(e,t=!1){let r=pa(e,!1);return r.length%2===1&&(r=(0,ot.HexString)(`0${r}`)),t?(0,ot.HexString)(`0x${r}`):r}T.ensureEvenLengthHexString=an;function hl(e){if(typeof e=="string"){const t=Qn(e).toLowerCase();if(on(t)&&t.length===40)return(0,ot.AddressString)(ga(t))}throw tr.standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(e)}`)}T.ensureAddressString=hl;function dl(e){if(Buffer.isBuffer(e))return e;if(typeof e=="string"){if(on(e)){const t=an(e,!1);return Buffer.from(t,"hex")}return Buffer.from(e,"utf8")}throw tr.standardErrors.rpc.invalidParams(`Not binary data: ${String(e)}`)}T.ensureBuffer=dl;function ma(e){if(typeof e=="number"&&Number.isInteger(e))return(0,ot.IntNumber)(e);if(typeof e=="string"){if(ha.test(e))return(0,ot.IntNumber)(Number(e));if(on(e))return(0,ot.IntNumber)(new Rt.default(an(e,!1),16).toNumber())}throw tr.standardErrors.rpc.invalidParams(`Not an integer: ${String(e)}`)}T.ensureIntNumber=ma;function fl(e){if(e instanceof RegExp)return(0,ot.RegExpString)(e.toString());throw tr.standardErrors.rpc.invalidParams(`Not a RegExp: ${String(e)}`)}T.ensureRegExpString=fl;function gl(e){if(e!==null&&(Rt.default.isBN(e)||va(e)))return new Rt.default(e.toString(10),10);if(typeof e=="number")return new Rt.default(ma(e));if(typeof e=="string"){if(ha.test(e))return new Rt.default(e,10);if(on(e))return new Rt.default(an(e,!1),16)}throw tr.standardErrors.rpc.invalidParams(`Not an integer: ${String(e)}`)}T.ensureBN=gl;function pl(e){if(typeof e=="string")return JSON.parse(e);if(typeof e=="object")return e;throw tr.standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(e)}`)}T.ensureParsedJSONObject=pl;function va(e){if(e==null||typeof e.constructor!="function")return!1;const{constructor:t}=e;return typeof t.config=="function"&&typeof t.EUCLID=="number"}T.isBigNumber=va;function ml(e,t){return Array.from({length:t-e},(r,n)=>e+n)}T.range=ml;function vl(){const e=document.querySelector('link[sizes="192x192"]')||document.querySelector('link[sizes="180x180"]')||document.querySelector('link[rel="icon"]')||document.querySelector('link[rel="shortcut icon"]'),{protocol:t,host:r}=document.location,n=e?e.getAttribute("href"):null;return!n||n.startsWith("javascript:")||n.startsWith("vbscript:")?null:n.startsWith("http://")||n.startsWith("https://")||n.startsWith("data:")?n:n.startsWith("//")?t+n:`${t}//${r}${n}`}T.getFavicon=vl;function wl(e,t,r,n,s,i){const c=n?"parent-id":"id",u=new URLSearchParams({[c]:e,secret:t,server:r,v:s,chainId:i.toString()}).toString();return`${r}/#/link?${u}`}T.createQrUrl=wl;function wa(){try{return window.frameElement!==null}catch{return!1}}T.isInIFrame=wa;function yl(){try{return wa()&&window.top?window.top.location:window.location}catch{return window.location}}T.getLocation=yl;function bl(){var e;return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((e=window?.navigator)===null||e===void 0?void 0:e.userAgent)}T.isMobileWeb=bl;var Kn={};Object.defineProperty(Kn,"__esModule",{value:!0});Kn.ScopedLocalStorage=void 0;class _l{constructor(t){this.scope=t}setItem(t,r){localStorage.setItem(this.scopedKey(t),r)}getItem(t){return localStorage.getItem(this.scopedKey(t))}removeItem(t){localStorage.removeItem(this.scopedKey(t))}clear(){const t=this.scopedKey(""),r=[];for(let n=0;nlocalStorage.removeItem(n))}scopedKey(t){return`${this.scope}:${t}`}}Kn.ScopedLocalStorage=_l;var Cr={},ya={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function s(h,f,g){this.fn=h,this.context=f,this.once=g||!1}function i(h,f,g,E,b){if(typeof g!="function")throw new TypeError("The listener must be a function");var k=new s(g,E||h,b),C=r?r+f:f;return h._events[C]?h._events[C].fn?h._events[C]=[h._events[C],k]:h._events[C].push(k):(h._events[C]=k,h._eventsCount++),h}function c(h,f){--h._eventsCount===0?h._events=new n:delete h._events[f]}function u(){this._events=new n,this._eventsCount=0}u.prototype.eventNames=function(){var f=[],g,E;if(this._eventsCount===0)return f;for(E in g=this._events)t.call(g,E)&&f.push(r?E.slice(1):E);return Object.getOwnPropertySymbols?f.concat(Object.getOwnPropertySymbols(g)):f},u.prototype.listeners=function(f){var g=r?r+f:f,E=this._events[g];if(!E)return[];if(E.fn)return[E.fn];for(var b=0,k=E.length,C=new Array(k);bn.json()).then(n=>{if(!n)throw Gi.standardErrors.rpc.parse({});const s=n,{error:i}=s;if(i)throw(0,Gi.serializeError)(i,t.method);return s})}}it.RelayAbstract=Sl;var Br={};Object.defineProperty(Br,"__esModule",{value:!0});Br.Session=void 0;const Zi=zc,Qi=T,Ki="session:id",Xi="session:secret",Yi="session:linked";class di{constructor(t,r,n,s){this._storage=t,this._id=r||(0,Qi.randomBytesHex)(16),this._secret=n||(0,Qi.randomBytesHex)(32),this._key=new Zi.sha256().update(`${this._id}, ${this._secret} WalletLink`).digest("hex"),this._linked=!!s}static load(t){const r=t.getItem(Ki),n=t.getItem(Yi),s=t.getItem(Xi);return r&&s?new di(t,r,s,n==="1"):null}static hash(t){return new Zi.sha256().update(t).digest("hex")}get id(){return this._id}get secret(){return this._secret}get key(){return this._key}get linked(){return this._linked}set linked(t){this._linked=t,this.persistLinked()}save(){return this._storage.setItem(Ki,this._id),this._storage.setItem(Xi,this._secret),this.persistLinked(),this}persistLinked(){this._storage.setItem(Yi,this._linked?"1":"0")}}Br.Session=di;var Xn={},Yn={};Object.defineProperty(Yn,"__esModule",{value:!0});Yn.Cipher=void 0;const Mn=T;class kl{constructor(t){this.secret=t}async encrypt(t){const r=this.secret;if(r.length!==64)throw Error("secret must be 256 bits");const n=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.importKey("raw",(0,Mn.hexStringToUint8Array)(r),{name:"aes-gcm"},!1,["encrypt","decrypt"]),i=new TextEncoder,c=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:n},s,i.encode(t)),u=16,h=c.slice(c.byteLength-u),f=c.slice(0,c.byteLength-u),g=new Uint8Array(h),E=new Uint8Array(f),b=new Uint8Array([...n,...g,...E]);return(0,Mn.uint8ArrayToHex)(b)}async decrypt(t){const r=this.secret;if(r.length!==64)throw Error("secret must be 256 bits");return new Promise((n,s)=>{(async function(){const i=await crypto.subtle.importKey("raw",(0,Mn.hexStringToUint8Array)(r),{name:"aes-gcm"},!1,["encrypt","decrypt"]),c=(0,Mn.hexStringToUint8Array)(t),u=c.slice(0,12),h=c.slice(12,28),f=c.slice(28),g=new Uint8Array([...f,...h]),E={name:"AES-GCM",iv:new Uint8Array(u)};try{const b=await window.crypto.subtle.decrypt(E,i,g),k=new TextDecoder;n(k.decode(b))}catch(b){s(b)}})()})}}Yn.Cipher=kl;var es={};Object.defineProperty(es,"__esModule",{value:!0});es.WalletLinkHTTP=void 0;class Ml{constructor(t,r,n){this.linkAPIUrl=t,this.sessionId=r;const s=`${r}:${n}`;this.auth=`Basic ${btoa(s)}`}async markUnseenEventsAsSeen(t){return Promise.all(t.map(r=>fetch(`${this.linkAPIUrl}/events/${r.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(r=>console.error("Unabled to mark event as failed:",r))}async fetchUnseenEvents(){var t;const r=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(r.ok){const{events:n,error:s}=await r.json();if(s)throw new Error(`Check unseen events failed: ${s}`);const i=(t=n?.filter(c=>c.event==="Web3Response").map(c=>({type:"Event",sessionId:this.sessionId,eventId:c.id,event:c.event,data:c.data})))!==null&&t!==void 0?t:[];return this.markUnseenEventsAsSeen(i),i}throw new Error(`Check unseen events failed: ${r.status}`)}}es.WalletLinkHTTP=Ml;var Ar={};Object.defineProperty(Ar,"__esModule",{value:!0});Ar.WalletLinkWebSocket=Ar.ConnectionState=void 0;var Sr;(function(e){e[e.DISCONNECTED=0]="DISCONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED"})(Sr||(Ar.ConnectionState=Sr={}));class Rl{setConnectionStateListener(t){this.connectionStateListener=t}setIncomingDataListener(t){this.incomingDataListener=t}constructor(t,r=WebSocket){this.WebSocketClass=r,this.webSocket=null,this.pendingData=[],this.url=t.replace(/^http/,"ws")}async connect(){if(this.webSocket)throw new Error("webSocket object is not null");return new Promise((t,r)=>{var n;let s;try{this.webSocket=s=new this.WebSocketClass(this.url)}catch(i){r(i);return}(n=this.connectionStateListener)===null||n===void 0||n.call(this,Sr.CONNECTING),s.onclose=i=>{var c;this.clearWebSocket(),r(new Error(`websocket error ${i.code}: ${i.reason}`)),(c=this.connectionStateListener)===null||c===void 0||c.call(this,Sr.DISCONNECTED)},s.onopen=i=>{var c;t(),(c=this.connectionStateListener)===null||c===void 0||c.call(this,Sr.CONNECTED),this.pendingData.length>0&&([...this.pendingData].forEach(h=>this.sendData(h)),this.pendingData=[])},s.onmessage=i=>{var c,u;if(i.data==="h")(c=this.incomingDataListener)===null||c===void 0||c.call(this,{type:"Heartbeat"});else try{const h=JSON.parse(i.data);(u=this.incomingDataListener)===null||u===void 0||u.call(this,h)}catch{}}})}disconnect(){var t;const{webSocket:r}=this;if(r){this.clearWebSocket(),(t=this.connectionStateListener)===null||t===void 0||t.call(this,Sr.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{r.close()}catch{}}}sendData(t){const{webSocket:r}=this;if(!r){this.pendingData.push(t),this.connect();return}r.send(t)}clearWebSocket(){const{webSocket:t}=this;t&&(this.webSocket=null,t.onclose=null,t.onerror=null,t.onmessage=null,t.onopen=null)}}Ar.WalletLinkWebSocket=Rl;Object.defineProperty(Xn,"__esModule",{value:!0});Xn.WalletLinkConnection=void 0;const vr=Fe,Il=Yn,dt=Or,eo=it,wr=Br,Cl=es,Rn=Ar,to=1e4,Al=6e4;class Nl{constructor({session:t,linkAPIUrl:r,listener:n,diagnostic:s,WebSocketClass:i=WebSocket}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=(0,vr.IntNumber)(1),this._connected=!1,this._linked=!1,this.shouldFetchUnseenEventsOnConnect=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=u=>{if(!u)return;new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",f=>u.JsonRpcUrl&&this.handleChainUpdated(f,u.JsonRpcUrl)]]).forEach((f,g)=>{const E=u[g];E!==void 0&&f(E)})},this.handleDestroyed=u=>{var h,f;u==="1"&&((h=this.listener)===null||h===void 0||h.resetAndReload(),(f=this.diagnostic)===null||f===void 0||f.log(dt.EVENTS.METADATA_DESTROYED,{alreadyDestroyed:this.isDestroyed,sessionIdHash:wr.Session.hash(this.session.id)}))},this.handleAccountUpdated=async u=>{var h,f;try{const g=await this.cipher.decrypt(u);(h=this.listener)===null||h===void 0||h.accountUpdated(g)}catch{(f=this.diagnostic)===null||f===void 0||f.log(dt.EVENTS.GENERAL_ERROR,{message:"Had error decrypting",value:"selectedAddress"})}},this.handleMetadataUpdated=async(u,h)=>{var f,g;try{const E=await this.cipher.decrypt(h);(f=this.listener)===null||f===void 0||f.metadataUpdated(u,E)}catch{(g=this.diagnostic)===null||g===void 0||g.log(dt.EVENTS.GENERAL_ERROR,{message:"Had error decrypting",value:u})}},this.handleWalletUsernameUpdated=async u=>{this.handleMetadataUpdated(eo.WALLET_USER_NAME_KEY,u)},this.handleAppVersionUpdated=async u=>{this.handleMetadataUpdated(eo.APP_VERSION_KEY,u)},this.handleChainUpdated=async(u,h)=>{var f,g;try{const E=await this.cipher.decrypt(u),b=await this.cipher.decrypt(h);(f=this.listener)===null||f===void 0||f.chainUpdated(E,b)}catch{(g=this.diagnostic)===null||g===void 0||g.log(dt.EVENTS.GENERAL_ERROR,{message:"Had error decrypting",value:"chainId|jsonRpcUrl"})}},this.session=t,this.cipher=new Il.Cipher(t.secret),this.diagnostic=s,this.listener=n;const c=new Rn.WalletLinkWebSocket(`${r}/rpc`,i);c.setConnectionStateListener(async u=>{var h;(h=this.diagnostic)===null||h===void 0||h.log(dt.EVENTS.CONNECTED_STATE_CHANGE,{state:u,sessionIdHash:wr.Session.hash(t.id)});let f=!1;switch(u){case Rn.ConnectionState.DISCONNECTED:if(!this.destroyed){const g=async()=>{await new Promise(E=>setTimeout(E,5e3)),this.destroyed||c.connect().catch(()=>{g()})};g()}break;case Rn.ConnectionState.CONNECTED:try{await this.authenticate(),this.sendIsLinked(),this.sendGetSessionConfig(),f=!0}catch{}this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},to),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();break;case Rn.ConnectionState.CONNECTING:break}this.connected!==f&&(this.connected=f)}),c.setIncomingDataListener(u=>{var h,f,g;switch(u.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{const E=u.type==="IsLinkedOK"?u.linked:void 0;(h=this.diagnostic)===null||h===void 0||h.log(dt.EVENTS.LINKED,{sessionIdHash:wr.Session.hash(t.id),linked:E,type:u.type,onlineGuests:u.onlineGuests}),this.linked=E||u.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":{(f=this.diagnostic)===null||f===void 0||f.log(dt.EVENTS.SESSION_CONFIG_RECEIVED,{sessionIdHash:wr.Session.hash(t.id),metadata_keys:u&&u.metadata?Object.keys(u.metadata):void 0}),this.handleSessionMetadataUpdated(u.metadata);break}case"Event":{this.handleIncomingEvent(u);break}}u.id!==void 0&&((g=this.requestResolutions.get(u.id))===null||g===void 0||g(u))}),this.ws=c,this.http=new Cl.WalletLinkHTTP(r,t.id,t.key)}connect(){var t;if(this.destroyed)throw new Error("instance is destroyed");(t=this.diagnostic)===null||t===void 0||t.log(dt.EVENTS.STARTED_CONNECTING,{sessionIdHash:wr.Session.hash(this.session.id)}),this.ws.connect()}destroy(){var t;this.destroyed=!0,this.ws.disconnect(),(t=this.diagnostic)===null||t===void 0||t.log(dt.EVENTS.DISCONNECTED,{sessionIdHash:wr.Session.hash(this.session.id)}),this.listener=void 0}get isDestroyed(){return this.destroyed}get connected(){return this._connected}set connected(t){var r,n;this._connected=t,t&&((r=this.onceConnected)===null||r===void 0||r.call(this)),(n=this.listener)===null||n===void 0||n.connectedUpdated(t)}setOnceConnected(t){return new Promise(r=>{this.connected?t().then(r):this.onceConnected=()=>{t().then(r),this.onceConnected=void 0}})}get linked(){return this._linked}set linked(t){var r,n;this._linked=t,t&&((r=this.onceLinked)===null||r===void 0||r.call(this)),(n=this.listener)===null||n===void 0||n.linkedUpdated(t)}setOnceLinked(t){return new Promise(r=>{this.linked?t().then(r):this.onceLinked=()=>{t().then(r),this.onceLinked=void 0}})}async handleIncomingEvent(t){var r,n;if(!(t.type!=="Event"||t.event!=="Web3Response"))try{const s=await this.cipher.decrypt(t.data),i=JSON.parse(s);if(i.type!=="WEB3_RESPONSE")return;(r=this.listener)===null||r===void 0||r.handleWeb3ResponseMessage(i)}catch{(n=this.diagnostic)===null||n===void 0||n.log(dt.EVENTS.GENERAL_ERROR,{message:"Had error decrypting",value:"incomingEvent"})}}async checkUnseenEvents(){if(!this.connected){this.shouldFetchUnseenEventsOnConnect=!0;return}await new Promise(t=>setTimeout(t,250));try{await this.fetchUnseenEventsAPI()}catch(t){console.error("Unable to check for unseen events",t)}}async fetchUnseenEventsAPI(){this.shouldFetchUnseenEventsOnConnect=!1,(await this.http.fetchUnseenEvents()).forEach(r=>this.handleIncomingEvent(r))}async setSessionMetadata(t,r){const n={type:"SetSessionConfig",id:(0,vr.IntNumber)(this.nextReqId++),sessionId:this.session.id,metadata:{[t]:r}};return this.setOnceConnected(async()=>{const s=await this.makeRequest(n);if(s.type==="Fail")throw new Error(s.error||"failed to set session metadata")})}async publishEvent(t,r,n=!1){const s=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},r),{origin:location.origin,relaySource:window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),i={type:"PublishEvent",id:(0,vr.IntNumber)(this.nextReqId++),sessionId:this.session.id,event:t,data:s,callWebhook:n};return this.setOnceLinked(async()=>{const c=await this.makeRequest(i);if(c.type==="Fail")throw new Error(c.error||"failed to publish event");return c.eventId})}sendData(t){this.ws.sendData(JSON.stringify(t))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>to*2){this.ws.disconnect();return}try{this.ws.sendData("h")}catch{}}async makeRequest(t,r=Al){const n=t.id;this.sendData(t);let s;return Promise.race([new Promise((i,c)=>{s=window.setTimeout(()=>{c(new Error(`request ${n} timed out`))},r)}),new Promise(i=>{this.requestResolutions.set(n,c=>{clearTimeout(s),i(c),this.requestResolutions.delete(n)})})])}async authenticate(){const t={type:"HostSession",id:(0,vr.IntNumber)(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key},r=await this.makeRequest(t);if(r.type==="Fail")throw new Error(r.error||"failed to authentcate")}sendIsLinked(){const t={type:"IsLinked",id:(0,vr.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(t)}sendGetSessionConfig(){const t={type:"GetSessionConfig",id:(0,vr.IntNumber)(this.nextReqId++),sessionId:this.session.id};this.sendData(t)}}Xn.WalletLinkConnection=Nl;var un={},hn={},fi={};Object.defineProperty(fi,"__esModule",{value:!0});fi.default='@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}';var Ll=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(hn,"__esModule",{value:!0});hn.injectCssReset=void 0;const xl=Ll(fi);function Tl(){const e=document.createElement("style");e.type="text/css",e.appendChild(document.createTextNode(xl.default)),document.documentElement.appendChild(e)}hn.injectCssReset=Tl;var ts={};const Ke=rn(Wc);var rs={};function ba(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;t65536?(n[0]=240|(s&1835008)>>>18,n[1]=128|(s&258048)>>>12,n[2]=128|(s&4032)>>>6,n[3]=128|s&63):s>2048?(n[0]=224|(s&61440)>>>12,n[1]=128|(s&4032)>>>6,n[2]=128|s&63):s>128?(n[0]=192|(s&1984)>>>6,n[1]=128|s&63):n[0]=s,this.parsedData.push(n)}this.parsedData=Array.prototype.concat.apply([],this.parsedData),this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}_a.prototype={getLength:function(e){return this.parsedData.length},write:function(e){for(var t=0,r=this.parsedData.length;t=7&&this.setupTypeNumber(e),this.dataCache==null&&(this.dataCache=wt.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)},setupPositionProbePattern:function(e,t){for(var r=-1;r<=7;r++)if(!(e+r<=-1||this.moduleCount<=e+r))for(var n=-1;n<=7;n++)t+n<=-1||this.moduleCount<=t+n||(0<=r&&r<=6&&(n==0||n==6)||0<=n&&n<=6&&(r==0||r==6)||2<=r&&r<=4&&2<=n&&n<=4?this.modules[e+r][t+n]=!0:this.modules[e+r][t+n]=!1)},getBestMaskPattern:function(){for(var e=0,t=0,r=0;r<8;r++){this.makeImpl(!0,r);var n=Pe.getLostPoint(this);(r==0||e>n)&&(e=n,t=r)}return t},createMovieClip:function(e,t,r){var n=e.createEmptyMovieClip(t,r),s=1;this.make();for(var i=0;i>r&1)==1;this.modules[Math.floor(r/3)][r%3+this.moduleCount-8-3]=n}for(var r=0;r<18;r++){var n=!e&&(t>>r&1)==1;this.modules[r%3+this.moduleCount-8-3][Math.floor(r/3)]=n}},setupTypeInfo:function(e,t){for(var r=this.errorCorrectLevel<<3|t,n=Pe.getBCHTypeInfo(r),s=0;s<15;s++){var i=!e&&(n>>s&1)==1;s<6?this.modules[s][8]=i:s<8?this.modules[s+1][8]=i:this.modules[this.moduleCount-15+s][8]=i}for(var s=0;s<15;s++){var i=!e&&(n>>s&1)==1;s<8?this.modules[8][this.moduleCount-s-1]=i:s<9?this.modules[8][15-s-1+1]=i:this.modules[8][15-s-1]=i}this.modules[this.moduleCount-8][8]=!e},mapData:function(e,t){for(var r=-1,n=this.moduleCount-1,s=7,i=0,c=this.moduleCount-1;c>0;c-=2)for(c==6&&c--;;){for(var u=0;u<2;u++)if(this.modules[n][c-u]==null){var h=!1;i>>s&1)==1);var f=Pe.getMask(t,n,c-u);f&&(h=!h),this.modules[n][c-u]=h,s--,s==-1&&(i++,s=7)}if(n+=r,n<0||this.moduleCount<=n){n-=r,r=-r;break}}}};wt.PAD0=236;wt.PAD1=17;wt.createData=function(e,t,r){for(var n=vt.getRSBlocks(e,t),s=new Ea,i=0;iu*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+u*8+")");for(s.getLengthInBits()+4<=u*8&&s.put(0,4);s.getLengthInBits()%8!=0;)s.putBit(!1);for(;!(s.getLengthInBits()>=u*8||(s.put(wt.PAD0,8),s.getLengthInBits()>=u*8));)s.put(wt.PAD1,8);return wt.createBytes(s,n)};wt.createBytes=function(e,t){for(var r=0,n=0,s=0,i=new Array(t.length),c=new Array(t.length),u=0;u=0?k.get(C):0}}for(var R=0,g=0;g=0;)t^=Pe.G15<=0;)t^=Pe.G18<>>=1;return t},getPatternPosition:function(e){return Pe.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,r){switch(e){case kt.PATTERN000:return(t+r)%2==0;case kt.PATTERN001:return t%2==0;case kt.PATTERN010:return r%3==0;case kt.PATTERN011:return(t+r)%3==0;case kt.PATTERN100:return(Math.floor(t/2)+Math.floor(r/3))%2==0;case kt.PATTERN101:return t*r%2+t*r%3==0;case kt.PATTERN110:return(t*r%2+t*r%3)%2==0;case kt.PATTERN111:return(t*r%3+(t+r)%2)%2==0;default:throw new Error("bad maskPattern:"+e)}},getErrorCorrectPolynomial:function(e){for(var t=new kr([1],0),r=0;r5&&(r+=3+i-5)}for(var n=0;n=256;)e-=255;return Ue.EXP_TABLE[e]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var We=0;We<8;We++)Ue.EXP_TABLE[We]=1<>>7-e%8&1)==1},put:function(e,t){for(var r=0;r>>t-r-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){var t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var Fs=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]];function Sa(e){if(this.options={padding:4,width:256,height:256,typeNumber:4,color:"#000000",background:"#ffffff",ecl:"M",image:{svg:"",width:0,height:0}},typeof e=="string"&&(e={content:e}),e)for(var t in e)this.options[t]=e[t];if(typeof this.options.content!="string")throw new Error("Expected 'content' as string!");if(this.options.content.length===0)throw new Error("Expected 'content' to be non-empty!");if(!(this.options.padding>=0))throw new Error("Expected 'padding' value to be non-negative!");if(!(this.options.width>0)||!(this.options.height>0))throw new Error("Expected 'width' or 'height' value to be higher than zero!");function r(h){switch(h){case"L":return It.L;case"M":return It.M;case"Q":return It.Q;case"H":return It.H;default:throw new Error("Unknwon error correction level: "+h)}}function n(h,f){for(var g=s(h),E=1,b=0,k=0,C=Fs.length;k<=C;k++){var R=Fs[k];if(!R)throw new Error("Content too long: expected "+b+" but got "+g);switch(f){case"L":b=R[0];break;case"M":b=R[1];break;case"Q":b=R[2];break;case"H":b=R[3];break;default:throw new Error("Unknwon error correction level: "+f)}if(g<=b)break;E++}if(E>Fs.length)throw new Error("Content too long");return E}function s(h){var f=encodeURI(h).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return f.length+(f.length!=h?3:0)}var i=this.options.content,c=n(i,this.options.ecl),u=r(this.options.ecl);this.qrcode=new wt(c,u),this.qrcode.addData(i),this.qrcode.make()}Sa.prototype.svg=function(e){var t=this.options||{},r=this.qrcode.modules;typeof e>"u"&&(e={container:t.container||"svg"});for(var n=typeof t.pretty<"u"?!!t.pretty:!0,s=n?" ":"",i=n?`\r +`:"",c=t.width,u=t.height,h=r.length,f=c/(h+2*t.padding),g=u/(h+2*t.padding),E=typeof t.join<"u"?!!t.join:!1,b=typeof t.swap<"u"?!!t.swap:!1,k=typeof t.xmlDeclaration<"u"?!!t.xmlDeclaration:!0,C=typeof t.predefined<"u"?!!t.predefined:!1,R=C?s+''+i:"",I=s+''+i,P="",L="",M=0;M'+i:P+=s+''+i}}E&&(P=s+'');let U="";if(this.options.image!==void 0&&this.options.image.svg){const _=c*this.options.image.width/100,o=u*this.options.image.height/100,l=c/2-_/2,d=u/2-o/2;U+=``,U+=this.options.image.svg+i,U+=""}var q="";switch(e.container){case"svg":k&&(q+=''+i),q+=''+i,q+=R+I+P,q+=U,q+="";break;case"svg-viewbox":k&&(q+=''+i),q+=''+i,q+=R+I+P,q+=U,q+="";break;case"g":q+=''+i,q+=R+I+P,q+=U,q+="";break;default:q+=(R+I+P+U).replace(/^\s+/,"");break}return q};var Dl=Sa,jl=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(as,"__esModule",{value:!0});as.QRCode=void 0;const Fl=Ke,so=ns,Hl=jl(Dl),Ul=e=>{const[t,r]=(0,so.useState)("");return(0,so.useEffect)(()=>{var n,s;const i=new Hl.default({content:e.content,background:e.bgColor||"#ffffff",color:e.fgColor||"#000000",container:"svg",ecl:"M",width:(n=e.width)!==null&&n!==void 0?n:256,height:(s=e.height)!==null&&s!==void 0?s:256,padding:0,image:e.image}),c=Buffer.from(i.svg(),"utf8").toString("base64");r(`data:image/svg+xml;base64,${c}`)},[e.bgColor,e.content,e.fgColor,e.height,e.image,e.width]),t?(0,Fl.h)("img",{src:t,alt:"QR Code"}):null};as.QRCode=Ul;var cs={},gi={};Object.defineProperty(gi,"__esModule",{value:!0});gi.default=".-cbwsdk-css-reset .-cbwsdk-spinner{display:inline-block}.-cbwsdk-css-reset .-cbwsdk-spinner svg{display:inline-block;animation:2s linear infinite -cbwsdk-spinner-svg}.-cbwsdk-css-reset .-cbwsdk-spinner svg circle{animation:1.9s ease-in-out infinite both -cbwsdk-spinner-circle;display:block;fill:rgba(0,0,0,0);stroke-dasharray:283;stroke-dashoffset:280;stroke-linecap:round;stroke-width:10px;transform-origin:50% 50%}@keyframes -cbwsdk-spinner-svg{0%{transform:rotateZ(0deg)}100%{transform:rotateZ(360deg)}}@keyframes -cbwsdk-spinner-circle{0%,25%{stroke-dashoffset:280;transform:rotate(0)}50%,75%{stroke-dashoffset:75;transform:rotate(45deg)}100%{stroke-dashoffset:280;transform:rotate(360deg)}}";var Vl=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(cs,"__esModule",{value:!0});cs.Spinner=void 0;const Cn=Ke,zl=Vl(gi),Wl=e=>{var t;const r=(t=e.size)!==null&&t!==void 0?t:64,n=e.color||"#000";return(0,Cn.h)("div",{class:"-cbwsdk-spinner"},(0,Cn.h)("style",null,zl.default),(0,Cn.h)("svg",{viewBox:"0 0 100 100",xmlns:"http://www.w3.org/2000/svg",style:{width:r,height:r}},(0,Cn.h)("circle",{style:{cx:50,cy:50,r:45,stroke:n}})))};cs.Spinner=Wl;var pi={};Object.defineProperty(pi,"__esModule",{value:!0});pi.default=".-cbwsdk-css-reset .-cbwsdk-connect-content{height:430px;width:700px;border-radius:12px;padding:30px}.-cbwsdk-css-reset .-cbwsdk-connect-content.light{background:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content.dark{background:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-connect-content-header{display:flex;align-items:center;justify-content:space-between;margin:0 0 30px}.-cbwsdk-css-reset .-cbwsdk-connect-content-heading{font-style:normal;font-weight:500;font-size:28px;line-height:36px;margin:0}.-cbwsdk-css-reset .-cbwsdk-connect-content-heading.light{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-connect-content-heading.dark{color:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content-layout{display:flex;flex-direction:row}.-cbwsdk-css-reset .-cbwsdk-connect-content-column-left{margin-right:30px;display:flex;flex-direction:column;justify-content:space-between}.-cbwsdk-css-reset .-cbwsdk-connect-content-column-right{flex:25%;margin-right:34px}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-wrapper{width:220px;height:220px;border-radius:12px;display:flex;justify-content:center;align-items:center;background:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting{position:absolute;top:0;bottom:0;left:0;right:0;display:flex;flex-direction:column;align-items:center;justify-content:center}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.light{background-color:rgba(255,255,255,.95)}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.light>p{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.dark{background-color:rgba(10,11,13,.9)}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting.dark>p{color:#fff}.-cbwsdk-css-reset .-cbwsdk-connect-content-qr-connecting>p{font-size:12px;font-weight:bold;margin-top:16px}.-cbwsdk-css-reset .-cbwsdk-connect-content-update-app{border-radius:8px;font-size:14px;line-height:20px;padding:12px;width:339px}.-cbwsdk-css-reset .-cbwsdk-connect-content-update-app.light{background:#eef0f3;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-connect-content-update-app.dark{background:#1e2025;color:#8a919e}.-cbwsdk-css-reset .-cbwsdk-cancel-button{-webkit-appearance:none;border:none;background:none;cursor:pointer;padding:0;margin:0}.-cbwsdk-css-reset .-cbwsdk-cancel-button-x{position:relative;display:block;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-wallet-steps{padding:0 0 0 16px;margin:0;width:100%;list-style:decimal}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item{list-style-type:decimal;display:list-item;font-style:normal;font-weight:400;font-size:16px;line-height:24px;margin-top:20px}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item.light{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item.dark{color:#fff}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-item-wrapper{display:flex;align-items:center}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-pad-left{margin-left:6px}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon{display:flex;border-radius:50%;height:24px;width:24px}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon svg{margin:auto;display:block}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon.light{background:#0052ff}.-cbwsdk-css-reset .-cbwsdk-wallet-steps-icon.dark{background:#588af5}.-cbwsdk-css-reset .-cbwsdk-connect-item{align-items:center;display:flex;flex-direction:row;padding:16px 24px;gap:12px;cursor:pointer;border-radius:100px;font-weight:600}.-cbwsdk-css-reset .-cbwsdk-connect-item.light{background:#f5f8ff;color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-connect-item.dark{background:#001033;color:#588af5}.-cbwsdk-css-reset .-cbwsdk-connect-item-copy-wrapper{margin:0 4px 0 8px}.-cbwsdk-css-reset .-cbwsdk-connect-item-title{margin:0 0 0;font-size:16px;line-height:24px;font-weight:500}.-cbwsdk-css-reset .-cbwsdk-connect-item-description{font-weight:400;font-size:14px;line-height:20px;margin:0}";var ka=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Nr,"__esModule",{value:!0});Nr.CoinbaseWalletSteps=Nr.ConnectContent=void 0;const Xt=ka(dn),z=Ke,ql=T,Jl=$r,Gl=ss,Zl=is,Ql=os,Kl=as,Xl=cs,Yl=ka(pi),Hs={title:"Coinbase Wallet app",description:"Connect with your self-custody wallet",steps:Ma},eu=e=>e==="light"?"#FFFFFF":"#0A0B0D";function tu(e){const{theme:t}=e,r=(0,ql.createQrUrl)(e.sessionId,e.sessionSecret,e.linkAPIUrl,e.isParentConnection,e.version,e.chainId),n=Hs.steps;return(0,z.h)("div",{"data-testid":"connect-content",className:(0,Xt.default)("-cbwsdk-connect-content",t)},(0,z.h)("style",null,Yl.default),(0,z.h)("div",{className:"-cbwsdk-connect-content-header"},(0,z.h)("h2",{className:(0,Xt.default)("-cbwsdk-connect-content-heading",t)},"Scan to connect with our mobile app"),e.onCancel&&(0,z.h)("button",{type:"button",className:"-cbwsdk-cancel-button",onClick:e.onCancel},(0,z.h)(Gl.CloseIcon,{fill:t==="light"?"#0A0B0D":"#FFFFFF"}))),(0,z.h)("div",{className:"-cbwsdk-connect-content-layout"},(0,z.h)("div",{className:"-cbwsdk-connect-content-column-left"},(0,z.h)(ru,{title:Hs.title,description:Hs.description,theme:t})),(0,z.h)("div",{className:"-cbwsdk-connect-content-column-right"},(0,z.h)("div",{className:"-cbwsdk-connect-content-qr-wrapper"},(0,z.h)(Kl.QRCode,{content:r,width:200,height:200,fgColor:"#000",bgColor:"transparent"}),(0,z.h)("input",{type:"hidden",name:"cbw-cbwsdk-version",value:Jl.LIB_VERSION}),(0,z.h)("input",{type:"hidden",value:r})),(0,z.h)(n,{theme:t}),!e.isConnected&&(0,z.h)("div",{"data-testid":"connecting-spinner",className:(0,Xt.default)("-cbwsdk-connect-content-qr-connecting",t)},(0,z.h)(Xl.Spinner,{size:36,color:t==="dark"?"#FFF":"#000"}),(0,z.h)("p",null,"Connecting...")))))}Nr.ConnectContent=tu;function ru({title:e,description:t,theme:r}){return(0,z.h)("div",{className:(0,Xt.default)("-cbwsdk-connect-item",r)},(0,z.h)("div",null,(0,z.h)(Zl.CoinbaseWalletRound,null)),(0,z.h)("div",{className:"-cbwsdk-connect-item-copy-wrapper"},(0,z.h)("h3",{className:"-cbwsdk-connect-item-title"},e),(0,z.h)("p",{className:"-cbwsdk-connect-item-description"},t)))}function Ma({theme:e}){return(0,z.h)("ol",{className:"-cbwsdk-wallet-steps"},(0,z.h)("li",{className:(0,Xt.default)("-cbwsdk-wallet-steps-item",e)},(0,z.h)("div",{className:"-cbwsdk-wallet-steps-item-wrapper"},"Open Coinbase Wallet app")),(0,z.h)("li",{className:(0,Xt.default)("-cbwsdk-wallet-steps-item",e)},(0,z.h)("div",{className:"-cbwsdk-wallet-steps-item-wrapper"},(0,z.h)("span",null,"Tap ",(0,z.h)("strong",null,"Scan")," "),(0,z.h)("span",{className:(0,Xt.default)("-cbwsdk-wallet-steps-pad-left","-cbwsdk-wallet-steps-icon",e)},(0,z.h)(Ql.QRCodeIcon,{fill:eu(e)})))))}Nr.CoinbaseWalletSteps=Ma;var ls={},us={};Object.defineProperty(us,"__esModule",{value:!0});us.ArrowLeftIcon=void 0;const io=Ke;function nu(e){return(0,io.h)("svg",Object.assign({width:"16",height:"16",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg"},e),(0,io.h)("path",{d:"M8.60675 0.155884L7.37816 1.28209L12.7723 7.16662H0V8.83328H12.6548L6.82149 14.6666L8 15.8451L15.8201 8.02501L8.60675 0.155884Z"}))}us.ArrowLeftIcon=nu;var hs={};Object.defineProperty(hs,"__esModule",{value:!0});hs.LaptopIcon=void 0;const Us=Ke;function su(e){return(0,Us.h)("svg",Object.assign({width:"14",height:"14",viewBox:"0 0 14 14",xmlns:"http://www.w3.org/2000/svg"},e),(0,Us.h)("path",{d:"M1.8001 2.2002H12.2001V9.40019H1.8001V2.2002ZM3.4001 3.8002V7.80019H10.6001V3.8002H3.4001Z"}),(0,Us.h)("path",{d:"M13.4001 10.2002H0.600098C0.600098 11.0838 1.31644 11.8002 2.2001 11.8002H11.8001C12.6838 11.8002 13.4001 11.0838 13.4001 10.2002Z"}))}hs.LaptopIcon=su;var ds={};Object.defineProperty(ds,"__esModule",{value:!0});ds.SafeIcon=void 0;const oo=Ke;function iu(e){return(0,oo.h)("svg",Object.assign({width:"14",height:"14",viewBox:"0 0 14 14",xmlns:"http://www.w3.org/2000/svg"},e),(0,oo.h)("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M0.600098 0.600098V11.8001H13.4001V0.600098H0.600098ZM7.0001 9.2001C5.3441 9.2001 4.0001 7.8561 4.0001 6.2001C4.0001 4.5441 5.3441 3.2001 7.0001 3.2001C8.6561 3.2001 10.0001 4.5441 10.0001 6.2001C10.0001 7.8561 8.6561 9.2001 7.0001 9.2001ZM0.600098 12.6001H3.8001V13.4001H0.600098V12.6001ZM10.2001 12.6001H13.4001V13.4001H10.2001V12.6001ZM8.8001 6.2001C8.8001 7.19421 7.99421 8.0001 7.0001 8.0001C6.00598 8.0001 5.2001 7.19421 5.2001 6.2001C5.2001 5.20598 6.00598 4.4001 7.0001 4.4001C7.99421 4.4001 8.8001 5.20598 8.8001 6.2001Z"}))}ds.SafeIcon=iu;var mi={};Object.defineProperty(mi,"__esModule",{value:!0});mi.default=".-cbwsdk-css-reset .-cbwsdk-try-extension{display:flex;margin-top:12px;height:202px;width:700px;border-radius:12px;padding:30px}.-cbwsdk-css-reset .-cbwsdk-try-extension.light{background:#fff}.-cbwsdk-css-reset .-cbwsdk-try-extension.dark{background:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-try-extension-column-half{flex:50%}.-cbwsdk-css-reset .-cbwsdk-try-extension-heading{font-style:normal;font-weight:500;font-size:25px;line-height:32px;margin:0;max-width:204px}.-cbwsdk-css-reset .-cbwsdk-try-extension-heading.light{color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-try-extension-heading.dark{color:#fff}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta{appearance:none;border:none;background:none;color:#0052ff;cursor:pointer;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta.light{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta.dark{color:#588af5}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta-wrapper{display:flex;align-items:center;margin-top:12px}.-cbwsdk-css-reset .-cbwsdk-try-extension-cta-icon{display:block;margin-left:4px;height:14px}.-cbwsdk-css-reset .-cbwsdk-try-extension-list{display:flex;flex-direction:column;justify-content:center;align-items:center;margin:0;padding:0;list-style:none;height:100%}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item{display:flex;align-items:center;flex-flow:nowrap;margin-top:24px}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item:first-of-type{margin-top:0}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon-wrapper{display:block}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon{display:flex;height:32px;width:32px;border-radius:50%}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon svg{margin:auto;display:block}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon.light{background:#eef0f3}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-icon.dark{background:#1e2025}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-copy{display:block;font-weight:400;font-size:14px;line-height:20px;padding-left:12px}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-copy.light{color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-try-extension-list-item-copy.dark{color:#8a919e}";var Ra=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ls,"__esModule",{value:!0});ls.TryExtensionContent=void 0;const zt=Ra(dn),Be=Ke,Vs=ns,ou=us,au=hs,cu=ds,lu=Ra(mi);function uu({theme:e}){const[t,r]=(0,Vs.useState)(!1),n=(0,Vs.useCallback)(()=>{window.open("https://api.wallet.coinbase.com/rpc/v2/desktop/chrome","_blank")},[]),s=(0,Vs.useCallback)(()=>{t?window.location.reload():(n(),r(!0))},[n,t]);return(0,Be.h)("div",{class:(0,zt.default)("-cbwsdk-try-extension",e)},(0,Be.h)("style",null,lu.default),(0,Be.h)("div",{class:"-cbwsdk-try-extension-column-half"},(0,Be.h)("h3",{class:(0,zt.default)("-cbwsdk-try-extension-heading",e)},"Or try the Coinbase Wallet browser extension"),(0,Be.h)("div",{class:"-cbwsdk-try-extension-cta-wrapper"},(0,Be.h)("button",{class:(0,zt.default)("-cbwsdk-try-extension-cta",e),onClick:s},t?"Refresh":"Install"),(0,Be.h)("div",null,!t&&(0,Be.h)(ou.ArrowLeftIcon,{class:"-cbwsdk-try-extension-cta-icon",fill:e==="light"?"#0052FF":"#588AF5"})))),(0,Be.h)("div",{class:"-cbwsdk-try-extension-column-half"},(0,Be.h)("ul",{class:"-cbwsdk-try-extension-list"},(0,Be.h)("li",{class:"-cbwsdk-try-extension-list-item"},(0,Be.h)("div",{class:"-cbwsdk-try-extension-list-item-icon-wrapper"},(0,Be.h)("span",{class:(0,zt.default)("-cbwsdk-try-extension-list-item-icon",e)},(0,Be.h)(au.LaptopIcon,{fill:e==="light"?"#0A0B0D":"#FFFFFF"}))),(0,Be.h)("div",{class:(0,zt.default)("-cbwsdk-try-extension-list-item-copy",e)},"Connect with dapps with just one click on your desktop browser")),(0,Be.h)("li",{class:"-cbwsdk-try-extension-list-item"},(0,Be.h)("div",{class:"-cbwsdk-try-extension-list-item-icon-wrapper"},(0,Be.h)("span",{class:(0,zt.default)("-cbwsdk-try-extension-list-item-icon",e)},(0,Be.h)(cu.SafeIcon,{fill:e==="light"?"#0A0B0D":"#FFFFFF"}))),(0,Be.h)("div",{class:(0,zt.default)("-cbwsdk-try-extension-list-item-copy",e)},"Add an additional layer of security by using a supported Ledger hardware wallet")))))}ls.TryExtensionContent=uu;var vi={};Object.defineProperty(vi,"__esModule",{value:!0});vi.default=".-cbwsdk-css-reset .-cbwsdk-connect-dialog{z-index:2147483647;position:fixed;top:0;left:0;right:0;bottom:0;display:flex;align-items:center;justify-content:center}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop{z-index:2147483647;position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop.light{background-color:rgba(0,0,0,.5)}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop.dark{background-color:rgba(50,53,61,.4)}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-box{display:flex;position:relative;flex-direction:column;transform:scale(1);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-box-hidden{opacity:0;transform:scale(0.85)}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-container{display:block}.-cbwsdk-css-reset .-cbwsdk-connect-dialog-container-hidden{display:none}";var Ia=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(rs,"__esModule",{value:!0});rs.ConnectDialog=void 0;const zs=Ia(dn),Wt=Ke,Ws=ns,hu=Nr,du=ls,fu=Ia(vi),gu=e=>{const{isOpen:t,darkMode:r}=e,[n,s]=(0,Ws.useState)(!t),[i,c]=(0,Ws.useState)(!t);(0,Ws.useEffect)(()=>{const h=[window.setTimeout(()=>{c(!t)},10)];return t?s(!1):h.push(window.setTimeout(()=>{s(!0)},360)),()=>{h.forEach(window.clearTimeout)}},[t]);const u=r?"dark":"light";return(0,Wt.h)("div",{class:(0,zs.default)("-cbwsdk-connect-dialog-container",n&&"-cbwsdk-connect-dialog-container-hidden")},(0,Wt.h)("style",null,fu.default),(0,Wt.h)("div",{class:(0,zs.default)("-cbwsdk-connect-dialog-backdrop",u,i&&"-cbwsdk-connect-dialog-backdrop-hidden")}),(0,Wt.h)("div",{class:"-cbwsdk-connect-dialog"},(0,Wt.h)("div",{class:(0,zs.default)("-cbwsdk-connect-dialog-box",i&&"-cbwsdk-connect-dialog-box-hidden")},e.connectDisabled?null:(0,Wt.h)(hu.ConnectContent,{theme:u,version:e.version,sessionId:e.sessionId,sessionSecret:e.sessionSecret,linkAPIUrl:e.linkAPIUrl,isConnected:e.isConnected,isParentConnection:e.isParentConnection,chainId:e.chainId,onCancel:e.onCancel}),(0,Wt.h)(du.TryExtensionContent,{theme:u}))))};rs.ConnectDialog=gu;Object.defineProperty(ts,"__esModule",{value:!0});ts.LinkFlow=void 0;const qs=Ke,pu=rs;class mu{constructor(t){this.connected=!1,this.chainId=1,this.isOpen=!1,this.onCancel=null,this.root=null,this.connectDisabled=!1,this.darkMode=t.darkMode,this.version=t.version,this.sessionId=t.sessionId,this.sessionSecret=t.sessionSecret,this.linkAPIUrl=t.linkAPIUrl,this.isParentConnection=t.isParentConnection}attach(t){this.root=document.createElement("div"),this.root.className="-cbwsdk-link-flow-root",t.appendChild(this.root),this.render()}setConnected(t){this.connected!==t&&(this.connected=t,this.render())}setChainId(t){this.chainId!==t&&(this.chainId=t,this.render())}detach(){var t;this.root&&((0,qs.render)(null,this.root),(t=this.root.parentElement)===null||t===void 0||t.removeChild(this.root))}setConnectDisabled(t){this.connectDisabled=t}open(t){this.isOpen=!0,this.onCancel=t.onCancel,this.render()}close(){this.isOpen=!1,this.onCancel=null,this.render()}render(){this.root&&(0,qs.render)((0,qs.h)(pu.ConnectDialog,{darkMode:this.darkMode,version:this.version,sessionId:this.sessionId,sessionSecret:this.sessionSecret,linkAPIUrl:this.linkAPIUrl,isOpen:this.isOpen,isConnected:this.connected,isParentConnection:this.isParentConnection,chainId:this.chainId,onCancel:this.onCancel,connectDisabled:this.connectDisabled}),this.root)}}ts.LinkFlow=mu;var wi={},yi={};Object.defineProperty(yi,"__esModule",{value:!0});yi.default=".-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}";(function(e){var t=B&&B.__importDefault||function(E){return E&&E.__esModule?E:{default:E}};Object.defineProperty(e,"__esModule",{value:!0}),e.SnackbarInstance=e.SnackbarContainer=e.Snackbar=void 0;const r=t(dn),n=Ke,s=ns,i=t(yi),c="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+",u="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=";class h{constructor(b){this.items=new Map,this.nextItemKey=0,this.root=null,this.darkMode=b.darkMode}attach(b){this.root=document.createElement("div"),this.root.className="-cbwsdk-snackbar-root",b.appendChild(this.root),this.render()}presentItem(b){const k=this.nextItemKey++;return this.items.set(k,b),this.render(),()=>{this.items.delete(k),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&(0,n.render)((0,n.h)("div",null,(0,n.h)(e.SnackbarContainer,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([b,k])=>(0,n.h)(e.SnackbarInstance,Object.assign({},k,{key:b}))))),this.root)}}e.Snackbar=h;const f=E=>(0,n.h)("div",{class:(0,r.default)("-cbwsdk-snackbar-container")},(0,n.h)("style",null,i.default),(0,n.h)("div",{class:"-cbwsdk-snackbar"},E.children));e.SnackbarContainer=f;const g=({autoExpand:E,message:b,menuItems:k})=>{const[C,R]=(0,s.useState)(!0),[I,P]=(0,s.useState)(E??!1);(0,s.useEffect)(()=>{const M=[window.setTimeout(()=>{R(!1)},1),window.setTimeout(()=>{P(!0)},1e4)];return()=>{M.forEach(window.clearTimeout)}});const L=()=>{P(!I)};return(0,n.h)("div",{class:(0,r.default)("-cbwsdk-snackbar-instance",C&&"-cbwsdk-snackbar-instance-hidden",I&&"-cbwsdk-snackbar-instance-expanded")},(0,n.h)("div",{class:"-cbwsdk-snackbar-instance-header",onClick:L},(0,n.h)("img",{src:c,class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",(0,n.h)("div",{class:"-cbwsdk-snackbar-instance-header-message"},b),(0,n.h)("div",{class:"-gear-container"},!I&&(0,n.h)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,n.h)("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),(0,n.h)("img",{src:u,class:"-gear-icon",title:"Expand"}))),k&&k.length>0&&(0,n.h)("div",{class:"-cbwsdk-snackbar-instance-menu"},k.map((M,j)=>(0,n.h)("div",{class:(0,r.default)("-cbwsdk-snackbar-instance-menu-item",M.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:M.onClick,key:j},(0,n.h)("svg",{width:M.svgWidth,height:M.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,n.h)("path",{"fill-rule":M.defaultFillRule,"clip-rule":M.defaultClipRule,d:M.path,fill:"#AAAAAA"})),(0,n.h)("span",{class:(0,r.default)("-cbwsdk-snackbar-instance-menu-item-info",M.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},M.info)))))};e.SnackbarInstance=g})(wi);Object.defineProperty(un,"__esModule",{value:!0});un.WalletLinkRelayUI=void 0;const vu=hn,wu=ts,yu=wi;class bu{constructor(t){this.standalone=null,this.attached=!1,this.snackbar=new yu.Snackbar({darkMode:t.darkMode}),this.linkFlow=new wu.LinkFlow({darkMode:t.darkMode,version:t.version,sessionId:t.session.id,sessionSecret:t.session.secret,linkAPIUrl:t.linkAPIUrl,isParentConnection:!1})}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");const t=document.documentElement,r=document.createElement("div");r.className="-cbwsdk-css-reset",t.appendChild(r),this.linkFlow.attach(r),this.snackbar.attach(r),this.attached=!0,(0,vu.injectCssReset)()}setConnected(t){this.linkFlow.setConnected(t)}setChainId(t){this.linkFlow.setChainId(t)}setConnectDisabled(t){this.linkFlow.setConnectDisabled(t)}addEthereumChain(){}watchAsset(){}switchEthereumChain(){}requestEthereumAccounts(t){this.linkFlow.open({onCancel:t.onCancel})}hideRequestEthereumAccounts(){this.linkFlow.close()}signEthereumMessage(){}signEthereumTransaction(){}submitEthereumTransaction(){}ethereumAddressFromSignedMessage(){}showConnecting(t){let r;return t.isUnlinkedErrorState?r={autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:t.onResetConnection}]}:r={message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:t.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:t.onResetConnection}]},this.snackbar.presentItem(r)}reloadUI(){document.location.reload()}inlineAccountsResponse(){return!1}inlineAddEthereumChain(){return!1}inlineWatchAsset(){return!1}inlineSwitchEthereumChain(){return!1}setStandalone(t){this.standalone=t}isStandalone(){var t;return(t=this.standalone)!==null&&t!==void 0?t:!1}}un.WalletLinkRelayUI=bu;Object.defineProperty(ln,"__esModule",{value:!0});ln.WalletLinkRelay=void 0;const yr=nn,_u=Fe,Te=T,qt=Or,ao=it,Mt=Br,Eu=Xn,Jt=Pr,Su=un;class Et extends ao.RelayAbstract{constructor(t){var r;super(),this.accountsCallback=null,this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.chainCallback=null,this.dappDefaultChain=1,this.appName="",this.appLogoUrl=null,this.linkedUpdated=c=>{var u;this.isLinked=c;const h=this.storage.getItem(ao.LOCAL_STORAGE_ADDRESSES_KEY);if(c&&(this.session.linked=c),this.isUnlinkedErrorState=!1,h){const f=h.split(" "),g=this.storage.getItem("IsStandaloneSigning")==="true";if(f[0]!==""&&!c&&this.session.linked&&!g){this.isUnlinkedErrorState=!0;const E=this.getSessionIdHash();(u=this.diagnostic)===null||u===void 0||u.log(qt.EVENTS.UNLINKED_ERROR_STATE,{sessionIdHash:E})}}},this.metadataUpdated=(c,u)=>{this.storage.setItem(c,u)},this.chainUpdated=(c,u)=>{this.chainCallbackParams.chainId===c&&this.chainCallbackParams.jsonRpcUrl===u||(this.chainCallbackParams={chainId:c,jsonRpcUrl:u},this.chainCallback&&this.chainCallback(c,u))},this.accountUpdated=c=>{this.accountsCallback&&this.accountsCallback([c]),Et.accountRequestCallbackIds.size>0&&(Array.from(Et.accountRequestCallbackIds.values()).forEach(u=>{const h={type:"WEB3_RESPONSE",id:u,response:{method:"requestEthereumAccounts",result:[c]}};this.invokeCallback(Object.assign(Object.assign({},h),{id:u}))}),Et.accountRequestCallbackIds.clear())},this.connectedUpdated=c=>{this.ui.setConnected(c)},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=t.linkAPIUrl,this.storage=t.storage,this.options=t;const{session:n,ui:s,connection:i}=this.subscribe();this._session=n,this.connection=i,this.relayEventManager=t.relayEventManager,this.diagnostic=t.diagnosticLogger,this._reloadOnDisconnect=(r=t.reloadOnDisconnect)!==null&&r!==void 0?r:!0,this.ui=s}subscribe(){const t=Mt.Session.load(this.storage)||new Mt.Session(this.storage).save(),{linkAPIUrl:r,diagnostic:n}=this,s=new Eu.WalletLinkConnection({session:t,linkAPIUrl:r,diagnostic:n,listener:this}),{version:i,darkMode:c}=this.options,u=this.options.uiConstructor({linkAPIUrl:r,version:i,darkMode:c,session:t});return s.connect(),{session:t,ui:u,connection:s}}attachUI(){this.ui.attach()}resetAndReload(){Promise.race([this.connection.setSessionMetadata("__destroyed","1"),new Promise(t=>setTimeout(()=>t(null),1e3))]).then(()=>{var t,r;const n=this.ui.isStandalone();(t=this.diagnostic)===null||t===void 0||t.log(qt.EVENTS.SESSION_STATE_CHANGE,{method:"relay::resetAndReload",sessionMetadataChange:"__destroyed, 1",sessionIdHash:this.getSessionIdHash()}),this.connection.destroy();const s=Mt.Session.load(this.storage);if(s?.id===this._session.id?this.storage.clear():s&&((r=this.diagnostic)===null||r===void 0||r.log(qt.EVENTS.SKIPPED_CLEARING_SESSION,{sessionIdHash:this.getSessionIdHash(),storedSessionIdHash:Mt.Session.hash(s.id)})),this._reloadOnDisconnect){this.ui.reloadUI();return}this.accountsCallback&&this.accountsCallback([],!0);const{session:i,ui:c,connection:u}=this.subscribe();this._session=i,this.connection=u,this.ui=c,n&&this.ui.setStandalone&&this.ui.setStandalone(!0),this.options.headlessMode||this.attachUI()}).catch(t=>{var r;(r=this.diagnostic)===null||r===void 0||r.log(qt.EVENTS.FAILURE,{method:"relay::resetAndReload",message:`failed to reset and reload with ${t}`,sessionIdHash:this.getSessionIdHash()})})}setAppInfo(t,r){this.appName=t,this.appLogoUrl=r}getStorageItem(t){return this.storage.getItem(t)}get session(){return this._session}setStorageItem(t,r){this.storage.setItem(t,r)}signEthereumMessage(t,r,n,s){return this.sendRequest({method:"signEthereumMessage",params:{message:(0,Te.hexStringFromBuffer)(t,!0),address:r,addPrefix:n,typedDataJson:s||null}})}ethereumAddressFromSignedMessage(t,r,n){return this.sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:(0,Te.hexStringFromBuffer)(t,!0),signature:(0,Te.hexStringFromBuffer)(r,!0),addPrefix:n}})}signEthereumTransaction(t){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:t.fromAddress,toAddress:t.toAddress,weiValue:(0,Te.bigIntStringFromBN)(t.weiValue),data:(0,Te.hexStringFromBuffer)(t.data,!0),nonce:t.nonce,gasPriceInWei:t.gasPriceInWei?(0,Te.bigIntStringFromBN)(t.gasPriceInWei):null,maxFeePerGas:t.gasPriceInWei?(0,Te.bigIntStringFromBN)(t.gasPriceInWei):null,maxPriorityFeePerGas:t.gasPriceInWei?(0,Te.bigIntStringFromBN)(t.gasPriceInWei):null,gasLimit:t.gasLimit?(0,Te.bigIntStringFromBN)(t.gasLimit):null,chainId:t.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(t){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:t.fromAddress,toAddress:t.toAddress,weiValue:(0,Te.bigIntStringFromBN)(t.weiValue),data:(0,Te.hexStringFromBuffer)(t.data,!0),nonce:t.nonce,gasPriceInWei:t.gasPriceInWei?(0,Te.bigIntStringFromBN)(t.gasPriceInWei):null,maxFeePerGas:t.maxFeePerGas?(0,Te.bigIntStringFromBN)(t.maxFeePerGas):null,maxPriorityFeePerGas:t.maxPriorityFeePerGas?(0,Te.bigIntStringFromBN)(t.maxPriorityFeePerGas):null,gasLimit:t.gasLimit?(0,Te.bigIntStringFromBN)(t.gasLimit):null,chainId:t.chainId,shouldSubmit:!0}})}submitEthereumTransaction(t,r){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:(0,Te.hexStringFromBuffer)(t,!0),chainId:r}})}scanQRCode(t){return this.sendRequest({method:"scanQRCode",params:{regExp:t}})}getQRCodeUrl(){return(0,Te.createQrUrl)(this._session.id,this._session.secret,this.linkAPIUrl,!1,this.options.version,this.dappDefaultChain)}genericRequest(t,r){return this.sendRequest({method:"generic",params:{action:r,data:t}})}sendGenericMessage(t){return this.sendRequest(t)}sendRequest(t){let r=null;const n=(0,Te.randomBytesHex)(8),s=c=>{this.publishWeb3RequestCanceledEvent(n),this.handleErrorResponse(n,t.method,c),r?.()};return{promise:new Promise((c,u)=>{this.ui.isStandalone()||(r=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:s,onResetConnection:this.resetAndReload})),this.relayEventManager.callbacks.set(n,h=>{if(r?.(),(0,Jt.isErrorResponse)(h))return u(new Error(h.errorMessage));c(h)}),this.ui.isStandalone()?this.sendRequestStandalone(n,t):this.publishWeb3RequestEvent(n,t)}),cancel:s}}setConnectDisabled(t){this.ui.setConnectDisabled(t)}setAccountsCallback(t){this.accountsCallback=t}setChainCallback(t){this.chainCallback=t}setDappDefaultChainCallback(t){this.dappDefaultChain=t,this.ui instanceof Su.WalletLinkRelayUI&&this.ui.setChainId(t)}publishWeb3RequestEvent(t,r){var n;const s={type:"WEB3_REQUEST",id:t,request:r},i=Mt.Session.load(this.storage);(n=this.diagnostic)===null||n===void 0||n.log(qt.EVENTS.WEB3_REQUEST,{eventId:s.id,method:`relay::${r.method}`,sessionIdHash:this.getSessionIdHash(),storedSessionIdHash:i?Mt.Session.hash(i.id):"",isSessionMismatched:(i?.id!==this._session.id).toString()}),this.publishEvent("Web3Request",s,!0).then(c=>{var u;(u=this.diagnostic)===null||u===void 0||u.log(qt.EVENTS.WEB3_REQUEST_PUBLISHED,{eventId:s.id,method:`relay::${r.method}`,sessionIdHash:this.getSessionIdHash(),storedSessionIdHash:i?Mt.Session.hash(i.id):"",isSessionMismatched:(i?.id!==this._session.id).toString()})}).catch(c=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:s.id,response:{method:r.method,errorMessage:c.message}})})}publishWeb3RequestCanceledEvent(t){const r={type:"WEB3_REQUEST_CANCELED",id:t};this.publishEvent("Web3RequestCanceled",r,!1).then()}publishEvent(t,r,n){return this.connection.publishEvent(t,r,n)}handleWeb3ResponseMessage(t){var r;const{response:n}=t;if((r=this.diagnostic)===null||r===void 0||r.log(qt.EVENTS.WEB3_RESPONSE,{eventId:t.id,method:`relay::${n.method}`,sessionIdHash:this.getSessionIdHash()}),n.method==="requestEthereumAccounts"){Et.accountRequestCallbackIds.forEach(s=>this.invokeCallback(Object.assign(Object.assign({},t),{id:s}))),Et.accountRequestCallbackIds.clear();return}this.invokeCallback(t)}handleErrorResponse(t,r,n,s){var i;const c=(i=n?.message)!==null&&i!==void 0?i:(0,yr.getMessageFromCode)(s);this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:t,response:{method:r,errorMessage:c,errorCode:s}})}invokeCallback(t){const r=this.relayEventManager.callbacks.get(t.id);r&&(r(t.response),this.relayEventManager.callbacks.delete(t.id))}requestEthereumAccounts(){const t={method:"requestEthereumAccounts",params:{appName:this.appName,appLogoUrl:this.appLogoUrl||null}},r=(0,Te.randomBytesHex)(8),n=i=>{this.publishWeb3RequestCanceledEvent(r),this.handleErrorResponse(r,t.method,i)};return{promise:new Promise((i,c)=>{if(this.relayEventManager.callbacks.set(r,u=>{if(this.ui.hideRequestEthereumAccounts(),(0,Jt.isErrorResponse)(u))return c(new Error(u.errorMessage));i(u)}),this.ui.inlineAccountsResponse()){const u=h=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:r,response:{method:"requestEthereumAccounts",result:h}})};this.ui.requestEthereumAccounts({onCancel:n,onAccounts:u})}else{const u=yr.standardErrors.provider.userRejectedRequest("User denied account authorization");this.ui.requestEthereumAccounts({onCancel:()=>n(u)})}Et.accountRequestCallbackIds.add(r),!this.ui.inlineAccountsResponse()&&!this.ui.isStandalone()&&this.publishWeb3RequestEvent(r,t)}),cancel:n}}selectProvider(t){const r={method:"selectProvider",params:{providerOptions:t}},n=(0,Te.randomBytesHex)(8),s=c=>{this.publishWeb3RequestCanceledEvent(n),this.handleErrorResponse(n,r.method,c)},i=new Promise((c,u)=>{this.relayEventManager.callbacks.set(n,g=>{if((0,Jt.isErrorResponse)(g))return u(new Error(g.errorMessage));c(g)});const h=g=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:n,response:{method:"selectProvider",result:_u.ProviderType.Unselected}})},f=g=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:n,response:{method:"selectProvider",result:g}})};this.ui.selectProvider&&this.ui.selectProvider({onApprove:f,onCancel:h,providerOptions:t})});return{cancel:s,promise:i}}watchAsset(t,r,n,s,i,c){const u={method:"watchAsset",params:{type:t,options:{address:r,symbol:n,decimals:s,image:i},chainId:c}};let h=null;const f=(0,Te.randomBytesHex)(8),g=b=>{this.publishWeb3RequestCanceledEvent(f),this.handleErrorResponse(f,u.method,b),h?.()};this.ui.inlineWatchAsset()||(h=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:g,onResetConnection:this.resetAndReload}));const E=new Promise((b,k)=>{this.relayEventManager.callbacks.set(f,I=>{if(h?.(),(0,Jt.isErrorResponse)(I))return k(new Error(I.errorMessage));b(I)});const C=I=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:f,response:{method:"watchAsset",result:!1}})},R=()=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:f,response:{method:"watchAsset",result:!0}})};this.ui.inlineWatchAsset()&&this.ui.watchAsset({onApprove:R,onCancel:C,type:t,address:r,symbol:n,decimals:s,image:i,chainId:c}),!this.ui.inlineWatchAsset()&&!this.ui.isStandalone()&&this.publishWeb3RequestEvent(f,u)});return{cancel:g,promise:E}}addEthereumChain(t,r,n,s,i,c){const u={method:"addEthereumChain",params:{chainId:t,rpcUrls:r,blockExplorerUrls:s,chainName:i,iconUrls:n,nativeCurrency:c}};let h=null;const f=(0,Te.randomBytesHex)(8),g=b=>{this.publishWeb3RequestCanceledEvent(f),this.handleErrorResponse(f,u.method,b),h?.()};return this.ui.inlineAddEthereumChain(t)||(h=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:g,onResetConnection:this.resetAndReload})),{promise:new Promise((b,k)=>{this.relayEventManager.callbacks.set(f,I=>{if(h?.(),(0,Jt.isErrorResponse)(I))return k(new Error(I.errorMessage));b(I)});const C=I=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:f,response:{method:"addEthereumChain",result:{isApproved:!1,rpcUrl:""}}})},R=I=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:f,response:{method:"addEthereumChain",result:{isApproved:!0,rpcUrl:I}}})};this.ui.inlineAddEthereumChain(t)&&this.ui.addEthereumChain({onCancel:C,onApprove:R,chainId:u.params.chainId,rpcUrls:u.params.rpcUrls,blockExplorerUrls:u.params.blockExplorerUrls,chainName:u.params.chainName,iconUrls:u.params.iconUrls,nativeCurrency:u.params.nativeCurrency}),!this.ui.inlineAddEthereumChain(t)&&!this.ui.isStandalone()&&this.publishWeb3RequestEvent(f,u)}),cancel:g}}switchEthereumChain(t,r){const n={method:"switchEthereumChain",params:Object.assign({chainId:t},{address:r})},s=(0,Te.randomBytesHex)(8),i=u=>{this.publishWeb3RequestCanceledEvent(s),this.handleErrorResponse(s,n.method,u)};return{promise:new Promise((u,h)=>{this.relayEventManager.callbacks.set(s,E=>{if((0,Jt.isErrorResponse)(E)&&E.errorCode)return h(yr.standardErrors.provider.custom({code:E.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."}));if((0,Jt.isErrorResponse)(E))return h(new Error(E.errorMessage));u(E)});const f=E=>{var b;if(E){const k=(b=(0,yr.getErrorCode)(E))!==null&&b!==void 0?b:yr.standardErrorCodes.provider.unsupportedChain;this.handleErrorResponse(s,"switchEthereumChain",E instanceof Error?E:yr.standardErrors.provider.unsupportedChain(t),k)}else this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:s,response:{method:"switchEthereumChain",result:{isApproved:!1,rpcUrl:""}}})},g=E=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:s,response:{method:"switchEthereumChain",result:{isApproved:!0,rpcUrl:E}}})};this.ui.switchEthereumChain({onCancel:f,onApprove:g,chainId:n.params.chainId,address:n.params.address}),!this.ui.inlineSwitchEthereumChain()&&!this.ui.isStandalone()&&this.publishWeb3RequestEvent(s,n)}),cancel:i}}inlineAddEthereumChain(t){return this.ui.inlineAddEthereumChain(t)}getSessionIdHash(){return Mt.Session.hash(this._session.id)}sendRequestStandalone(t,r){const n=i=>{this.handleErrorResponse(t,r.method,i)},s=i=>{this.handleWeb3ResponseMessage({type:"WEB3_RESPONSE",id:t,response:i})};switch(r.method){case"signEthereumMessage":this.ui.signEthereumMessage({request:r,onSuccess:s,onCancel:n});break;case"signEthereumTransaction":this.ui.signEthereumTransaction({request:r,onSuccess:s,onCancel:n});break;case"submitEthereumTransaction":this.ui.submitEthereumTransaction({request:r,onSuccess:s,onCancel:n});break;case"ethereumAddressFromSignedMessage":this.ui.ethereumAddressFromSignedMessage({request:r,onSuccess:s});break;default:n();break}}}ln.WalletLinkRelay=Et;Et.accountRequestCallbackIds=new Set;var fn={},fs={},Ca={};(function(e){var t=B&&B.__createBinding||(Object.create?function(n,s,i,c){c===void 0&&(c=i);var u=Object.getOwnPropertyDescriptor(s,i);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[i]}}),Object.defineProperty(n,c,u)}:function(n,s,i,c){c===void 0&&(c=i),n[c]=s[i]}),r=B&&B.__exportStar||function(n,s){for(var i in n)i!=="default"&&!Object.prototype.hasOwnProperty.call(s,i)&&t(s,n,i)};Object.defineProperty(e,"__esModule",{value:!0}),r(wi,e)})(Ca);var bi={};Object.defineProperty(bi,"__esModule",{value:!0});bi.default=".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}";var Aa=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(fs,"__esModule",{value:!0});fs.RedirectDialog=void 0;const ku=Aa(dn),mt=Ke,Mu=hn,Ru=Ca,Iu=Aa(bi);class Cu{constructor(){this.root=null}attach(){const t=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",t.appendChild(this.root),(0,Mu.injectCssReset)()}present(t){this.render(t)}clear(){this.render(null)}render(t){this.root&&((0,mt.render)(null,this.root),t&&(0,mt.render)((0,mt.h)(Au,Object.assign({},t,{onDismiss:()=>{this.clear()}})),this.root))}}fs.RedirectDialog=Cu;const Au=({title:e,buttonText:t,darkMode:r,onButtonClick:n,onDismiss:s})=>{const i=r?"dark":"light";return(0,mt.h)(Ru.SnackbarContainer,{darkMode:r},(0,mt.h)("div",{class:"-cbwsdk-redirect-dialog"},(0,mt.h)("style",null,Iu.default),(0,mt.h)("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:s}),(0,mt.h)("div",{class:(0,ku.default)("-cbwsdk-redirect-dialog-box",i)},(0,mt.h)("p",null,e),(0,mt.h)("button",{onClick:n},t))))};Object.defineProperty(fn,"__esModule",{value:!0});fn.MobileRelayUI=void 0;const Nu=fs;class Lu{constructor(t){this.attached=!1,this.darkMode=!1,this.redirectDialog=new Nu.RedirectDialog,this.darkMode=t.darkMode}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}setConnected(t){}redirectToCoinbaseWallet(t){const r=new URL("https://go.cb-w.com/walletlink");r.searchParams.append("redirect_url",window.location.href),t&&r.searchParams.append("wl_url",t);const n=document.createElement("a");n.target="cbw-opener",n.href=r.href,n.rel="noreferrer noopener",n.click()}openCoinbaseWalletDeeplink(t){this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",darkMode:this.darkMode,onButtonClick:()=>{this.redirectToCoinbaseWallet(t)}}),setTimeout(()=>{this.redirectToCoinbaseWallet(t)},99)}showConnecting(t){return()=>{this.redirectDialog.clear()}}hideRequestEthereumAccounts(){this.redirectDialog.clear()}requestEthereumAccounts(){}addEthereumChain(){}watchAsset(){}selectProvider(){}switchEthereumChain(){}signEthereumMessage(){}signEthereumTransaction(){}submitEthereumTransaction(){}ethereumAddressFromSignedMessage(){}reloadUI(){}setStandalone(){}setConnectDisabled(){}inlineAccountsResponse(){return!1}inlineAddEthereumChain(){return!1}inlineWatchAsset(){return!1}inlineSwitchEthereumChain(){return!1}isStandalone(){return!1}}fn.MobileRelayUI=Lu;Object.defineProperty(cn,"__esModule",{value:!0});cn.MobileRelay=void 0;const xu=T,Tu=ln,Pu=fn;class $u extends Tu.WalletLinkRelay{constructor(t){var r;super(t),this._enableMobileWalletLink=(r=t.enableMobileWalletLink)!==null&&r!==void 0?r:!1}requestEthereumAccounts(){return this._enableMobileWalletLink?super.requestEthereumAccounts():{promise:new Promise(()=>{const t=(0,xu.getLocation)();t.href=`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(t.href)}`}),cancel:()=>{}}}publishWeb3RequestEvent(t,r){if(super.publishWeb3RequestEvent(t,r),!(this._enableMobileWalletLink&&this.ui instanceof Pu.MobileRelayUI))return;let n=!1;switch(r.method){case"requestEthereumAccounts":case"connectAndSignIn":n=!0,this.ui.openCoinbaseWalletDeeplink(this.getQRCodeUrl());break;case"switchEthereumChain":return;default:n=!0,this.ui.openCoinbaseWalletDeeplink();break}n&&window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0})}handleWeb3ResponseMessage(t){super.handleWeb3ResponseMessage(t)}connectAndSignIn(t){if(!this._enableMobileWalletLink)throw new Error("connectAndSignIn is supported only when enableMobileWalletLink is on");return this.sendRequest({method:"connectAndSignIn",params:{appName:this.appName,appLogoUrl:this.appLogoUrl,domain:window.location.hostname,aud:window.location.href,version:"1",type:"eip4361",nonce:t.nonce,iat:new Date().toISOString(),chainId:`eip155:${this.dappDefaultChain}`,statement:t.statement,resources:t.resources}})}}cn.MobileRelay=$u;const{Transform:Ou}=ia;var Bu=e=>class Na extends Ou{constructor(r,n,s,i,c){super(c),this._rate=r,this._capacity=n,this._delimitedSuffix=s,this._hashBitLength=i,this._options=c,this._state=new e,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,s){let i=null;try{this.update(r,n)}catch(c){i=c}s(i)}_flush(r){let n=null;try{this.push(this.digest())}catch(s){n=s}r(n)}update(r,n){if(!Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return Buffer.isBuffer(r)||(r=Buffer.from(r,n)),this._state.absorb(r),this}digest(r){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let n=this._state.squeeze(this._hashBitLength/8);return r!==void 0&&(n=n.toString(r)),this._resetState(),n}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const r=new Na(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}};const{Transform:Du}=ia;var ju=e=>class La extends Du{constructor(r,n,s,i){super(i),this._rate=r,this._capacity=n,this._delimitedSuffix=s,this._options=i,this._state=new e,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,s){let i=null;try{this.update(r,n)}catch(c){i=c}s(i)}_flush(){}_read(r){this.push(this.squeeze(r))}update(r,n){if(!Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return Buffer.isBuffer(r)||(r=Buffer.from(r,n)),this._state.absorb(r),this}squeeze(r,n){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let s=this._state.squeeze(r);return n!==void 0&&(s=s.toString(n)),s}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){const r=new La(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}};const Fu=Bu,Hu=ju;var Uu=function(e){const t=Fu(e),r=Hu(e);return function(n,s){switch(typeof n=="string"?n.toLowerCase():n){case"keccak224":return new t(1152,448,null,224,s);case"keccak256":return new t(1088,512,null,256,s);case"keccak384":return new t(832,768,null,384,s);case"keccak512":return new t(576,1024,null,512,s);case"sha3-224":return new t(1152,448,6,224,s);case"sha3-256":return new t(1088,512,6,256,s);case"sha3-384":return new t(832,768,6,384,s);case"sha3-512":return new t(576,1024,6,512,s);case"shake128":return new r(1344,256,31,s);case"shake256":return new r(1088,512,31,s);default:throw new Error("Invald algorithm: "+n)}}},xa={};const co=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];xa.p1600=function(e){for(let t=0;t<24;++t){const r=e[0]^e[10]^e[20]^e[30]^e[40],n=e[1]^e[11]^e[21]^e[31]^e[41],s=e[2]^e[12]^e[22]^e[32]^e[42],i=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],u=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],f=e[7]^e[17]^e[27]^e[37]^e[47],g=e[8]^e[18]^e[28]^e[38]^e[48],E=e[9]^e[19]^e[29]^e[39]^e[49];let b=g^(s<<1|i>>>31),k=E^(i<<1|s>>>31);const C=e[0]^b,R=e[1]^k,I=e[10]^b,P=e[11]^k,L=e[20]^b,M=e[21]^k,j=e[30]^b,A=e[31]^k,$=e[40]^b,J=e[41]^k;b=r^(c<<1|u>>>31),k=n^(u<<1|c>>>31);const De=e[2]^b,Ve=e[3]^k,Q=e[12]^b,U=e[13]^k,q=e[22]^b,_=e[23]^k,o=e[32]^b,l=e[33]^k,d=e[42]^b,p=e[43]^k;b=s^(h<<1|f>>>31),k=i^(f<<1|h>>>31);const v=e[4]^b,y=e[5]^k,S=e[14]^b,m=e[15]^k,a=e[24]^b,w=e[25]^k,x=e[34]^b,N=e[35]^k,O=e[44]^b,je=e[45]^k;b=c^(g<<1|E>>>31),k=u^(E<<1|g>>>31);const G=e[6]^b,Z=e[7]^k,Ur=e[16]^b,_e=e[17]^k,Ee=e[26]^b,Vr=e[27]^k,Se=e[36]^b,ke=e[37]^k,zr=e[46]^b,Me=e[47]^k;b=h^(r<<1|n>>>31),k=f^(n<<1|r>>>31);const Re=e[8]^b,Wr=e[9]^k,Ie=e[18]^b,Ce=e[19]^k,qr=e[28]^b,Ae=e[29]^k,Ne=e[38]^b,Jr=e[39]^k,Le=e[48]^b,xe=e[49]^k,sr=C,K=R,X=P<<4|I>>>28,ir=I<<4|P>>>28,Y=L<<3|M>>>29,ee=M<<3|L>>>29,or=A<<9|j>>>23,te=j<<9|A>>>23,re=$<<18|J>>>14,ar=J<<18|$>>>14,ne=De<<1|Ve>>>31,se=Ve<<1|De>>>31,cr=U<<12|Q>>>20,ie=Q<<12|U>>>20,oe=q<<10|_>>>22,lr=_<<10|q>>>22,ae=l<<13|o>>>19,ce=o<<13|l>>>19,ur=d<<2|p>>>30,le=p<<2|d>>>30,ue=y<<30|v>>>2,hr=v<<30|y>>>2,he=S<<6|m>>>26,de=m<<6|S>>>26,dr=w<<11|a>>>21,fe=a<<11|w>>>21,ge=x<<15|N>>>17,fr=N<<15|x>>>17,pe=je<<29|O>>>3,me=O<<29|je>>>3,gr=G<<28|Z>>>4,ve=Z<<28|G>>>4,we=_e<<23|Ur>>>9,pr=Ur<<23|_e>>>9,ye=Ee<<25|Vr>>>7,be=Vr<<25|Ee>>>7,Nt=Se<<21|ke>>>11,Lt=ke<<21|Se>>>11,xt=Me<<24|zr>>>8,Tt=zr<<24|Me>>>8,Pt=Re<<27|Wr>>>5,$t=Wr<<27|Re>>>5,Ot=Ie<<20|Ce>>>12,Bt=Ce<<20|Ie>>>12,Dt=Ae<<7|qr>>>25,jt=qr<<7|Ae>>>25,Ft=Ne<<8|Jr>>>24,Ht=Jr<<8|Ne>>>24,Ut=Le<<14|xe>>>18,Vt=xe<<14|Le>>>18;e[0]=sr^~cr&dr,e[1]=K^~ie&fe,e[10]=gr^~Ot&Y,e[11]=ve^~Bt&ee,e[20]=ne^~he&ye,e[21]=se^~de&be,e[30]=Pt^~X&oe,e[31]=$t^~ir&lr,e[40]=ue^~we&Dt,e[41]=hr^~pr&jt,e[2]=cr^~dr&Nt,e[3]=ie^~fe&Lt,e[12]=Ot^~Y&ae,e[13]=Bt^~ee&ce,e[22]=he^~ye&Ft,e[23]=de^~be&Ht,e[32]=X^~oe&ge,e[33]=ir^~lr&fr,e[42]=we^~Dt&or,e[43]=pr^~jt&te,e[4]=dr^~Nt&Ut,e[5]=fe^~Lt&Vt,e[14]=Y^~ae&pe,e[15]=ee^~ce&me,e[24]=ye^~Ft&re,e[25]=be^~Ht&ar,e[34]=oe^~ge&xt,e[35]=lr^~fr&Tt,e[44]=Dt^~or&ur,e[45]=jt^~te&le,e[6]=Nt^~Ut&sr,e[7]=Lt^~Vt&K,e[16]=ae^~pe&gr,e[17]=ce^~me&ve,e[26]=Ft^~re&ne,e[27]=Ht^~ar&se,e[36]=ge^~xt&Pt,e[37]=fr^~Tt&$t,e[46]=or^~ur&ue,e[47]=te^~le&hr,e[8]=Ut^~sr&cr,e[9]=Vt^~K&ie,e[18]=pe^~gr&Ot,e[19]=me^~ve&Bt,e[28]=re^~ne&he,e[29]=ar^~se&de,e[38]=xt^~Pt&X,e[39]=Tt^~$t&ir,e[48]=ur^~ue&we,e[49]=le^~hr&pr,e[0]^=co[t*2],e[1]^=co[t*2+1]}};const Hn=xa;function Dr(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}Dr.prototype.initialize=function(e,t){for(let r=0;r<50;++r)this.state[r]=0;this.blockSize=e/8,this.count=0,this.squeezing=!1};Dr.prototype.absorb=function(e){for(let t=0;t>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(Hn.p1600(this.state),this.count=0);return t};Dr.prototype.copy=function(e){for(let t=0;t<50;++t)e.state[t]=this.state[t];e.blockSize=this.blockSize,e.count=this.count,e.squeezing=this.squeezing};var Vu=Dr,zu=Uu(Vu);const Wu=zu,qu=qn;function Ta(e){return Buffer.allocUnsafe(e).fill(0)}function Pa(e,t,r){const n=Ta(t);return e=gs(e),r?e.length"u")throw new Error("Not an array?");if(r=ja(e),r!=="dynamic"&&r!==0&&t.length>r)throw new Error("Elements exceed array size: "+r);s=[],e=e.slice(0,e.lastIndexOf("[")),typeof t=="string"&&(t=JSON.parse(t));for(i in t)s.push(pt(e,t[i]));if(r==="dynamic"){var c=pt("uint256",t.length);s.unshift(c)}return Buffer.concat(s)}else{if(e==="bytes")return t=new Buffer(t),s=Buffer.concat([pt("uint256",t.length),t]),t.length%32!==0&&(s=Buffer.concat([s,Yt.zeros(32-t.length%32)])),s;if(e.startsWith("bytes")){if(r=Mr(e),r<1||r>32)throw new Error("Invalid bytes width: "+r);return Yt.setLengthRight(t,32)}else if(e.startsWith("uint")){if(r=Mr(e),r%8||r<8||r>256)throw new Error("Invalid uint width: "+r);if(n=Gt(t),n.bitLength()>r)throw new Error("Supplied uint exceeds width: "+r+" vs "+n.bitLength());if(n<0)throw new Error("Supplied uint is negative");return n.toArrayLike(Buffer,"be",32)}else if(e.startsWith("int")){if(r=Mr(e),r%8||r<8||r>256)throw new Error("Invalid int width: "+r);if(n=Gt(t),n.bitLength()>r)throw new Error("Supplied int exceeds width: "+r+" vs "+n.bitLength());return n.toTwos(256).toArrayLike(Buffer,"be",32)}else if(e.startsWith("ufixed")){if(r=lo(e),n=Gt(t),n<0)throw new Error("Supplied ufixed is negative");return pt("uint256",n.mul(new Qt(2).pow(new Qt(r[1]))))}else if(e.startsWith("fixed"))return r=lo(e),pt("int256",Gt(t).mul(new Qt(2).pow(new Qt(r[1]))))}throw new Error("Unsupported or invalid type: "+e)}function Ku(e){return e==="string"||e==="bytes"||ja(e)==="dynamic"}function Xu(e){return e.lastIndexOf("]")===e.length-1}function Yu(e,t){var r=[],n=[],s=32*e.length;for(var i in e){var c=Da(e[i]),u=t[i],h=pt(c,u);Ku(c)?(r.push(pt("uint256",s)),n.push(h),s+=h.length):r.push(h)}return Buffer.concat(r.concat(n))}function Fa(e,t){if(e.length!==t.length)throw new Error("Number of types are not matching the values");for(var r,n,s=[],i=0;i32)throw new Error("Invalid bytes width: "+r);s.push(Yt.setLengthRight(u,r))}else if(c.startsWith("uint")){if(r=Mr(c),r%8||r<8||r>256)throw new Error("Invalid uint width: "+r);if(n=Gt(u),n.bitLength()>r)throw new Error("Supplied uint exceeds width: "+r+" vs "+n.bitLength());s.push(n.toArrayLike(Buffer,"be",r/8))}else if(c.startsWith("int")){if(r=Mr(c),r%8||r<8||r>256)throw new Error("Invalid int width: "+r);if(n=Gt(u),n.bitLength()>r)throw new Error("Supplied int exceeds width: "+r+" vs "+n.bitLength());s.push(n.toTwos(r).toArrayLike(Buffer,"be",r/8))}else throw new Error("Unsupported or invalid type: "+c)}return Buffer.concat(s)}function eh(e,t){return Yt.keccak(Fa(e,t))}var th={rawEncode:Yu,solidityPack:Fa,soliditySHA3:eh};const lt=Ba,Xr=th,Ha={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},Js={encodeData(e,t,r,n=!0){const s=["bytes32"],i=[this.hashType(e,r)];if(n){const c=(u,h,f)=>{if(r[h]!==void 0)return["bytes32",f==null?"0x0000000000000000000000000000000000000000000000000000000000000000":lt.keccak(this.encodeData(h,f,r,n))];if(f===void 0)throw new Error(`missing value for field ${u} of type ${h}`);if(h==="bytes")return["bytes32",lt.keccak(f)];if(h==="string")return typeof f=="string"&&(f=Buffer.from(f,"utf8")),["bytes32",lt.keccak(f)];if(h.lastIndexOf("]")===h.length-1){const g=h.slice(0,h.lastIndexOf("[")),E=f.map(b=>c(u,g,b));return["bytes32",lt.keccak(Xr.rawEncode(E.map(([b])=>b),E.map(([,b])=>b)))]}return[h,f]};for(const u of r[e]){const[h,f]=c(u.name,u.type,t[u.name]);s.push(h),i.push(f)}}else for(const c of r[e]){let u=t[c.name];if(u!==void 0)if(c.type==="bytes")s.push("bytes32"),u=lt.keccak(u),i.push(u);else if(c.type==="string")s.push("bytes32"),typeof u=="string"&&(u=Buffer.from(u,"utf8")),u=lt.keccak(u),i.push(u);else if(r[c.type]!==void 0)s.push("bytes32"),u=lt.keccak(this.encodeData(c.type,u,r,n)),i.push(u);else{if(c.type.lastIndexOf("]")===c.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");s.push(c.type),i.push(u)}}return Xr.rawEncode(s,i)},encodeType(e,t){let r="",n=this.findTypeDependencies(e,t).filter(s=>s!==e);n=[e].concat(n.sort());for(const s of n){if(!t[s])throw new Error("No type definition specified: "+s);r+=s+"("+t[s].map(({name:c,type:u})=>u+" "+c).join(",")+")"}return r},findTypeDependencies(e,t,r=[]){if(e=e.match(/^\w*/)[0],r.includes(e)||t[e]===void 0)return r;r.push(e);for(const n of t[e])for(const s of this.findTypeDependencies(n.type,t,r))!r.includes(s)&&r.push(s);return r},hashStruct(e,t,r,n=!0){return lt.keccak(this.encodeData(e,t,r,n))},hashType(e,t){return lt.keccak(this.encodeType(e,t))},sanitizeData(e){const t={};for(const r in Ha.properties)e[r]&&(t[r]=e[r]);return t.types&&(t.types=Object.assign({EIP712Domain:[]},t.types)),t},hash(e,t=!0){const r=this.sanitizeData(e),n=[Buffer.from("1901","hex")];return n.push(this.hashStruct("EIP712Domain",r.domain,r.types,t)),r.primaryType!=="EIP712Domain"&&n.push(this.hashStruct(r.primaryType,r.message,r.types,t)),lt.keccak(Buffer.concat(n))}};var rh={TYPED_MESSAGE_SCHEMA:Ha,TypedDataUtils:Js,hashForSignTypedDataLegacy:function(e){return nh(e.data)},hashForSignTypedData_v3:function(e){return Js.hash(e.data,!1)},hashForSignTypedData_v4:function(e){return Js.hash(e.data)}};function nh(e){const t=new Error("Expect argument to be non-empty array");if(typeof e!="object"||!e.length)throw t;const r=e.map(function(i){return i.type==="bytes"?lt.toBuffer(i.value):i.value}),n=e.map(function(i){return i.type}),s=e.map(function(i){if(!i.name)throw t;return i.type+" "+i.name});return Xr.soliditySHA3(["bytes32","bytes32"],[Xr.soliditySHA3(new Array(e.length).fill("string"),s),Xr.soliditySHA3(n,r)])}var Lr={};Object.defineProperty(Lr,"__esModule",{value:!0});Lr.filterFromParam=Lr.FilterPolyfill=void 0;const Er=Fe,Ge=T,sh=5*60*1e3,Zt={jsonrpc:"2.0",id:0};class ih{constructor(t){this.logFilters=new Map,this.blockFilters=new Set,this.pendingTransactionFilters=new Set,this.cursors=new Map,this.timeouts=new Map,this.nextFilterId=(0,Er.IntNumber)(1),this.REQUEST_THROTTLE_INTERVAL=1e3,this.lastFetchTimestamp=new Date(0),this.resolvers=[],this.provider=t}async newFilter(t){const r=Ua(t),n=this.makeFilterId(),s=await this.setInitialCursorPosition(n,r.fromBlock);return console.info(`Installing new log filter(${n}):`,r,"initial cursor position:",s),this.logFilters.set(n,r),this.setFilterTimeout(n),(0,Ge.hexStringFromIntNumber)(n)}async newBlockFilter(){const t=this.makeFilterId(),r=await this.setInitialCursorPosition(t,"latest");return console.info(`Installing new block filter (${t}) with initial cursor position:`,r),this.blockFilters.add(t),this.setFilterTimeout(t),(0,Ge.hexStringFromIntNumber)(t)}async newPendingTransactionFilter(){const t=this.makeFilterId(),r=await this.setInitialCursorPosition(t,"latest");return console.info(`Installing new block filter (${t}) with initial cursor position:`,r),this.pendingTransactionFilters.add(t),this.setFilterTimeout(t),(0,Ge.hexStringFromIntNumber)(t)}uninstallFilter(t){const r=(0,Ge.intNumberFromHexString)(t);return console.info(`Uninstalling filter (${r})`),this.deleteFilter(r),!0}getFilterChanges(t){const r=(0,Ge.intNumberFromHexString)(t);return this.timeouts.has(r)&&this.setFilterTimeout(r),this.logFilters.has(r)?this.getLogFilterChanges(r):this.blockFilters.has(r)?this.getBlockFilterChanges(r):this.pendingTransactionFilters.has(r)?this.getPendingTransactionFilterChanges(r):Promise.resolve(An())}async getFilterLogs(t){const r=(0,Ge.intNumberFromHexString)(t),n=this.logFilters.get(r);return n?this.sendAsyncPromise(Object.assign(Object.assign({},Zt),{method:"eth_getLogs",params:[uo(n)]})):An()}makeFilterId(){return(0,Er.IntNumber)(++this.nextFilterId)}sendAsyncPromise(t){return new Promise((r,n)=>{this.provider.sendAsync(t,(s,i)=>{if(s)return n(s);if(Array.isArray(i)||i==null)return n(new Error(`unexpected response received: ${JSON.stringify(i)}`));r(i)})})}deleteFilter(t){console.info(`Deleting filter (${t})`),this.logFilters.delete(t),this.blockFilters.delete(t),this.pendingTransactionFilters.delete(t),this.cursors.delete(t),this.timeouts.delete(t)}async getLogFilterChanges(t){const r=this.logFilters.get(t),n=this.cursors.get(t);if(!n||!r)return An();const s=await this.getCurrentBlockHeight(),i=r.toBlock==="latest"?s:r.toBlock;if(n>s||n>Number(r.toBlock))return Nn();console.info(`Fetching logs from ${n} to ${i} for filter ${t}`);const c=await this.sendAsyncPromise(Object.assign(Object.assign({},Zt),{method:"eth_getLogs",params:[uo(Object.assign(Object.assign({},r),{fromBlock:n,toBlock:i}))]}));if(Array.isArray(c.result)){const u=c.result.map(f=>(0,Ge.intNumberFromHexString)(f.blockNumber||"0x0")),h=Math.max(...u);if(h&&h>n){const f=(0,Er.IntNumber)(h+1);console.info(`Moving cursor position for filter (${t}) from ${n} to ${f}`),this.cursors.set(t,f)}}return c}async getBlockFilterChanges(t){const r=this.cursors.get(t);if(!r)return An();const n=await this.getCurrentBlockHeight();if(r>n)return Nn();console.info(`Fetching blocks from ${r} to ${n} for filter (${t})`);const s=(await Promise.all((0,Ge.range)(r,n+1).map(c=>this.getBlockHashByNumber((0,Er.IntNumber)(c))))).filter(c=>!!c),i=(0,Er.IntNumber)(r+s.length);return console.info(`Moving cursor position for filter (${t}) from ${r} to ${i}`),this.cursors.set(t,i),Object.assign(Object.assign({},Zt),{result:s})}async getPendingTransactionFilterChanges(t){return Promise.resolve(Nn())}async setInitialCursorPosition(t,r){const n=await this.getCurrentBlockHeight(),s=typeof r=="number"&&r>n?r:n;return this.cursors.set(t,s),s}setFilterTimeout(t){const r=this.timeouts.get(t);r&&window.clearTimeout(r);const n=window.setTimeout(()=>{console.info(`Filter (${t}) timed out`),this.deleteFilter(t)},sh);this.timeouts.set(t,n)}async getCurrentBlockHeight(){const t=new Date;if(t.getTime()-this.lastFetchTimestamp.getTime()>this.REQUEST_THROTTLE_INTERVAL){this.lastFetchTimestamp=t;const r=await this._getCurrentBlockHeight();this.currentBlockHeight=r,this.resolvers.forEach(n=>n(r)),this.resolvers=[]}return this.currentBlockHeight?this.currentBlockHeight:new Promise(r=>this.resolvers.push(r))}async _getCurrentBlockHeight(){const{result:t}=await this.sendAsyncPromise(Object.assign(Object.assign({},Zt),{method:"eth_blockNumber",params:[]}));return(0,Ge.intNumberFromHexString)((0,Ge.ensureHexString)(t))}async getBlockHashByNumber(t){const r=await this.sendAsyncPromise(Object.assign(Object.assign({},Zt),{method:"eth_getBlockByNumber",params:[(0,Ge.hexStringFromIntNumber)(t),!1]}));return r.result&&typeof r.result.hash=="string"?(0,Ge.ensureHexString)(r.result.hash):null}}Lr.FilterPolyfill=ih;function Ua(e){return{fromBlock:ho(e.fromBlock),toBlock:ho(e.toBlock),addresses:e.address===void 0?null:Array.isArray(e.address)?e.address:[e.address],topics:e.topics||[]}}Lr.filterFromParam=Ua;function uo(e){const t={fromBlock:fo(e.fromBlock),toBlock:fo(e.toBlock),topics:e.topics};return e.addresses!==null&&(t.address=e.addresses),t}function ho(e){if(e===void 0||e==="latest"||e==="pending")return"latest";if(e==="earliest")return(0,Er.IntNumber)(0);if((0,Ge.isHexString)(e))return(0,Ge.intNumberFromHexString)(e);throw new Error(`Invalid block option: ${String(e)}`)}function fo(e){return e==="latest"?e:(0,Ge.hexStringFromIntNumber)(e)}function An(){return Object.assign(Object.assign({},Zt),{error:{code:-32e3,message:"filter not found"}})}function Nn(){return Object.assign(Object.assign({},Zt),{result:[]})}var ps={},Va={},ms={},_i=oh;function oh(e){e=e||{};var t=e.max||Number.MAX_SAFE_INTEGER,r=typeof e.start<"u"?e.start:Math.floor(Math.random()*t);return function(){return r=r%t,r++}}const go=(e,t)=>function(){const r=t.promiseModule,n=new Array(arguments.length);for(let s=0;s{t.errorFirst?n.push(function(c,u){if(t.multiArgs){const h=new Array(arguments.length-1);for(let f=1;f{t=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},t);const r=s=>{const i=c=>typeof c=="string"?s===c:c.test(s);return t.include?t.include.some(i):!t.exclude.some(i)};let n;typeof e=="function"?n=function(){return t.excludeMain?e.apply(this,arguments):go(e,t).apply(this,arguments)}:n=Object.create(Object.getPrototypeOf(e));for(const s in e){const i=e[s];n[s]=typeof i=="function"&&r(s)?go(i,t):i}return n},gn={},pn={};Object.defineProperty(pn,"__esModule",{value:!0});const ch=sa;function po(e,t,r){try{Reflect.apply(e,t,r)}catch(n){setTimeout(()=>{throw n})}}function lh(e){const t=e.length,r=new Array(t);for(let n=0;n0&&([c]=r),c instanceof Error)throw c;const u=new Error(`Unhandled error.${c?` (${c.message})`:""}`);throw u.context=c,u}const i=s[t];if(i===void 0)return!1;if(typeof i=="function")po(i,this,r);else{const c=i.length,u=lh(i);for(let h=0;he+t,mo=["sync","latest"];class ph extends dh.default{constructor(t){super(),this._blockResetDuration=t.blockResetDuration||20*fh,this._usePastBlocks=t.usePastBlocks||!1,this._currentBlock=null,this._isRunning=!1,this._onNewListener=this._onNewListener.bind(this),this._onRemoveListener=this._onRemoveListener.bind(this),this._resetCurrentBlock=this._resetCurrentBlock.bind(this),this._setupInternalEvents()}async destroy(){this._cancelBlockResetTimeout(),await this._maybeEnd(),super.removeAllListeners()}isRunning(){return this._isRunning}getCurrentBlock(){return this._currentBlock}async getLatestBlock(){return this._currentBlock?this._currentBlock:await new Promise(r=>this.once("latest",r))}removeAllListeners(t){return t?super.removeAllListeners(t):super.removeAllListeners(),this._setupInternalEvents(),this._onRemoveListener(),this}_setupInternalEvents(){this.removeListener("newListener",this._onNewListener),this.removeListener("removeListener",this._onRemoveListener),this.on("newListener",this._onNewListener),this.on("removeListener",this._onRemoveListener)}_onNewListener(t){mo.includes(t)&&this._maybeStart()}_onRemoveListener(){this._getBlockTrackerEventCount()>0||this._maybeEnd()}async _maybeStart(){this._isRunning||(this._isRunning=!0,this._cancelBlockResetTimeout(),await this._start(),this.emit("_started"))}async _maybeEnd(){this._isRunning&&(this._isRunning=!1,this._setupBlockResetTimeout(),await this._end(),this.emit("_ended"))}_getBlockTrackerEventCount(){return mo.map(t=>this.listenerCount(t)).reduce(gh)}_shouldUseNewBlock(t){const r=this._currentBlock;if(!r)return!0;const n=vo(t),s=vo(r);return this._usePastBlocks&&ns}_newPotentialLatest(t){this._shouldUseNewBlock(t)&&this._setCurrentBlock(t)}_setCurrentBlock(t){const r=this._currentBlock;this._currentBlock=t,this.emit("latest",t),this.emit("sync",{oldBlock:r,newBlock:t})}_setupBlockResetTimeout(){this._cancelBlockResetTimeout(),this._blockResetTimeout=setTimeout(this._resetCurrentBlock,this._blockResetDuration),this._blockResetTimeout.unref&&this._blockResetTimeout.unref()}_cancelBlockResetTimeout(){this._blockResetTimeout&&clearTimeout(this._blockResetTimeout)}_resetCurrentBlock(){this._currentBlock=null}}gn.BaseBlockTracker=ph;function vo(e){return Number.parseInt(e,16)}var za={},Wa={},qe={};class qa extends TypeError{constructor(t,r){let n;const{message:s,explanation:i,...c}=t,{path:u}=t,h=u.length===0?s:`At path: ${u.join(".")} -- ${s}`;super(i??h),i!=null&&(this.cause=h),Object.assign(this,c),this.name=this.constructor.name,this.failures=()=>n??(n=[t,...r()])}}function mh(e){return at(e)&&typeof e[Symbol.iterator]=="function"}function at(e){return typeof e=="object"&&e!=null}function wo(e){if(Object.prototype.toString.call(e)!=="[object Object]")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function He(e){return typeof e=="symbol"?e.toString():typeof e=="string"?JSON.stringify(e):`${e}`}function vh(e){const{done:t,value:r}=e.next();return t?void 0:r}function wh(e,t,r,n){if(e===!0)return;e===!1?e={}:typeof e=="string"&&(e={message:e});const{path:s,branch:i}=t,{type:c}=r,{refinement:u,message:h=`Expected a value of type \`${c}\`${u?` with refinement \`${u}\``:""}, but received: \`${He(n)}\``}=e;return{value:n,type:c,refinement:u,key:s[s.length-1],path:s,branch:i,...e,message:h}}function*ii(e,t,r,n){mh(e)||(e=[e]);for(const s of e){const i=wh(s,t,r,n);i&&(yield i)}}function*Ei(e,t,r={}){const{path:n=[],branch:s=[e],coerce:i=!1,mask:c=!1}=r,u={path:n,branch:s};if(i&&(e=t.coercer(e,u),c&&t.type!=="type"&&at(t.schema)&&at(e)&&!Array.isArray(e)))for(const f in e)t.schema[f]===void 0&&delete e[f];let h="valid";for(const f of t.validator(e,u))f.explanation=r.message,h="not_valid",yield[f,void 0];for(let[f,g,E]of t.entries(e,u)){const b=Ei(g,E,{path:f===void 0?n:[...n,f],branch:f===void 0?s:[...s,g],coerce:i,mask:c,message:r.message});for(const k of b)k[0]?(h=k[0].refinement!=null?"not_refined":"not_valid",yield[k[0],void 0]):i&&(g=k[1],f===void 0?e=g:e instanceof Map?e.set(f,g):e instanceof Set?e.add(g):at(e)&&(g!==void 0||f in e)&&(e[f]=g))}if(h!=="not_valid")for(const f of t.refiner(e,u))f.explanation=r.message,h="not_refined",yield[f,void 0];h==="valid"&&(yield[void 0,e])}class Oe{constructor(t){const{type:r,schema:n,validator:s,refiner:i,coercer:c=h=>h,entries:u=function*(){}}=t;this.type=r,this.schema=n,this.entries=u,this.coercer=c,s?this.validator=(h,f)=>{const g=s(h,f);return ii(g,f,this,h)}:this.validator=()=>[],i?this.refiner=(h,f)=>{const g=i(h,f);return ii(g,f,this,h)}:this.refiner=()=>[]}assert(t,r){return Ja(t,this,r)}create(t,r){return Ga(t,this,r)}is(t){return Si(t,this)}mask(t,r){return Za(t,this,r)}validate(t,r={}){return jr(t,this,r)}}function Ja(e,t,r){const n=jr(e,t,{message:r});if(n[0])throw n[0]}function Ga(e,t,r){const n=jr(e,t,{coerce:!0,message:r});if(n[0])throw n[0];return n[1]}function Za(e,t,r){const n=jr(e,t,{coerce:!0,mask:!0,message:r});if(n[0])throw n[0];return n[1]}function Si(e,t){return!jr(e,t)[0]}function jr(e,t,r={}){const n=Ei(e,t,r),s=vh(n);return s[0]?[new qa(s[0],function*(){for(const c of n)c[0]&&(yield c[0])}),void 0]:[void 0,s[1]]}function yh(...e){const t=e[0].type==="type",r=e.map(s=>s.schema),n=Object.assign({},...r);return t?vn(n):mn(n)}function Xe(e,t){return new Oe({type:e,schema:null,validator:t})}function bh(e,t){return new Oe({...e,refiner:(r,n)=>r===void 0||e.refiner(r,n),validator(r,n){return r===void 0?!0:(t(r,n),e.validator(r,n))}})}function _h(e){return new Oe({type:"dynamic",schema:null,*entries(t,r){yield*e(t,r).entries(t,r)},validator(t,r){return e(t,r).validator(t,r)},coercer(t,r){return e(t,r).coercer(t,r)},refiner(t,r){return e(t,r).refiner(t,r)}})}function Eh(e){let t;return new Oe({type:"lazy",schema:null,*entries(r,n){t??(t=e()),yield*t.entries(r,n)},validator(r,n){return t??(t=e()),t.validator(r,n)},coercer(r,n){return t??(t=e()),t.coercer(r,n)},refiner(r,n){return t??(t=e()),t.refiner(r,n)}})}function Sh(e,t){const{schema:r}=e,n={...r};for(const s of t)delete n[s];switch(e.type){case"type":return vn(n);default:return mn(n)}}function kh(e){const t=e instanceof Oe,r=t?{...e.schema}:{...e};for(const n in r)r[n]=Qa(r[n]);return t&&e.type==="type"?vn(r):mn(r)}function Mh(e,t){const{schema:r}=e,n={};for(const s of t)n[s]=r[s];switch(e.type){case"type":return vn(n);default:return mn(n)}}function Rh(e,t){return console.warn("superstruct@0.11 - The `struct` helper has been renamed to `define`."),Xe(e,t)}function Ih(){return Xe("any",()=>!0)}function Ch(e){return new Oe({type:"array",schema:e,*entries(t){if(e&&Array.isArray(t))for(const[r,n]of t.entries())yield[r,n,e]},coercer(t){return Array.isArray(t)?t.slice():t},validator(t){return Array.isArray(t)||`Expected an array value, but received: ${He(t)}`}})}function Ah(){return Xe("bigint",e=>typeof e=="bigint")}function Nh(){return Xe("boolean",e=>typeof e=="boolean")}function Lh(){return Xe("date",e=>e instanceof Date&&!isNaN(e.getTime())||`Expected a valid \`Date\` object, but received: ${He(e)}`)}function xh(e){const t={},r=e.map(n=>He(n)).join();for(const n of e)t[n]=n;return new Oe({type:"enums",schema:t,validator(n){return e.includes(n)||`Expected one of \`${r}\`, but received: ${He(n)}`}})}function Th(){return Xe("func",e=>typeof e=="function"||`Expected a function, but received: ${He(e)}`)}function Ph(e){return Xe("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${He(t)}`)}function $h(){return Xe("integer",e=>typeof e=="number"&&!isNaN(e)&&Number.isInteger(e)||`Expected an integer, but received: ${He(e)}`)}function Oh(e){return new Oe({type:"intersection",schema:null,*entries(t,r){for(const n of e)yield*n.entries(t,r)},*validator(t,r){for(const n of e)yield*n.validator(t,r)},*refiner(t,r){for(const n of e)yield*n.refiner(t,r)}})}function Bh(e){const t=He(e),r=typeof e;return new Oe({type:"literal",schema:r==="string"||r==="number"||r==="boolean"?e:null,validator(n){return n===e||`Expected the literal \`${t}\`, but received: ${He(n)}`}})}function Dh(e,t){return new Oe({type:"map",schema:null,*entries(r){if(e&&t&&r instanceof Map)for(const[n,s]of r.entries())yield[n,n,e],yield[n,s,t]},coercer(r){return r instanceof Map?new Map(r):r},validator(r){return r instanceof Map||`Expected a \`Map\` object, but received: ${He(r)}`}})}function ki(){return Xe("never",()=>!1)}function jh(e){return new Oe({...e,validator:(t,r)=>t===null||e.validator(t,r),refiner:(t,r)=>t===null||e.refiner(t,r)})}function Fh(){return Xe("number",e=>typeof e=="number"&&!isNaN(e)||`Expected a number, but received: ${He(e)}`)}function mn(e){const t=e?Object.keys(e):[],r=ki();return new Oe({type:"object",schema:e||null,*entries(n){if(e&&at(n)){const s=new Set(Object.keys(n));for(const i of t)s.delete(i),yield[i,n[i],e[i]];for(const i of s)yield[i,n[i],r]}},validator(n){return at(n)||`Expected an object, but received: ${He(n)}`},coercer(n){return at(n)?{...n}:n}})}function Qa(e){return new Oe({...e,validator:(t,r)=>t===void 0||e.validator(t,r),refiner:(t,r)=>t===void 0||e.refiner(t,r)})}function Hh(e,t){return new Oe({type:"record",schema:null,*entries(r){if(at(r))for(const n in r){const s=r[n];yield[n,n,e],yield[n,s,t]}},validator(r){return at(r)||`Expected an object, but received: ${He(r)}`}})}function Uh(){return Xe("regexp",e=>e instanceof RegExp)}function Vh(e){return new Oe({type:"set",schema:null,*entries(t){if(e&&t instanceof Set)for(const r of t)yield[r,r,e]},coercer(t){return t instanceof Set?new Set(t):t},validator(t){return t instanceof Set||`Expected a \`Set\` object, but received: ${He(t)}`}})}function Ka(){return Xe("string",e=>typeof e=="string"||`Expected a string, but received: ${He(e)}`)}function zh(e){const t=ki();return new Oe({type:"tuple",schema:null,*entries(r){if(Array.isArray(r)){const n=Math.max(e.length,r.length);for(let s=0;sr.type).join(" | ");return new Oe({type:"union",schema:null,coercer(r){for(const n of e){const[s,i]=n.validate(r,{coerce:!0});if(!s)return i}return r},validator(r,n){const s=[];for(const i of e){const[...c]=Ei(r,i,n),[u]=c;if(u[0])for(const[h]of c)h&&s.push(h);else return[]}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${He(r)}`,...s]}})}function Xa(){return Xe("unknown",()=>!0)}function Mi(e,t,r){return new Oe({...e,coercer:(n,s)=>Si(n,t)?e.coercer(r(n,s),s):e.coercer(n,s)})}function qh(e,t,r={}){return Mi(e,Xa(),n=>{const s=typeof t=="function"?t():t;if(n===void 0)return s;if(!r.strict&&wo(n)&&wo(s)){const i={...n};let c=!1;for(const u in s)i[u]===void 0&&(i[u]=s[u],c=!0);if(c)return i}return n})}function Jh(e){return Mi(e,Ka(),t=>t.trim())}function Gh(e){return rr(e,"empty",t=>{const r=Ya(t);return r===0||`Expected an empty ${e.type} but received one with a size of \`${r}\``})}function Ya(e){return e instanceof Map||e instanceof Set?e.size:e.length}function Zh(e,t,r={}){const{exclusive:n}=r;return rr(e,"max",s=>n?sn?s>t:s>=t||`Expected a ${e.type} greater than ${n?"":"or equal to "}${t} but received \`${s}\``)}function Kh(e){return rr(e,"nonempty",t=>Ya(t)>0||`Expected a nonempty ${e.type} but received an empty one`)}function Xh(e,t){return rr(e,"pattern",r=>t.test(r)||`Expected a ${e.type} matching \`/${t.source}/\` but received "${r}"`)}function Yh(e,t,r=t){const n=`Expected a ${e.type}`,s=t===r?`of \`${t}\``:`between \`${t}\` and \`${r}\``;return rr(e,"size",i=>{if(typeof i=="number"||i instanceof Date)return t<=i&&i<=r||`${n} ${s} but received \`${i}\``;if(i instanceof Map||i instanceof Set){const{size:c}=i;return t<=c&&c<=r||`${n} with a size ${s} but received one with a size of \`${c}\``}else{const{length:c}=i;return t<=c&&c<=r||`${n} with a length ${s} but received one with a length of \`${c}\``}})}function rr(e,t,r){return new Oe({...e,*refiner(n,s){yield*e.refiner(n,s);const i=r(n,s),c=ii(i,s,e,n);for(const u of c)yield{...u,refinement:t}}})}const ed=Object.freeze(Object.defineProperty({__proto__:null,Struct:Oe,StructError:qa,any:Ih,array:Ch,assert:Ja,assign:yh,bigint:Ah,boolean:Nh,coerce:Mi,create:Ga,date:Lh,defaulted:qh,define:Xe,deprecated:bh,dynamic:_h,empty:Gh,enums:xh,func:Th,instance:Ph,integer:$h,intersection:Oh,is:Si,lazy:Eh,literal:Bh,map:Dh,mask:Za,max:Zh,min:Qh,never:ki,nonempty:Kh,nullable:jh,number:Fh,object:mn,omit:Sh,optional:Qa,partial:kh,pattern:Xh,pick:Mh,record:Hh,refine:rr,regexp:Uh,set:Vh,size:Yh,string:Ka,struct:Rh,trimmed:Jh,tuple:zh,type:vn,union:Wh,unknown:Xa,validate:jr},Symbol.toStringTag,{value:"Module"})),nr=rn(ed);Object.defineProperty(qe,"__esModule",{value:!0});qe.assertExhaustive=qe.assertStruct=qe.assert=qe.AssertionError=void 0;const td=nr;function rd(e){return typeof e=="object"&&e!==null&&"message"in e}function nd(e){var t,r;return typeof((r=(t=e?.prototype)===null||t===void 0?void 0:t.constructor)===null||r===void 0?void 0:r.name)=="string"}function sd(e){const t=rd(e)?e.message:String(e);return t.endsWith(".")?t.slice(0,-1):t}function ec(e,t){return nd(e)?new e({message:t}):e({message:t})}class Ri extends Error{constructor(t){super(t.message),this.code="ERR_ASSERTION"}}qe.AssertionError=Ri;function id(e,t="Assertion failed.",r=Ri){if(!e)throw t instanceof Error?t:ec(r,t)}qe.assert=id;function od(e,t,r="Assertion failed",n=Ri){try{(0,td.assert)(e,t)}catch(s){throw ec(n,`${r}: ${sd(s)}.`)}}qe.assertStruct=od;function ad(e){throw new Error("Invalid branch reached. Should be detected during compilation.")}qe.assertExhaustive=ad;var wn={};Object.defineProperty(wn,"__esModule",{value:!0});wn.base64=void 0;const cd=nr,ld=qe,ud=(e,t={})=>{var r,n;const s=(r=t.paddingRequired)!==null&&r!==void 0?r:!1,i=(n=t.characterSet)!==null&&n!==void 0?n:"base64";let c;i==="base64"?c=String.raw`[A-Za-z0-9+\/]`:((0,ld.assert)(i==="base64url"),c=String.raw`[-_A-Za-z0-9]`);let u;return s?u=new RegExp(`^(?:${c}{4})*(?:${c}{3}=|${c}{2}==)?$`,"u"):u=new RegExp(`^(?:${c}{4})*(?:${c}{2,3}|${c}{3}=|${c}{2}==)?$`,"u"),(0,cd.pattern)(e,u)};wn.base64=ud;var W={},yn={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.remove0x=e.add0x=e.assertIsStrictHexString=e.assertIsHexString=e.isStrictHexString=e.isHexString=e.StrictHexStruct=e.HexStruct=void 0;const t=nr,r=qe;e.HexStruct=(0,t.pattern)((0,t.string)(),/^(?:0x)?[0-9a-f]+$/iu),e.StrictHexStruct=(0,t.pattern)((0,t.string)(),/^0x[0-9a-f]+$/iu);function n(f){return(0,t.is)(f,e.HexStruct)}e.isHexString=n;function s(f){return(0,t.is)(f,e.StrictHexStruct)}e.isStrictHexString=s;function i(f){(0,r.assert)(n(f),"Value must be a hexadecimal string.")}e.assertIsHexString=i;function c(f){(0,r.assert)(s(f),'Value must be a hexadecimal string, starting with "0x".')}e.assertIsStrictHexString=c;function u(f){return f.startsWith("0x")?f:f.startsWith("0X")?`0x${f.substring(2)}`:`0x${f}`}e.add0x=u;function h(f){return f.startsWith("0x")||f.startsWith("0X")?f.substring(2):f}e.remove0x=h})(yn);Object.defineProperty(W,"__esModule",{value:!0});W.createDataView=W.concatBytes=W.valueToBytes=W.stringToBytes=W.numberToBytes=W.signedBigIntToBytes=W.bigIntToBytes=W.hexToBytes=W.bytesToString=W.bytesToNumber=W.bytesToSignedBigInt=W.bytesToBigInt=W.bytesToHex=W.assertIsBytes=W.isBytes=void 0;const tt=qe,oi=yn,yo=48,bo=58,_o=87;function hd(){const e=[];return()=>{if(e.length===0)for(let t=0;t<256;t++)e.push(t.toString(16).padStart(2,"0"));return e}}const dd=hd();function Ii(e){return e instanceof Uint8Array}W.isBytes=Ii;function Fr(e){(0,tt.assert)(Ii(e),"Value must be a Uint8Array.")}W.assertIsBytes=Fr;function tc(e){if(Fr(e),e.length===0)return"0x";const t=dd(),r=new Array(e.length);for(let n=0;n=BigInt(0),"Value must be a non-negative bigint.");const t=e.toString(16);return vs(t)}W.bigIntToBytes=nc;function md(e,t){(0,tt.assert)(t>0);const r=e>>BigInt(31);return!((~e&r)+(e&~r)>>BigInt(t*8+-1))}function vd(e,t){(0,tt.assert)(typeof e=="bigint","Value must be a bigint."),(0,tt.assert)(typeof t=="number","Byte length must be a number."),(0,tt.assert)(t>0,"Byte length must be greater than 0."),(0,tt.assert)(md(e,t),"Byte length is too small to represent the given value.");let r=e;const n=new Uint8Array(t);for(let s=0;s>=BigInt(8);return n.reverse()}W.signedBigIntToBytes=vd;function sc(e){(0,tt.assert)(typeof e=="number","Value must be a number."),(0,tt.assert)(e>=0,"Value must be a non-negative number."),(0,tt.assert)(Number.isSafeInteger(e),"Value is not a safe integer. Use `bigIntToBytes` instead.");const t=e.toString(16);return vs(t)}W.numberToBytes=sc;function ic(e){return(0,tt.assert)(typeof e=="string","Value must be a string."),new TextEncoder().encode(e)}W.stringToBytes=ic;function oc(e){if(typeof e=="bigint")return nc(e);if(typeof e=="number")return sc(e);if(typeof e=="string")return e.startsWith("0x")?vs(e):ic(e);if(Ii(e))return e;throw new TypeError(`Unsupported value type: "${typeof e}".`)}W.valueToBytes=oc;function wd(e){const t=new Array(e.length);let r=0;for(let s=0;st.call(r,n,s,this))}get(t){return Ze(this,ct,"f").get(t)}has(t){return Ze(this,ct,"f").has(t)}keys(){return Ze(this,ct,"f").keys()}values(){return Ze(this,ct,"f").values()}toString(){return`FrozenMap(${this.size}) {${this.size>0?` ${[...this.entries()].map(([t,r])=>`${String(t)} => ${String(r)}`).join(", ")} `:""}}`}}xr.FrozenMap=Ci;class Ai{constructor(t){ft.set(this,void 0),lc(this,ft,new Set(t),"f"),Object.freeze(this)}get size(){return Ze(this,ft,"f").size}[(ft=new WeakMap,Symbol.iterator)](){return Ze(this,ft,"f")[Symbol.iterator]()}entries(){return Ze(this,ft,"f").entries()}forEach(t,r){return Ze(this,ft,"f").forEach((n,s,i)=>t.call(r,n,s,this))}has(t){return Ze(this,ft,"f").has(t)}keys(){return Ze(this,ft,"f").keys()}values(){return Ze(this,ft,"f").values()}toString(){return`FrozenSet(${this.size}) {${this.size>0?` ${[...this.values()].map(t=>String(t)).join(", ")} `:""}}`}}xr.FrozenSet=Ai;Object.freeze(Ci);Object.freeze(Ci.prototype);Object.freeze(Ai);Object.freeze(Ai.prototype);var uc={};Object.defineProperty(uc,"__esModule",{value:!0});var hc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getJsonRpcIdValidator=e.assertIsJsonRpcError=e.isJsonRpcError=e.assertIsJsonRpcFailure=e.isJsonRpcFailure=e.assertIsJsonRpcSuccess=e.isJsonRpcSuccess=e.assertIsJsonRpcResponse=e.isJsonRpcResponse=e.assertIsPendingJsonRpcResponse=e.isPendingJsonRpcResponse=e.JsonRpcResponseStruct=e.JsonRpcFailureStruct=e.JsonRpcSuccessStruct=e.PendingJsonRpcResponseStruct=e.assertIsJsonRpcRequest=e.isJsonRpcRequest=e.assertIsJsonRpcNotification=e.isJsonRpcNotification=e.JsonRpcNotificationStruct=e.JsonRpcRequestStruct=e.JsonRpcParamsStruct=e.JsonRpcErrorStruct=e.JsonRpcIdStruct=e.JsonRpcVersionStruct=e.jsonrpc2=e.getJsonSize=e.isValidJson=e.JsonStruct=e.UnsafeJsonStruct=void 0;const t=nr,r=qe,n=()=>(0,t.define)("finite number",A=>(0,t.is)(A,(0,t.number)())&&Number.isFinite(A));e.UnsafeJsonStruct=(0,t.union)([(0,t.literal)(null),(0,t.boolean)(),n(),(0,t.string)(),(0,t.array)((0,t.lazy)(()=>e.UnsafeJsonStruct)),(0,t.record)((0,t.string)(),(0,t.lazy)(()=>e.UnsafeJsonStruct))]),e.JsonStruct=(0,t.define)("Json",(A,$)=>{function J(De,Ve){const U=[...Ve.validator(De,$)];return U.length>0?U:!0}try{const De=J(A,e.UnsafeJsonStruct);return De!==!0?De:J(JSON.parse(JSON.stringify(A)),e.UnsafeJsonStruct)}catch(De){return De instanceof RangeError?"Circular reference detected":!1}});function s(A){return(0,t.is)(A,e.JsonStruct)}e.isValidJson=s;function i(A){(0,r.assertStruct)(A,e.JsonStruct,"Invalid JSON value");const $=JSON.stringify(A);return new TextEncoder().encode($).byteLength}e.getJsonSize=i,e.jsonrpc2="2.0",e.JsonRpcVersionStruct=(0,t.literal)(e.jsonrpc2),e.JsonRpcIdStruct=(0,t.nullable)((0,t.union)([(0,t.number)(),(0,t.string)()])),e.JsonRpcErrorStruct=(0,t.object)({code:(0,t.integer)(),message:(0,t.string)(),data:(0,t.optional)(e.JsonStruct),stack:(0,t.optional)((0,t.string)())}),e.JsonRpcParamsStruct=(0,t.optional)((0,t.union)([(0,t.record)((0,t.string)(),e.JsonStruct),(0,t.array)(e.JsonStruct)])),e.JsonRpcRequestStruct=(0,t.object)({id:e.JsonRpcIdStruct,jsonrpc:e.JsonRpcVersionStruct,method:(0,t.string)(),params:e.JsonRpcParamsStruct}),e.JsonRpcNotificationStruct=(0,t.omit)(e.JsonRpcRequestStruct,["id"]);function c(A){return(0,t.is)(A,e.JsonRpcNotificationStruct)}e.isJsonRpcNotification=c;function u(A,$){(0,r.assertStruct)(A,e.JsonRpcNotificationStruct,"Invalid JSON-RPC notification",$)}e.assertIsJsonRpcNotification=u;function h(A){return(0,t.is)(A,e.JsonRpcRequestStruct)}e.isJsonRpcRequest=h;function f(A,$){(0,r.assertStruct)(A,e.JsonRpcRequestStruct,"Invalid JSON-RPC request",$)}e.assertIsJsonRpcRequest=f,e.PendingJsonRpcResponseStruct=(0,t.object)({id:e.JsonRpcIdStruct,jsonrpc:e.JsonRpcVersionStruct,result:(0,t.optional)((0,t.unknown)()),error:(0,t.optional)(e.JsonRpcErrorStruct)}),e.JsonRpcSuccessStruct=(0,t.object)({id:e.JsonRpcIdStruct,jsonrpc:e.JsonRpcVersionStruct,result:e.JsonStruct}),e.JsonRpcFailureStruct=(0,t.object)({id:e.JsonRpcIdStruct,jsonrpc:e.JsonRpcVersionStruct,error:e.JsonRpcErrorStruct}),e.JsonRpcResponseStruct=(0,t.union)([e.JsonRpcSuccessStruct,e.JsonRpcFailureStruct]);function g(A){return(0,t.is)(A,e.PendingJsonRpcResponseStruct)}e.isPendingJsonRpcResponse=g;function E(A,$){(0,r.assertStruct)(A,e.PendingJsonRpcResponseStruct,"Invalid pending JSON-RPC response",$)}e.assertIsPendingJsonRpcResponse=E;function b(A){return(0,t.is)(A,e.JsonRpcResponseStruct)}e.isJsonRpcResponse=b;function k(A,$){(0,r.assertStruct)(A,e.JsonRpcResponseStruct,"Invalid JSON-RPC response",$)}e.assertIsJsonRpcResponse=k;function C(A){return(0,t.is)(A,e.JsonRpcSuccessStruct)}e.isJsonRpcSuccess=C;function R(A,$){(0,r.assertStruct)(A,e.JsonRpcSuccessStruct,"Invalid JSON-RPC success response",$)}e.assertIsJsonRpcSuccess=R;function I(A){return(0,t.is)(A,e.JsonRpcFailureStruct)}e.isJsonRpcFailure=I;function P(A,$){(0,r.assertStruct)(A,e.JsonRpcFailureStruct,"Invalid JSON-RPC failure response",$)}e.assertIsJsonRpcFailure=P;function L(A){return(0,t.is)(A,e.JsonRpcErrorStruct)}e.isJsonRpcError=L;function M(A,$){(0,r.assertStruct)(A,e.JsonRpcErrorStruct,"Invalid JSON-RPC error",$)}e.assertIsJsonRpcError=M;function j(A){const{permitEmptyString:$,permitFractions:J,permitNull:De}=Object.assign({permitEmptyString:!0,permitFractions:!1,permitNull:!0},A);return Q=>!!(typeof Q=="number"&&(J||Number.isInteger(Q))||typeof Q=="string"&&($||Q.length>0)||De&&Q===null)}e.getJsonRpcIdValidator=j})(hc);var dc={};Object.defineProperty(dc,"__esModule",{value:!0});var Tr={},Nd=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Tr,"__esModule",{value:!0});Tr.createModuleLogger=Tr.createProjectLogger=void 0;const Ld=Nd(Hc),xd=(0,Ld.default)("metamask");function Td(e){return xd.extend(e)}Tr.createProjectLogger=Td;function Pd(e,t){return e.extend(t)}Tr.createModuleLogger=Pd;var fc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.calculateNumberSize=e.calculateStringSize=e.isASCII=e.isPlainObject=e.ESCAPE_CHARACTERS_REGEXP=e.JsonSize=e.hasProperty=e.isObject=e.isNullOrUndefined=e.isNonEmptyArray=void 0;function t(f){return Array.isArray(f)&&f.length>0}e.isNonEmptyArray=t;function r(f){return f==null}e.isNullOrUndefined=r;function n(f){return!!f&&typeof f=="object"&&!Array.isArray(f)}e.isObject=n;const s=(f,g)=>Object.hasOwnProperty.call(f,g);e.hasProperty=s,function(f){f[f.Null=4]="Null",f[f.Comma=1]="Comma",f[f.Wrapper=1]="Wrapper",f[f.True=4]="True",f[f.False=5]="False",f[f.Quote=1]="Quote",f[f.Colon=1]="Colon",f[f.Date=24]="Date"}(e.JsonSize||(e.JsonSize={})),e.ESCAPE_CHARACTERS_REGEXP=/"|\\|\n|\r|\t/gu;function i(f){if(typeof f!="object"||f===null)return!1;try{let g=f;for(;Object.getPrototypeOf(g)!==null;)g=Object.getPrototypeOf(g);return Object.getPrototypeOf(f)===g}catch{return!1}}e.isPlainObject=i;function c(f){return f.charCodeAt(0)<=127}e.isASCII=c;function u(f){var g;return f.split("").reduce((b,k)=>c(k)?b+1:b+2,0)+((g=f.match(e.ESCAPE_CHARACTERS_REGEXP))!==null&&g!==void 0?g:[]).length}e.calculateStringSize=u;function h(f){return f.toString().length}e.calculateNumberSize=h})(fc);var bt={};Object.defineProperty(bt,"__esModule",{value:!0});bt.hexToBigInt=bt.hexToNumber=bt.bigIntToHex=bt.numberToHex=void 0;const Rr=qe,en=yn,$d=e=>((0,Rr.assert)(typeof e=="number","Value must be a number."),(0,Rr.assert)(e>=0,"Value must be a non-negative number."),(0,Rr.assert)(Number.isSafeInteger(e),"Value is not a safe integer. Use `bigIntToHex` instead."),(0,en.add0x)(e.toString(16)));bt.numberToHex=$d;const Od=e=>((0,Rr.assert)(typeof e=="bigint","Value must be a bigint."),(0,Rr.assert)(e>=0,"Value must be a non-negative bigint."),(0,en.add0x)(e.toString(16)));bt.bigIntToHex=Od;const Bd=e=>{(0,en.assertIsHexString)(e);const t=parseInt(e,16);return(0,Rr.assert)(Number.isSafeInteger(t),"Value is not a safe integer. Use `hexToBigInt` instead."),t};bt.hexToNumber=Bd;const Dd=e=>((0,en.assertIsHexString)(e),BigInt((0,en.add0x)(e)));bt.hexToBigInt=Dd;var gc={};Object.defineProperty(gc,"__esModule",{value:!0});var pc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.timeSince=e.inMilliseconds=e.Duration=void 0,function(i){i[i.Millisecond=1]="Millisecond",i[i.Second=1e3]="Second",i[i.Minute=6e4]="Minute",i[i.Hour=36e5]="Hour",i[i.Day=864e5]="Day",i[i.Week=6048e5]="Week",i[i.Year=31536e6]="Year"}(e.Duration||(e.Duration={}));const t=i=>Number.isInteger(i)&&i>=0,r=(i,c)=>{if(!t(i))throw new Error(`"${c}" must be a non-negative integer. Received: "${i}".`)};function n(i,c){return r(i,"count"),i*c}e.inMilliseconds=n;function s(i){return r(i,"timestamp"),Date.now()-i}e.timeSince=s})(pc);var mc={};Object.defineProperty(mc,"__esModule",{value:!0});var vc={},ai={exports:{}};const jd="2.0.0",wc=256,Fd=Number.MAX_SAFE_INTEGER||9007199254740991,Hd=16,Ud=wc-6,Vd=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var bs={MAX_LENGTH:wc,MAX_SAFE_COMPONENT_LENGTH:Hd,MAX_SAFE_BUILD_LENGTH:Ud,MAX_SAFE_INTEGER:Fd,RELEASE_TYPES:Vd,SEMVER_SPEC_VERSION:jd,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},Gs={};const zd=typeof process=="object"&&Gs&&Gs.NODE_DEBUG&&/\bsemver\b/i.test(Gs.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};var _s=zd;(function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:s}=bs,i=_s;t=e.exports={};const c=t.re=[],u=t.safeRe=[],h=t.src=[],f=t.safeSrc=[],g=t.t={};let E=0;const b="[a-zA-Z0-9-]",k=[["\\s",1],["\\d",s],[b,n]],C=I=>{for(const[P,L]of k)I=I.split(`${P}*`).join(`${P}{0,${L}}`).split(`${P}+`).join(`${P}{1,${L}}`);return I},R=(I,P,L)=>{const M=C(P),j=E++;i(I,j,P),g[I]=j,h[j]=P,f[j]=M,c[j]=new RegExp(P,L?"g":void 0),u[j]=new RegExp(M,L?"g":void 0)};R("NUMERICIDENTIFIER","0|[1-9]\\d*"),R("NUMERICIDENTIFIERLOOSE","\\d+"),R("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${b}*`),R("MAINVERSION",`(${h[g.NUMERICIDENTIFIER]})\\.(${h[g.NUMERICIDENTIFIER]})\\.(${h[g.NUMERICIDENTIFIER]})`),R("MAINVERSIONLOOSE",`(${h[g.NUMERICIDENTIFIERLOOSE]})\\.(${h[g.NUMERICIDENTIFIERLOOSE]})\\.(${h[g.NUMERICIDENTIFIERLOOSE]})`),R("PRERELEASEIDENTIFIER",`(?:${h[g.NONNUMERICIDENTIFIER]}|${h[g.NUMERICIDENTIFIER]})`),R("PRERELEASEIDENTIFIERLOOSE",`(?:${h[g.NONNUMERICIDENTIFIER]}|${h[g.NUMERICIDENTIFIERLOOSE]})`),R("PRERELEASE",`(?:-(${h[g.PRERELEASEIDENTIFIER]}(?:\\.${h[g.PRERELEASEIDENTIFIER]})*))`),R("PRERELEASELOOSE",`(?:-?(${h[g.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${h[g.PRERELEASEIDENTIFIERLOOSE]})*))`),R("BUILDIDENTIFIER",`${b}+`),R("BUILD",`(?:\\+(${h[g.BUILDIDENTIFIER]}(?:\\.${h[g.BUILDIDENTIFIER]})*))`),R("FULLPLAIN",`v?${h[g.MAINVERSION]}${h[g.PRERELEASE]}?${h[g.BUILD]}?`),R("FULL",`^${h[g.FULLPLAIN]}$`),R("LOOSEPLAIN",`[v=\\s]*${h[g.MAINVERSIONLOOSE]}${h[g.PRERELEASELOOSE]}?${h[g.BUILD]}?`),R("LOOSE",`^${h[g.LOOSEPLAIN]}$`),R("GTLT","((?:<|>)?=?)"),R("XRANGEIDENTIFIERLOOSE",`${h[g.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),R("XRANGEIDENTIFIER",`${h[g.NUMERICIDENTIFIER]}|x|X|\\*`),R("XRANGEPLAIN",`[v=\\s]*(${h[g.XRANGEIDENTIFIER]})(?:\\.(${h[g.XRANGEIDENTIFIER]})(?:\\.(${h[g.XRANGEIDENTIFIER]})(?:${h[g.PRERELEASE]})?${h[g.BUILD]}?)?)?`),R("XRANGEPLAINLOOSE",`[v=\\s]*(${h[g.XRANGEIDENTIFIERLOOSE]})(?:\\.(${h[g.XRANGEIDENTIFIERLOOSE]})(?:\\.(${h[g.XRANGEIDENTIFIERLOOSE]})(?:${h[g.PRERELEASELOOSE]})?${h[g.BUILD]}?)?)?`),R("XRANGE",`^${h[g.GTLT]}\\s*${h[g.XRANGEPLAIN]}$`),R("XRANGELOOSE",`^${h[g.GTLT]}\\s*${h[g.XRANGEPLAINLOOSE]}$`),R("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),R("COERCE",`${h[g.COERCEPLAIN]}(?:$|[^\\d])`),R("COERCEFULL",h[g.COERCEPLAIN]+`(?:${h[g.PRERELEASE]})?(?:${h[g.BUILD]})?(?:$|[^\\d])`),R("COERCERTL",h[g.COERCE],!0),R("COERCERTLFULL",h[g.COERCEFULL],!0),R("LONETILDE","(?:~>?)"),R("TILDETRIM",`(\\s*)${h[g.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",R("TILDE",`^${h[g.LONETILDE]}${h[g.XRANGEPLAIN]}$`),R("TILDELOOSE",`^${h[g.LONETILDE]}${h[g.XRANGEPLAINLOOSE]}$`),R("LONECARET","(?:\\^)"),R("CARETTRIM",`(\\s*)${h[g.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",R("CARET",`^${h[g.LONECARET]}${h[g.XRANGEPLAIN]}$`),R("CARETLOOSE",`^${h[g.LONECARET]}${h[g.XRANGEPLAINLOOSE]}$`),R("COMPARATORLOOSE",`^${h[g.GTLT]}\\s*(${h[g.LOOSEPLAIN]})$|^$`),R("COMPARATOR",`^${h[g.GTLT]}\\s*(${h[g.FULLPLAIN]})$|^$`),R("COMPARATORTRIM",`(\\s*)${h[g.GTLT]}\\s*(${h[g.LOOSEPLAIN]}|${h[g.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",R("HYPHENRANGE",`^\\s*(${h[g.XRANGEPLAIN]})\\s+-\\s+(${h[g.XRANGEPLAIN]})\\s*$`),R("HYPHENRANGELOOSE",`^\\s*(${h[g.XRANGEPLAINLOOSE]})\\s+-\\s+(${h[g.XRANGEPLAINLOOSE]})\\s*$`),R("STAR","(<|>)?=?\\s*\\*"),R("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),R("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(ai,ai.exports);var bn=ai.exports;const Wd=Object.freeze({loose:!0}),qd=Object.freeze({}),Jd=e=>e?typeof e!="object"?Wd:e:qd;var Ni=Jd;const So=/^[0-9]+$/,yc=(e,t)=>{const r=So.test(e),n=So.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:eyc(t,e);var bc={compareIdentifiers:yc,rcompareIdentifiers:Gd};const Ln=_s,{MAX_LENGTH:ko,MAX_SAFE_INTEGER:xn}=bs,{safeRe:Tn,t:Pn}=bn,Zd=Ni,{compareIdentifiers:br}=bc;let Qd=class gt{constructor(t,r){if(r=Zd(r),t instanceof gt){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>ko)throw new TypeError(`version is longer than ${ko} characters`);Ln("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;const n=t.trim().match(r.loose?Tn[Pn.LOOSE]:Tn[Pn.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>xn||this.major<0)throw new TypeError("Invalid major version");if(this.minor>xn||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>xn||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){const i=+s;if(i>=0&&i=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let i=[r,s];n===!1&&(i=[r]),br(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var Qe=Qd;const Mo=Qe,Kd=(e,t,r=!1)=>{if(e instanceof Mo)return e;try{return new Mo(e,t)}catch(n){if(!r)return null;throw n}};var Hr=Kd;const Xd=Hr,Yd=(e,t)=>{const r=Xd(e,t);return r?r.version:null};var ef=Yd;const tf=Hr,rf=(e,t)=>{const r=tf(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};var nf=rf;const Ro=Qe,sf=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new Ro(e instanceof Ro?e.version:e,r).inc(t,n,s).version}catch{return null}};var of=sf;const Io=Hr,af=(e,t)=>{const r=Io(e,null,!0),n=Io(t,null,!0),s=r.compare(n);if(s===0)return null;const i=s>0,c=i?r:n,u=i?n:r,h=!!c.prerelease.length;if(!!u.prerelease.length&&!h){if(!u.patch&&!u.minor)return"major";if(u.compareMain(c)===0)return u.minor&&!u.patch?"minor":"patch"}const g=h?"pre":"";return r.major!==n.major?g+"major":r.minor!==n.minor?g+"minor":r.patch!==n.patch?g+"patch":"prerelease"};var cf=af;const lf=Qe,uf=(e,t)=>new lf(e,t).major;var hf=uf;const df=Qe,ff=(e,t)=>new df(e,t).minor;var gf=ff;const pf=Qe,mf=(e,t)=>new pf(e,t).patch;var vf=mf;const wf=Hr,yf=(e,t)=>{const r=wf(e,t);return r&&r.prerelease.length?r.prerelease:null};var bf=yf;const Co=Qe,_f=(e,t,r)=>new Co(e,r).compare(new Co(t,r));var ut=_f;const Ef=ut,Sf=(e,t,r)=>Ef(t,e,r);var kf=Sf;const Mf=ut,Rf=(e,t)=>Mf(e,t,!0);var If=Rf;const Ao=Qe,Cf=(e,t,r)=>{const n=new Ao(e,r),s=new Ao(t,r);return n.compare(s)||n.compareBuild(s)};var Li=Cf;const Af=Li,Nf=(e,t)=>e.sort((r,n)=>Af(r,n,t));var Lf=Nf;const xf=Li,Tf=(e,t)=>e.sort((r,n)=>xf(n,r,t));var Pf=Tf;const $f=ut,Of=(e,t,r)=>$f(e,t,r)>0;var Es=Of;const Bf=ut,Df=(e,t,r)=>Bf(e,t,r)<0;var xi=Df;const jf=ut,Ff=(e,t,r)=>jf(e,t,r)===0;var _c=Ff;const Hf=ut,Uf=(e,t,r)=>Hf(e,t,r)!==0;var Ec=Uf;const Vf=ut,zf=(e,t,r)=>Vf(e,t,r)>=0;var Ti=zf;const Wf=ut,qf=(e,t,r)=>Wf(e,t,r)<=0;var Pi=qf;const Jf=_c,Gf=Ec,Zf=Es,Qf=Ti,Kf=xi,Xf=Pi,Yf=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return Jf(e,r,n);case"!=":return Gf(e,r,n);case">":return Zf(e,r,n);case">=":return Qf(e,r,n);case"<":return Kf(e,r,n);case"<=":return Xf(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};var Sc=Yf;const e0=Qe,t0=Hr,{safeRe:$n,t:On}=bn,r0=(e,t)=>{if(e instanceof e0)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?$n[On.COERCEFULL]:$n[On.COERCE]);else{const h=t.includePrerelease?$n[On.COERCERTLFULL]:$n[On.COERCERTL];let f;for(;(f=h.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||f.index+f[0].length!==r.index+r[0].length)&&(r=f),h.lastIndex=f.index+f[1].length+f[2].length;h.lastIndex=-1}if(r===null)return null;const n=r[2],s=r[3]||"0",i=r[4]||"0",c=t.includePrerelease&&r[5]?`-${r[5]}`:"",u=t.includePrerelease&&r[6]?`+${r[6]}`:"";return t0(`${n}.${s}.${i}${c}${u}`,t)};var n0=r0;class s0{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}}var i0=s0,Zs,No;function ht(){if(No)return Zs;No=1;const e=/\s+/g;class t{constructor(l,d){if(d=s(d),l instanceof t)return l.loose===!!d.loose&&l.includePrerelease===!!d.includePrerelease?l:new t(l.raw,d);if(l instanceof i)return this.raw=l.value,this.set=[[l]],this.formatted=void 0,this;if(this.options=d,this.loose=!!d.loose,this.includePrerelease=!!d.includePrerelease,this.raw=l.trim().replace(e," "),this.set=this.raw.split("||").map(p=>this.parseRange(p.trim())).filter(p=>p.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const p=this.set[0];if(this.set=this.set.filter(v=>!R(v[0])),this.set.length===0)this.set=[p];else if(this.set.length>1){for(const v of this.set)if(v.length===1&&I(v[0])){this.set=[v];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let l=0;l0&&(this.formatted+="||");const d=this.set[l];for(let p=0;p0&&(this.formatted+=" "),this.formatted+=d[p].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(l){const p=((this.options.includePrerelease&&k)|(this.options.loose&&C))+":"+l,v=n.get(p);if(v)return v;const y=this.options.loose,S=y?h[f.HYPHENRANGELOOSE]:h[f.HYPHENRANGE];l=l.replace(S,q(this.options.includePrerelease)),c("hyphen replace",l),l=l.replace(h[f.COMPARATORTRIM],g),c("comparator trim",l),l=l.replace(h[f.TILDETRIM],E),c("tilde trim",l),l=l.replace(h[f.CARETTRIM],b),c("caret trim",l);let m=l.split(" ").map(N=>L(N,this.options)).join(" ").split(/\s+/).map(N=>U(N,this.options));y&&(m=m.filter(N=>(c("loose invalid filter",N,this.options),!!N.match(h[f.COMPARATORLOOSE])))),c("range list",m);const a=new Map,w=m.map(N=>new i(N,this.options));for(const N of w){if(R(N))return[N];a.set(N.value,N)}a.size>1&&a.has("")&&a.delete("");const x=[...a.values()];return n.set(p,x),x}intersects(l,d){if(!(l instanceof t))throw new TypeError("a Range is required");return this.set.some(p=>P(p,d)&&l.set.some(v=>P(v,d)&&p.every(y=>v.every(S=>y.intersects(S,d)))))}test(l){if(!l)return!1;if(typeof l=="string")try{l=new u(l,this.options)}catch{return!1}for(let d=0;do.value==="<0.0.0-0",I=o=>o.value==="",P=(o,l)=>{let d=!0;const p=o.slice();let v=p.pop();for(;d&&p.length;)d=p.every(y=>v.intersects(y,l)),v=p.pop();return d},L=(o,l)=>(c("comp",o,l),o=$(o,l),c("caret",o),o=j(o,l),c("tildes",o),o=De(o,l),c("xrange",o),o=Q(o,l),c("stars",o),o),M=o=>!o||o.toLowerCase()==="x"||o==="*",j=(o,l)=>o.trim().split(/\s+/).map(d=>A(d,l)).join(" "),A=(o,l)=>{const d=l.loose?h[f.TILDELOOSE]:h[f.TILDE];return o.replace(d,(p,v,y,S,m)=>{c("tilde",o,p,v,y,S,m);let a;return M(v)?a="":M(y)?a=`>=${v}.0.0 <${+v+1}.0.0-0`:M(S)?a=`>=${v}.${y}.0 <${v}.${+y+1}.0-0`:m?(c("replaceTilde pr",m),a=`>=${v}.${y}.${S}-${m} <${v}.${+y+1}.0-0`):a=`>=${v}.${y}.${S} <${v}.${+y+1}.0-0`,c("tilde return",a),a})},$=(o,l)=>o.trim().split(/\s+/).map(d=>J(d,l)).join(" "),J=(o,l)=>{c("caret",o,l);const d=l.loose?h[f.CARETLOOSE]:h[f.CARET],p=l.includePrerelease?"-0":"";return o.replace(d,(v,y,S,m,a)=>{c("caret",o,v,y,S,m,a);let w;return M(y)?w="":M(S)?w=`>=${y}.0.0${p} <${+y+1}.0.0-0`:M(m)?y==="0"?w=`>=${y}.${S}.0${p} <${y}.${+S+1}.0-0`:w=`>=${y}.${S}.0${p} <${+y+1}.0.0-0`:a?(c("replaceCaret pr",a),y==="0"?S==="0"?w=`>=${y}.${S}.${m}-${a} <${y}.${S}.${+m+1}-0`:w=`>=${y}.${S}.${m}-${a} <${y}.${+S+1}.0-0`:w=`>=${y}.${S}.${m}-${a} <${+y+1}.0.0-0`):(c("no pr"),y==="0"?S==="0"?w=`>=${y}.${S}.${m}${p} <${y}.${S}.${+m+1}-0`:w=`>=${y}.${S}.${m}${p} <${y}.${+S+1}.0-0`:w=`>=${y}.${S}.${m} <${+y+1}.0.0-0`),c("caret return",w),w})},De=(o,l)=>(c("replaceXRanges",o,l),o.split(/\s+/).map(d=>Ve(d,l)).join(" ")),Ve=(o,l)=>{o=o.trim();const d=l.loose?h[f.XRANGELOOSE]:h[f.XRANGE];return o.replace(d,(p,v,y,S,m,a)=>{c("xRange",o,p,v,y,S,m,a);const w=M(y),x=w||M(S),N=x||M(m),O=N;return v==="="&&O&&(v=""),a=l.includePrerelease?"-0":"",w?v===">"||v==="<"?p="<0.0.0-0":p="*":v&&O?(x&&(S=0),m=0,v===">"?(v=">=",x?(y=+y+1,S=0,m=0):(S=+S+1,m=0)):v==="<="&&(v="<",x?y=+y+1:S=+S+1),v==="<"&&(a="-0"),p=`${v+y}.${S}.${m}${a}`):x?p=`>=${y}.0.0${a} <${+y+1}.0.0-0`:N&&(p=`>=${y}.${S}.0${a} <${y}.${+S+1}.0-0`),c("xRange return",p),p})},Q=(o,l)=>(c("replaceStars",o,l),o.trim().replace(h[f.STAR],"")),U=(o,l)=>(c("replaceGTE0",o,l),o.trim().replace(h[l.includePrerelease?f.GTE0PRE:f.GTE0],"")),q=o=>(l,d,p,v,y,S,m,a,w,x,N,O)=>(M(p)?d="":M(v)?d=`>=${p}.0.0${o?"-0":""}`:M(y)?d=`>=${p}.${v}.0${o?"-0":""}`:S?d=`>=${d}`:d=`>=${d}${o?"-0":""}`,M(w)?a="":M(x)?a=`<${+w+1}.0.0-0`:M(N)?a=`<${w}.${+x+1}.0-0`:O?a=`<=${w}.${x}.${N}-${O}`:o?a=`<${w}.${x}.${+N+1}-0`:a=`<=${a}`,`${d} ${a}`.trim()),_=(o,l,d)=>{for(let p=0;p0){const v=o[p].semver;if(v.major===l.major&&v.minor===l.minor&&v.patch===l.patch)return!0}return!1}return!0};return Zs}var Qs,Lo;function Ss(){if(Lo)return Qs;Lo=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(g,E){if(E=r(E),g instanceof t){if(g.loose===!!E.loose)return g;g=g.value}g=g.trim().split(/\s+/).join(" "),c("comparator",g,E),this.options=E,this.loose=!!E.loose,this.parse(g),this.semver===e?this.value="":this.value=this.operator+this.semver.version,c("comp",this)}parse(g){const E=this.options.loose?n[s.COMPARATORLOOSE]:n[s.COMPARATOR],b=g.match(E);if(!b)throw new TypeError(`Invalid comparator: ${g}`);this.operator=b[1]!==void 0?b[1]:"",this.operator==="="&&(this.operator=""),b[2]?this.semver=new u(b[2],this.options.loose):this.semver=e}toString(){return this.value}test(g){if(c("Comparator.test",g,this.options.loose),this.semver===e||g===e)return!0;if(typeof g=="string")try{g=new u(g,this.options)}catch{return!1}return i(g,this.operator,this.semver,this.options)}intersects(g,E){if(!(g instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new h(g.value,E).test(this.value):g.operator===""?g.value===""?!0:new h(this.value,E).test(g.semver):(E=r(E),E.includePrerelease&&(this.value==="<0.0.0-0"||g.value==="<0.0.0-0")||!E.includePrerelease&&(this.value.startsWith("<0.0.0")||g.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&g.operator.startsWith(">")||this.operator.startsWith("<")&&g.operator.startsWith("<")||this.semver.version===g.semver.version&&this.operator.includes("=")&&g.operator.includes("=")||i(this.semver,"<",g.semver,E)&&this.operator.startsWith(">")&&g.operator.startsWith("<")||i(this.semver,">",g.semver,E)&&this.operator.startsWith("<")&&g.operator.startsWith(">")))}}Qs=t;const r=Ni,{safeRe:n,t:s}=bn,i=Sc,c=_s,u=Qe,h=ht();return Qs}const o0=ht(),a0=(e,t,r)=>{try{t=new o0(t,r)}catch{return!1}return t.test(e)};var ks=a0;const c0=ht(),l0=(e,t)=>new c0(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));var u0=l0;const h0=Qe,d0=ht(),f0=(e,t,r)=>{let n=null,s=null,i=null;try{i=new d0(t,r)}catch{return null}return e.forEach(c=>{i.test(c)&&(!n||s.compare(c)===-1)&&(n=c,s=new h0(n,r))}),n};var g0=f0;const p0=Qe,m0=ht(),v0=(e,t,r)=>{let n=null,s=null,i=null;try{i=new m0(t,r)}catch{return null}return e.forEach(c=>{i.test(c)&&(!n||s.compare(c)===1)&&(n=c,s=new p0(n,r))}),n};var w0=v0;const Ks=Qe,y0=ht(),xo=Es,b0=(e,t)=>{e=new y0(e,t);let r=new Ks("0.0.0");if(e.test(r)||(r=new Ks("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n{const u=new Ks(c.semver.version);switch(c.operator){case">":u.prerelease.length===0?u.patch++:u.prerelease.push(0),u.raw=u.format();case"":case">=":(!i||xo(u,i))&&(i=u);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${c.operator}`)}}),i&&(!r||xo(r,i))&&(r=i)}return r&&e.test(r)?r:null};var _0=b0;const E0=ht(),S0=(e,t)=>{try{return new E0(e,t).range||"*"}catch{return null}};var k0=S0;const M0=Qe,kc=Ss(),{ANY:R0}=kc,I0=ht(),C0=ks,To=Es,Po=xi,A0=Pi,N0=Ti,L0=(e,t,r,n)=>{e=new M0(e,n),t=new I0(t,n);let s,i,c,u,h;switch(r){case">":s=To,i=A0,c=Po,u=">",h=">=";break;case"<":s=Po,i=N0,c=To,u="<",h="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(C0(e,t,n))return!1;for(let f=0;f{k.semver===R0&&(k=new kc(">=0.0.0")),E=E||k,b=b||k,s(k.semver,E.semver,n)?E=k:c(k.semver,b.semver,n)&&(b=k)}),E.operator===u||E.operator===h||(!b.operator||b.operator===u)&&i(e,b.semver))return!1;if(b.operator===h&&c(e,b.semver))return!1}return!0};var $i=L0;const x0=$i,T0=(e,t,r)=>x0(e,t,">",r);var P0=T0;const $0=$i,O0=(e,t,r)=>$0(e,t,"<",r);var B0=O0;const $o=ht(),D0=(e,t,r)=>(e=new $o(e,r),t=new $o(t,r),e.intersects(t,r));var j0=D0;const F0=ks,H0=ut;var U0=(e,t,r)=>{const n=[];let s=null,i=null;const c=e.sort((g,E)=>H0(g,E,r));for(const g of c)F0(g,t,r)?(i=g,s||(s=g)):(i&&n.push([s,i]),i=null,s=null);s&&n.push([s,null]);const u=[];for(const[g,E]of n)g===E?u.push(g):!E&&g===c[0]?u.push("*"):E?g===c[0]?u.push(`<=${E}`):u.push(`${g} - ${E}`):u.push(`>=${g}`);const h=u.join(" || "),f=typeof t.raw=="string"?t.raw:String(t);return h.length{if(e===t)return!0;e=new Oo(e,r),t=new Oo(t,r);let n=!1;e:for(const s of e.set){for(const i of t.set){const c=W0(s,i,r);if(n=n||c!==null,c)continue e}if(n)return!1}return!0},z0=[new Oi(">=0.0.0-0")],Bo=[new Oi(">=0.0.0")],W0=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Xs){if(t.length===1&&t[0].semver===Xs)return!0;r.includePrerelease?e=z0:e=Bo}if(t.length===1&&t[0].semver===Xs){if(r.includePrerelease)return!0;t=Bo}const n=new Set;let s,i;for(const k of e)k.operator===">"||k.operator===">="?s=Do(s,k,r):k.operator==="<"||k.operator==="<="?i=jo(i,k,r):n.add(k.semver);if(n.size>1)return null;let c;if(s&&i){if(c=Bi(s.semver,i.semver,r),c>0)return null;if(c===0&&(s.operator!==">="||i.operator!=="<="))return null}for(const k of n){if(s&&!Zr(k,String(s),r)||i&&!Zr(k,String(i),r))return null;for(const C of t)if(!Zr(k,String(C),r))return!1;return!0}let u,h,f,g,E=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1,b=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;E&&E.prerelease.length===1&&i.operator==="<"&&E.prerelease[0]===0&&(E=!1);for(const k of t){if(g=g||k.operator===">"||k.operator===">=",f=f||k.operator==="<"||k.operator==="<=",s){if(b&&k.semver.prerelease&&k.semver.prerelease.length&&k.semver.major===b.major&&k.semver.minor===b.minor&&k.semver.patch===b.patch&&(b=!1),k.operator===">"||k.operator===">="){if(u=Do(s,k,r),u===k&&u!==s)return!1}else if(s.operator===">="&&!Zr(s.semver,String(k),r))return!1}if(i){if(E&&k.semver.prerelease&&k.semver.prerelease.length&&k.semver.major===E.major&&k.semver.minor===E.minor&&k.semver.patch===E.patch&&(E=!1),k.operator==="<"||k.operator==="<="){if(h=jo(i,k,r),h===k&&h!==i)return!1}else if(i.operator==="<="&&!Zr(i.semver,String(k),r))return!1}if(!k.operator&&(i||s)&&c!==0)return!1}return!(s&&f&&!i&&c!==0||i&&g&&!s&&c!==0||b||E)},Do=(e,t,r)=>{if(!e)return t;const n=Bi(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},jo=(e,t,r)=>{if(!e)return t;const n=Bi(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};var q0=V0;const Ys=bn,Fo=bs,J0=Qe,Ho=bc,G0=Hr,Z0=ef,Q0=nf,K0=of,X0=cf,Y0=hf,e1=gf,t1=vf,r1=bf,n1=ut,s1=kf,i1=If,o1=Li,a1=Lf,c1=Pf,l1=Es,u1=xi,h1=_c,d1=Ec,f1=Ti,g1=Pi,p1=Sc,m1=n0,v1=Ss(),w1=ht(),y1=ks,b1=u0,_1=g0,E1=w0,S1=_0,k1=k0,M1=$i,R1=P0,I1=B0,C1=j0,A1=U0,N1=q0;var L1={parse:G0,valid:Z0,clean:Q0,inc:K0,diff:X0,major:Y0,minor:e1,patch:t1,prerelease:r1,compare:n1,rcompare:s1,compareLoose:i1,compareBuild:o1,sort:a1,rsort:c1,gt:l1,lt:u1,eq:h1,neq:d1,gte:f1,lte:g1,cmp:p1,coerce:m1,Comparator:v1,Range:w1,satisfies:y1,toComparators:b1,maxSatisfying:_1,minSatisfying:E1,minVersion:S1,validRange:k1,outside:M1,gtr:R1,ltr:I1,intersects:C1,simplifyRange:A1,subset:N1,SemVer:J0,re:Ys.re,src:Ys.src,tokens:Ys.t,SEMVER_SPEC_VERSION:Fo.SEMVER_SPEC_VERSION,RELEASE_TYPES:Fo.RELEASE_TYPES,compareIdentifiers:Ho.compareIdentifiers,rcompareIdentifiers:Ho.rcompareIdentifiers};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.satisfiesVersionRange=e.gtRange=e.gtVersion=e.assertIsSemVerRange=e.assertIsSemVerVersion=e.isValidSemVerRange=e.isValidSemVerVersion=e.VersionRangeStruct=e.VersionStruct=void 0;const t=L1,r=nr,n=qe;e.VersionStruct=(0,r.refine)((0,r.string)(),"Version",E=>(0,t.valid)(E)===null?`Expected SemVer version, got "${E}"`:!0),e.VersionRangeStruct=(0,r.refine)((0,r.string)(),"Version range",E=>(0,t.validRange)(E)===null?`Expected SemVer range, got "${E}"`:!0);function s(E){return(0,r.is)(E,e.VersionStruct)}e.isValidSemVerVersion=s;function i(E){return(0,r.is)(E,e.VersionRangeStruct)}e.isValidSemVerRange=i;function c(E){(0,n.assertStruct)(E,e.VersionStruct)}e.assertIsSemVerVersion=c;function u(E){(0,n.assertStruct)(E,e.VersionRangeStruct)}e.assertIsSemVerRange=u;function h(E,b){return(0,t.gt)(E,b)}e.gtVersion=h;function f(E,b){return(0,t.gtr)(E,b)}e.gtRange=f;function g(E,b){return(0,t.satisfies)(E,b,{includePrerelease:!0})}e.satisfiesVersionRange=g})(vc);(function(e){var t=B&&B.__createBinding||(Object.create?function(n,s,i,c){c===void 0&&(c=i);var u=Object.getOwnPropertyDescriptor(s,i);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[i]}}),Object.defineProperty(n,c,u)}:function(n,s,i,c){c===void 0&&(c=i),n[c]=s[i]}),r=B&&B.__exportStar||function(n,s){for(var i in n)i!=="default"&&!Object.prototype.hasOwnProperty.call(s,i)&&t(s,n,i)};Object.defineProperty(e,"__esModule",{value:!0}),r(qe,e),r(wn,e),r(W,e),r(ws,e),r(yt,e),r(xr,e),r(uc,e),r(yn,e),r(hc,e),r(dc,e),r(Tr,e),r(fc,e),r(bt,e),r(gc,e),r(pc,e),r(mc,e),r(vc,e)})(Wa);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createModuleLogger=e.projectLogger=void 0;const t=Wa;Object.defineProperty(e,"createModuleLogger",{enumerable:!0,get:function(){return t.createModuleLogger}}),e.projectLogger=(0,t.createProjectLogger)("eth-block-tracker")})(za);var Mc=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ms,"__esModule",{value:!0});ms.PollingBlockTracker=void 0;const x1=Mc(_i),T1=Mc(ah),P1=gn,Uo=za,Vo=(0,Uo.createModuleLogger)(Uo.projectLogger,"polling-block-tracker"),$1=(0,x1.default)(),O1=1e3;class B1 extends P1.BaseBlockTracker{constructor(t={}){var r;if(!t.provider)throw new Error("PollingBlockTracker - no provider specified.");super(Object.assign(Object.assign({},t),{blockResetDuration:(r=t.blockResetDuration)!==null&&r!==void 0?r:t.pollingInterval})),this._provider=t.provider,this._pollingInterval=t.pollingInterval||20*O1,this._retryTimeout=t.retryTimeout||this._pollingInterval/10,this._keepEventLoopActive=t.keepEventLoopActive===void 0?!0:t.keepEventLoopActive,this._setSkipCacheFlag=t.setSkipCacheFlag||!1}async checkForLatestBlock(){return await this._updateLatestBlock(),await this.getLatestBlock()}async _start(){this._synchronize()}async _end(){}async _synchronize(){for(var t;this._isRunning;)try{await this._updateLatestBlock();const r=zo(this._pollingInterval,!this._keepEventLoopActive);this.emit("_waitingForNextIteration"),await r}catch(r){const n=new Error(`PollingBlockTracker - encountered an error while attempting to update latest block: +${(t=r.stack)!==null&&t!==void 0?t:r}`);try{this.emit("error",n)}catch{console.error(n)}const s=zo(this._retryTimeout,!this._keepEventLoopActive);this.emit("_waitingForNextIteration"),await s}}async _updateLatestBlock(){const t=await this._fetchLatestBlock();this._newPotentialLatest(t)}async _fetchLatestBlock(){const t={jsonrpc:"2.0",id:$1(),method:"eth_blockNumber",params:[]};this._setSkipCacheFlag&&(t.skipCache=!0),Vo("Making request",t);const r=await(0,T1.default)(n=>this._provider.sendAsync(t,n))();if(Vo("Got response",r),r.error)throw new Error(`PollingBlockTracker - encountered error fetching block: +${r.error.message}`);return r.result}}ms.PollingBlockTracker=B1;function zo(e,t){return new Promise(r=>{const n=setTimeout(r,e);n.unref&&t&&n.unref()})}var Ms={},D1=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ms,"__esModule",{value:!0});Ms.SubscribeBlockTracker=void 0;const j1=D1(_i),F1=gn,H1=(0,j1.default)();class U1 extends F1.BaseBlockTracker{constructor(t={}){if(!t.provider)throw new Error("SubscribeBlockTracker - no provider specified.");super(t),this._provider=t.provider,this._subscriptionId=null}async checkForLatestBlock(){return await this.getLatestBlock()}async _start(){if(this._subscriptionId===void 0||this._subscriptionId===null)try{const t=await this._call("eth_blockNumber");this._subscriptionId=await this._call("eth_subscribe","newHeads"),this._provider.on("data",this._handleSubData.bind(this)),this._newPotentialLatest(t)}catch(t){this.emit("error",t)}}async _end(){if(this._subscriptionId!==null&&this._subscriptionId!==void 0)try{await this._call("eth_unsubscribe",this._subscriptionId),this._subscriptionId=null}catch(t){this.emit("error",t)}}_call(t,...r){return new Promise((n,s)=>{this._provider.sendAsync({id:H1(),method:t,params:r,jsonrpc:"2.0"},(i,c)=>{i?s(i):n(c.result)})})}_handleSubData(t,r){var n;r.method==="eth_subscription"&&((n=r.params)===null||n===void 0?void 0:n.subscription)===this._subscriptionId&&this._newPotentialLatest(r.params.result.number)}}Ms.SubscribeBlockTracker=U1;(function(e){var t=B&&B.__createBinding||(Object.create?function(n,s,i,c){c===void 0&&(c=i),Object.defineProperty(n,c,{enumerable:!0,get:function(){return s[i]}})}:function(n,s,i,c){c===void 0&&(c=i),n[c]=s[i]}),r=B&&B.__exportStar||function(n,s){for(var i in n)i!=="default"&&!Object.prototype.hasOwnProperty.call(s,i)&&t(s,n,i)};Object.defineProperty(e,"__esModule",{value:!0}),r(ms,e),r(Ms,e)})(Va);var Di={},Rs={},_n={};Object.defineProperty(_n,"__esModule",{value:!0});_n.getUniqueId=void 0;const Rc=4294967295;let ei=Math.floor(Math.random()*Rc);function V1(){return ei=(ei+1)%Rc,ei}_n.getUniqueId=V1;Object.defineProperty(Rs,"__esModule",{value:!0});Rs.createIdRemapMiddleware=void 0;const z1=_n;function W1(){return(e,t,r,n)=>{const s=e.id,i=z1.getUniqueId();e.id=i,t.id=i,r(c=>{e.id=s,t.id=s,c()})}}Rs.createIdRemapMiddleware=W1;var Is={};Object.defineProperty(Is,"__esModule",{value:!0});Is.createAsyncMiddleware=void 0;function q1(e){return async(t,r,n,s)=>{let i;const c=new Promise(g=>{i=g});let u=null,h=!1;const f=async()=>{h=!0,n(g=>{u=g,i()}),await c};try{await e(t,r,f),h?(await c,u(null)):s(null)}catch(g){u?u(g):s(g)}}}Is.createAsyncMiddleware=q1;var Cs={};Object.defineProperty(Cs,"__esModule",{value:!0});Cs.createScaffoldMiddleware=void 0;function J1(e){return(t,r,n,s)=>{const i=e[t.method];return i===void 0?n():typeof i=="function"?i(t,r,n,s):(r.result=i,s())}}Cs.createScaffoldMiddleware=J1;var En={},ji={};Object.defineProperty(ji,"__esModule",{value:!0});const G1=sa;function Wo(e,t,r){try{Reflect.apply(e,t,r)}catch(n){setTimeout(()=>{throw n})}}function Z1(e){const t=e.length,r=new Array(t);for(let n=0;n0&&([c]=r),c instanceof Error)throw c;const u=new Error(`Unhandled error.${c?` (${c.message})`:""}`);throw u.context=c,u}const i=s[t];if(i===void 0)return!1;if(typeof i=="function")Wo(i,this,r);else{const c=i.length,u=Z1(i);for(let h=0;h"u"&&(n=Ac()),ci(e,"",0,[],void 0,0,n);var s;try{Kt.length===0?s=JSON.stringify(e,t,r):s=JSON.stringify(e,Lc(t),r)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;er.length!==0;){var i=er.pop();i.length===4?Object.defineProperty(i[0],i[1],i[3]):i[0][i[1]]=i[2]}}return s}function Ir(e,t,r,n){var s=Object.getOwnPropertyDescriptor(n,r);s.get!==void 0?s.configurable?(Object.defineProperty(n,r,{value:e}),er.push([n,r,t,s])):Kt.push([t,r,e]):(n[r]=e,er.push([n,r,t]))}function ci(e,t,r,n,s,i,c){i+=1;var u;if(typeof e=="object"&&e!==null){for(u=0;uc.depthLimit){Ir(Un,e,t,s);return}if(typeof c.edgesLimit<"u"&&r+1>c.edgesLimit){Ir(Un,e,t,s);return}if(n.push(e),Array.isArray(e))for(u=0;ut?1:0}function Nc(e,t,r,n){typeof n>"u"&&(n=Ac());var s=li(e,"",0,[],void 0,0,n)||e,i;try{Kt.length===0?i=JSON.stringify(s,t,r):i=JSON.stringify(s,Lc(t),r)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;er.length!==0;){var c=er.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return i}function li(e,t,r,n,s,i,c){i+=1;var u;if(typeof e=="object"&&e!==null){for(u=0;uc.depthLimit){Ir(Un,e,t,s);return}if(typeof c.edgesLimit<"u"&&r+1>c.edgesLimit){Ir(Un,e,t,s);return}if(n.push(e),Array.isArray(e))for(u=0;u0)for(var n=0;n=1e3&&e<=4999}function rg(e,t){if(t!=="[Circular]")return t}var Fi={},At={};Object.defineProperty(At,"__esModule",{value:!0});At.errorValues=At.errorCodes=void 0;At.errorCodes={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901}};At.errorValues={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."}};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.serializeError=e.isValidCode=e.getMessageFromCode=e.JSON_RPC_SERVER_ERROR_MESSAGE=void 0;const t=At,r=Ct,n=t.errorCodes.rpc.internal,s="Unspecified error message. This is a bug, please report it.",i={code:n,message:c(n)};e.JSON_RPC_SERVER_ERROR_MESSAGE="Unspecified server error.";function c(b,k=s){if(Number.isInteger(b)){const C=b.toString();if(E(t.errorValues,C))return t.errorValues[C].message;if(f(b))return e.JSON_RPC_SERVER_ERROR_MESSAGE}return k}e.getMessageFromCode=c;function u(b){if(!Number.isInteger(b))return!1;const k=b.toString();return!!(t.errorValues[k]||f(b))}e.isValidCode=u;function h(b,{fallbackError:k=i,shouldIncludeStack:C=!1}={}){var R,I;if(!k||!Number.isInteger(k.code)||typeof k.message!="string")throw new Error("Must provide fallback error with integer number code and string message.");if(b instanceof r.EthereumRpcError)return b.serialize();const P={};if(b&&typeof b=="object"&&!Array.isArray(b)&&E(b,"code")&&u(b.code)){const M=b;P.code=M.code,M.message&&typeof M.message=="string"?(P.message=M.message,E(M,"data")&&(P.data=M.data)):(P.message=c(P.code),P.data={originalError:g(b)})}else{P.code=k.code;const M=(R=b)===null||R===void 0?void 0:R.message;P.message=M&&typeof M=="string"?M:k.message,P.data={originalError:g(b)}}const L=(I=b)===null||I===void 0?void 0:I.stack;return C&&b&&L&&typeof L=="string"&&(P.stack=L),P}e.serializeError=h;function f(b){return b>=-32099&&b<=-32e3}function g(b){return b&&typeof b=="object"&&!Array.isArray(b)?Object.assign({},b):b}function E(b,k){return Object.prototype.hasOwnProperty.call(b,k)}})(Fi);var As={};Object.defineProperty(As,"__esModule",{value:!0});As.ethErrors=void 0;const Hi=Ct,Tc=Fi,Je=At;As.ethErrors={rpc:{parse:e=>nt(Je.errorCodes.rpc.parse,e),invalidRequest:e=>nt(Je.errorCodes.rpc.invalidRequest,e),invalidParams:e=>nt(Je.errorCodes.rpc.invalidParams,e),methodNotFound:e=>nt(Je.errorCodes.rpc.methodNotFound,e),internal:e=>nt(Je.errorCodes.rpc.internal,e),server:e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:t}=e;if(!Number.isInteger(t)||t>-32005||t<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return nt(t,e)},invalidInput:e=>nt(Je.errorCodes.rpc.invalidInput,e),resourceNotFound:e=>nt(Je.errorCodes.rpc.resourceNotFound,e),resourceUnavailable:e=>nt(Je.errorCodes.rpc.resourceUnavailable,e),transactionRejected:e=>nt(Je.errorCodes.rpc.transactionRejected,e),methodNotSupported:e=>nt(Je.errorCodes.rpc.methodNotSupported,e),limitExceeded:e=>nt(Je.errorCodes.rpc.limitExceeded,e)},provider:{userRejectedRequest:e=>Qr(Je.errorCodes.provider.userRejectedRequest,e),unauthorized:e=>Qr(Je.errorCodes.provider.unauthorized,e),unsupportedMethod:e=>Qr(Je.errorCodes.provider.unsupportedMethod,e),disconnected:e=>Qr(Je.errorCodes.provider.disconnected,e),chainDisconnected:e=>Qr(Je.errorCodes.provider.chainDisconnected,e),custom:e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:t,message:r,data:n}=e;if(!r||typeof r!="string")throw new Error('"message" must be a nonempty string');return new Hi.EthereumProviderError(t,r,n)}}};function nt(e,t){const[r,n]=Pc(t);return new Hi.EthereumRpcError(e,r||Tc.getMessageFromCode(e),n)}function Qr(e,t){const[r,n]=Pc(t);return new Hi.EthereumProviderError(e,r||Tc.getMessageFromCode(e),n)}function Pc(e){if(e){if(typeof e=="string")return[e];if(typeof e=="object"&&!Array.isArray(e)){const{message:t,data:r}=e;if(t&&typeof t!="string")throw new Error("Must specify string message.");return[t||void 0,r]}}return[]}(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getMessageFromCode=e.serializeError=e.EthereumProviderError=e.EthereumRpcError=e.ethErrors=e.errorCodes=void 0;const t=Ct;Object.defineProperty(e,"EthereumRpcError",{enumerable:!0,get:function(){return t.EthereumRpcError}}),Object.defineProperty(e,"EthereumProviderError",{enumerable:!0,get:function(){return t.EthereumProviderError}});const r=Fi;Object.defineProperty(e,"serializeError",{enumerable:!0,get:function(){return r.serializeError}}),Object.defineProperty(e,"getMessageFromCode",{enumerable:!0,get:function(){return r.getMessageFromCode}});const n=As;Object.defineProperty(e,"ethErrors",{enumerable:!0,get:function(){return n.ethErrors}});const s=At;Object.defineProperty(e,"errorCodes",{enumerable:!0,get:function(){return s.errorCodes}})})(Ic);var ng=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(En,"__esModule",{value:!0});En.JsonRpcEngine=void 0;const sg=ng(ji),st=Ic;class _t extends sg.default{constructor(){super(),this._middleware=[]}push(t){this._middleware.push(t)}handle(t,r){if(r&&typeof r!="function")throw new Error('"callback" must be a function if provided.');return Array.isArray(t)?r?this._handleBatch(t,r):this._handleBatch(t):r?this._handle(t,r):this._promiseHandle(t)}asMiddleware(){return async(t,r,n,s)=>{try{const[i,c,u]=await _t._runAllMiddleware(t,r,this._middleware);return c?(await _t._runReturnHandlers(u),s(i)):n(async h=>{try{await _t._runReturnHandlers(u)}catch(f){return h(f)}return h()})}catch(i){return s(i)}}}async _handleBatch(t,r){try{const n=await Promise.all(t.map(this._promiseHandle.bind(this)));return r?r(null,n):n}catch(n){if(r)return r(n);throw n}}_promiseHandle(t){return new Promise(r=>{this._handle(t,(n,s)=>{r(s)})})}async _handle(t,r){if(!t||Array.isArray(t)||typeof t!="object"){const c=new st.EthereumRpcError(st.errorCodes.rpc.invalidRequest,`Requests must be plain objects. Received: ${typeof t}`,{request:t});return r(c,{id:void 0,jsonrpc:"2.0",error:c})}if(typeof t.method!="string"){const c=new st.EthereumRpcError(st.errorCodes.rpc.invalidRequest,`Must specify a string method. Received: ${typeof t.method}`,{request:t});return r(c,{id:t.id,jsonrpc:"2.0",error:c})}const n=Object.assign({},t),s={id:n.id,jsonrpc:n.jsonrpc};let i=null;try{await this._processRequest(n,s)}catch(c){i=c}return i&&(delete s.result,s.error||(s.error=st.serializeError(i))),r(i,s)}async _processRequest(t,r){const[n,s,i]=await _t._runAllMiddleware(t,r,this._middleware);if(_t._checkForCompletion(t,r,s),await _t._runReturnHandlers(i),n)throw n}static async _runAllMiddleware(t,r,n){const s=[];let i=null,c=!1;for(const u of n)if([i,c]=await _t._runMiddleware(t,r,u,s),c)break;return[i,c,s.reverse()]}static _runMiddleware(t,r,n,s){return new Promise(i=>{const c=h=>{const f=h||r.error;f&&(r.error=st.serializeError(f)),i([f,!0])},u=h=>{r.error?c(r.error):(h&&(typeof h!="function"&&c(new st.EthereumRpcError(st.errorCodes.rpc.internal,`JsonRpcEngine: "next" return handlers must be functions. Received "${typeof h}" for request: +${ti(t)}`,{request:t})),s.push(h)),i([null,!1]))};try{n(t,r,u,c)}catch(h){c(h)}})}static async _runReturnHandlers(t){for(const r of t)await new Promise((n,s)=>{r(i=>i?s(i):n())})}static _checkForCompletion(t,r,n){if(!("result"in r)&&!("error"in r))throw new st.EthereumRpcError(st.errorCodes.rpc.internal,`JsonRpcEngine: Response has no error or result for request: +${ti(t)}`,{request:t});if(!n)throw new st.EthereumRpcError(st.errorCodes.rpc.internal,`JsonRpcEngine: Nothing ended request: +${ti(t)}`,{request:t})}}En.JsonRpcEngine=_t;function ti(e){return JSON.stringify(e,null,2)}var Ns={};Object.defineProperty(Ns,"__esModule",{value:!0});Ns.mergeMiddleware=void 0;const ig=En;function og(e){const t=new ig.JsonRpcEngine;return e.forEach(r=>t.push(r)),t.asMiddleware()}Ns.mergeMiddleware=og;(function(e){var t=B&&B.__createBinding||(Object.create?function(n,s,i,c){c===void 0&&(c=i),Object.defineProperty(n,c,{enumerable:!0,get:function(){return s[i]}})}:function(n,s,i,c){c===void 0&&(c=i),n[c]=s[i]}),r=B&&B.__exportStar||function(n,s){for(var i in n)i!=="default"&&!Object.prototype.hasOwnProperty.call(s,i)&&t(s,n,i)};Object.defineProperty(e,"__esModule",{value:!0}),r(Rs,e),r(Is,e),r(Cs,e),r(_n,e),r(En,e),r(Ns,e)})(Di);var $c={},Ui={};const Vi=rn(Uc);var Ls={};Object.defineProperty(Ls,"__esModule",{value:!0});var qo=Vi,ag=function(){function e(t){if(this._maxConcurrency=t,this._queue=[],t<=0)throw new Error("semaphore must be initialized to a positive value");this._value=t}return e.prototype.acquire=function(){var t=this,r=this.isLocked(),n=new Promise(function(s){return t._queue.push(s)});return r||this._dispatch(),n},e.prototype.runExclusive=function(t){return qo.__awaiter(this,void 0,void 0,function(){var r,n,s;return qo.__generator(this,function(i){switch(i.label){case 0:return[4,this.acquire()];case 1:r=i.sent(),n=r[0],s=r[1],i.label=2;case 2:return i.trys.push([2,,4,5]),[4,t(n)];case 3:return[2,i.sent()];case 4:return s(),[7];case 5:return[2]}})})},e.prototype.isLocked=function(){return this._value<=0},e.prototype.release=function(){if(this._maxConcurrency>1)throw new Error("this method is unavailabel on semaphores with concurrency > 1; use the scoped release returned by acquire instead");if(this._currentReleaser){var t=this._currentReleaser;this._currentReleaser=void 0,t()}},e.prototype._dispatch=function(){var t=this,r=this._queue.shift();if(r){var n=!1;this._currentReleaser=function(){n||(n=!0,t._value++,t._dispatch())},r([this._value--,this._currentReleaser])}},e}();Ls.default=ag;Object.defineProperty(Ui,"__esModule",{value:!0});var Jo=Vi,cg=Ls,lg=function(){function e(){this._semaphore=new cg.default(1)}return e.prototype.acquire=function(){return Jo.__awaiter(this,void 0,void 0,function(){var t,r;return Jo.__generator(this,function(n){switch(n.label){case 0:return[4,this._semaphore.acquire()];case 1:return t=n.sent(),r=t[1],[2,r]}})})},e.prototype.runExclusive=function(t){return this._semaphore.runExclusive(function(){return t()})},e.prototype.isLocked=function(){return this._semaphore.isLocked()},e.prototype.release=function(){this._semaphore.release()},e}();Ui.default=lg;var xs={};Object.defineProperty(xs,"__esModule",{value:!0});xs.withTimeout=void 0;var Bn=Vi;function ug(e,t,r){var n=this;return r===void 0&&(r=new Error("timeout")),{acquire:function(){return new Promise(function(s,i){return Bn.__awaiter(n,void 0,void 0,function(){var c,u,h;return Bn.__generator(this,function(f){switch(f.label){case 0:return c=!1,setTimeout(function(){c=!0,i(r)},t),[4,e.acquire()];case 1:return u=f.sent(),c?(h=Array.isArray(u)?u[1]:u,h()):s(u),[2]}})})})},runExclusive:function(s){return Bn.__awaiter(this,void 0,void 0,function(){var i,c;return Bn.__generator(this,function(u){switch(u.label){case 0:i=function(){},u.label=1;case 1:return u.trys.push([1,,7,8]),[4,this.acquire()];case 2:return c=u.sent(),Array.isArray(c)?(i=c[1],[4,s(c[0])]):[3,4];case 3:return[2,u.sent()];case 4:return i=c,[4,s()];case 5:return[2,u.sent()];case 6:return[3,8];case 7:return i(),[7];case 8:return[2]}})})},release:function(){e.release()},isLocked:function(){return e.isLocked()}}}xs.withTimeout=ug;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.withTimeout=e.Semaphore=e.Mutex=void 0;var t=Ui;Object.defineProperty(e,"Mutex",{enumerable:!0,get:function(){return t.default}});var r=Ls;Object.defineProperty(e,"Semaphore",{enumerable:!0,get:function(){return r.default}});var n=xs;Object.defineProperty(e,"withTimeout",{enumerable:!0,get:function(){return n.withTimeout}})})($c);var hg=fg,dg=Object.prototype.hasOwnProperty;function fg(){for(var e={},t=0;tfunction(...s){const i=t.promiseModule;return new i((c,u)=>{t.multiArgs?s.push((...f)=>{t.errorFirst?f[0]?u(f):(f.shift(),c(f)):c(f)}):t.errorFirst?s.push((f,g)=>{f?u(f):c(g)}):s.push(c),Reflect.apply(e,this===r?n:this,s)})},Zo=new WeakMap;var wg=(e,t)=>{t={exclude:[/.+(?:Sync|Stream)$/],errorFirst:!0,promiseModule:Promise,...t};const r=typeof e;if(!(e!==null&&(r==="object"||r==="function")))throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${e===null?"null":r}\``);const n=(c,u)=>{let h=Zo.get(c);if(h||(h={},Zo.set(c,h)),u in h)return h[u];const f=C=>typeof C=="string"||typeof u=="symbol"?u===C:C.test(u),g=Reflect.getOwnPropertyDescriptor(c,u),E=g===void 0||g.writable||g.configurable,k=(t.include?t.include.some(f):!t.exclude.some(f))&&E;return h[u]=k,k},s=new WeakMap,i=new Proxy(e,{apply(c,u,h){const f=s.get(c);if(f)return Reflect.apply(f,u,h);const g=t.excludeMain?c:Go(c,t,i,c);return s.set(c,g),Reflect.apply(g,u,h)},get(c,u){const h=c[u];if(!n(c,u)||h===Function.prototype[u])return h;const f=s.get(h);if(f)return f;if(typeof h=="function"){const g=Go(h,t,i,c);return s.set(h,g),g}return h}});return i};const yg=pn.default;let bg=class extends yg{constructor(){super(),this.updates=[]}async initialize(){}async update(){throw new Error("BaseFilter - no update method specified")}addResults(t){this.updates=this.updates.concat(t),t.forEach(r=>this.emit("update",r))}addInitialResults(t){}getChangesAndClear(){const t=this.updates;return this.updates=[],t}};var zi=bg;const _g=zi;let Eg=class extends _g{constructor(){super(),this.allResults=[]}async update(){throw new Error("BaseFilterWithHistory - no update method specified")}addResults(t){this.allResults=this.allResults.concat(t),super.addResults(t)}addInitialResults(t){this.allResults=this.allResults.concat(t),super.addInitialResults(t)}getAllResults(){return this.allResults}};var Sg=Eg,kn={minBlockRef:kg,maxBlockRef:Mg,sortBlockRefs:Wi,bnToHex:Rg,blockRefIsNumber:Ig,hexToInt:Vn,incrementHexInt:Cg,intToHex:Oc,unsafeRandomBytes:Ag};function kg(...e){return Wi(e)[0]}function Mg(...e){const t=Wi(e);return t[t.length-1]}function Wi(e){return e.sort((t,r)=>t==="latest"||r==="earliest"?1:r==="latest"||t==="earliest"?-1:Vn(t)-Vn(r))}function Rg(e){return"0x"+e.toString(16)}function Ig(e){return e&&!["earliest","latest","pending"].includes(e)}function Vn(e){return e==null?e:Number.parseInt(e,16)}function Cg(e){if(e==null)return e;const t=Vn(e);return Oc(t+1)}function Oc(e){if(e==null)return e;let t=e.toString(16);return t.length%2&&(t="0"+t),"0x"+t}function Ag(e){let t="0x";for(let r=0;rn.toLowerCase()))}async initialize({currentBlock:t}){let r=this.params.fromBlock;["latest","pending"].includes(r)&&(r=t),r==="earliest"&&(r="0x0"),this.params.fromBlock=r;const n=Pg(this.params.toBlock,t),s=Object.assign({},this.params,{toBlock:n}),i=await this._fetchLogs(s);this.addInitialResults(i)}async update({oldBlock:t,newBlock:r}){const n=r;let s;t?s=Tg(t):s=r;const i=Object.assign({},this.params,{fromBlock:s,toBlock:n}),u=(await this._fetchLogs(i)).filter(h=>this.matchLog(h));this.addResults(u)}async _fetchLogs(t){return await Lg(n=>this.ethQuery.getLogs(t,n))()}matchLog(t){if(Dn(this.params.fromBlock)>=Dn(t.blockNumber)||$g(this.params.toBlock)&&Dn(this.params.toBlock)<=Dn(t.blockNumber))return!1;const r=t.address&&t.address.toLowerCase();return this.params.address&&r&&!this.params.address.includes(r)?!1:this.params.topics.every((s,i)=>{let c=t.topics[i];if(!c)return!1;c=c.toLowerCase();let u=Array.isArray(s)?s:[s];return u.includes(null)?!0:(u=u.map(g=>g.toLowerCase()),u.includes(c))})}};var Bg=Og,qi=Dg;async function Dg({provider:e,fromBlock:t,toBlock:r}){t||(t=r);const n=Ko(t),i=Ko(r)-n+1,c=Array(i).fill().map((h,f)=>n+f).map(jg);let u=await Promise.all(c.map(h=>Hg(e,"eth_getBlockByNumber",[h,!1])));return u=u.filter(h=>h!==null),u}function Ko(e){return e==null?e:Number.parseInt(e,16)}function jg(e){return e==null?e:"0x"+e.toString(16)}function Fg(e,t){return new Promise((r,n)=>{e.sendAsync(t,(s,i)=>{s?n(s):i.error?n(i.error):i.result?r(i.result):n(new Error("Result was empty"))})})}async function Hg(e,t,r){for(let n=0;n<3;n++)try{return await Fg(e,{id:1,jsonrpc:"2.0",method:t,params:r})}catch(s){console.error(`provider.sendAsync failed: ${s.stack||s.message||s}`)}return null}const Ug=zi,Vg=qi,{incrementHexInt:zg}=kn;let Wg=class extends Ug{constructor({provider:t,params:r}){super(),this.type="block",this.provider=t}async update({oldBlock:t,newBlock:r}){const n=r,s=zg(t),c=(await Vg({provider:this.provider,fromBlock:s,toBlock:n})).map(u=>u.hash);this.addResults(c)}};var qg=Wg;const Jg=zi,Gg=qi,{incrementHexInt:Zg}=kn;let Qg=class extends Jg{constructor({provider:t}){super(),this.type="tx",this.provider=t}async update({oldBlock:t}){const r=t,n=Zg(t),s=await Gg({provider:this.provider,fromBlock:n,toBlock:r}),i=[];for(const c of s)i.push(...c.transactions);this.addResults(i)}};var Kg=Qg;const Xg=$c.Mutex,{createAsyncMiddleware:Yg,createScaffoldMiddleware:ep}=Di,tp=Bg,rp=qg,np=Kg,{intToHex:Bc,hexToInt:ri}=kn;var sp=ip;function ip({blockTracker:e,provider:t}){let r=0,n={};const s=new Xg,i=op({mutex:s}),c=ep({eth_newFilter:i(ni(h)),eth_newBlockFilter:i(ni(f)),eth_newPendingTransactionFilter:i(ni(g)),eth_uninstallFilter:i(Fn(k)),eth_getFilterChanges:i(Fn(E)),eth_getFilterLogs:i(Fn(b))}),u=async({oldBlock:L,newBlock:M})=>{if(n.length===0)return;const j=await s.acquire();try{await Promise.all(_r(n).map(async A=>{try{await A.update({oldBlock:L,newBlock:M})}catch($){console.error($)}}))}catch(A){console.error(A)}j()};return c.newLogFilter=h,c.newBlockFilter=f,c.newPendingTransactionFilter=g,c.uninstallFilter=k,c.getFilterChanges=E,c.getFilterLogs=b,c.destroy=()=>{I()},c;async function h(L){const M=new tp({provider:t,params:L});return await C(M),M}async function f(){const L=new rp({provider:t});return await C(L),L}async function g(){const L=new np({provider:t});return await C(L),L}async function E(L){const M=ri(L),j=n[M];if(!j)throw new Error(`No filter for index "${M}"`);return j.getChangesAndClear()}async function b(L){const M=ri(L),j=n[M];if(!j)throw new Error(`No filter for index "${M}"`);let A=[];return j.type==="log"&&(A=j.getAllResults()),A}async function k(L){const M=ri(L),A=!!n[M];return A&&await R(M),A}async function C(L){const M=_r(n).length,j=await e.getLatestBlock();await L.initialize({currentBlock:j}),r++,n[r]=L,L.id=r,L.idHex=Bc(r);const A=_r(n).length;return P({prevFilterCount:M,newFilterCount:A}),r}async function R(L){const M=_r(n).length;delete n[L];const j=_r(n).length;P({prevFilterCount:M,newFilterCount:j})}async function I(){const L=_r(n).length;n={},P({prevFilterCount:L,newFilterCount:0})}function P({prevFilterCount:L,newFilterCount:M}){if(L===0&&M>0){e.on("sync",u);return}if(L>0&&M===0){e.removeListener("sync",u);return}}}function ni(e){return Fn(async(...t)=>{const r=await e(...t);return Bc(r.id)})}function Fn(e){return Yg(async(t,r)=>{const n=await e.apply(null,t.params);r.result=n})}function op({mutex:e}){return t=>async(r,n,s,i)=>{(await e.acquire())(),t(r,n,s,i)}}function _r(e,t){const r=[];for(let n in e)r.push(e[n]);return r}const ap=pn.default,{createAsyncMiddleware:Xo,createScaffoldMiddleware:cp}=Di,lp=sp,{unsafeRandomBytes:up,incrementHexInt:hp}=kn,dp=qi;var fp=gp;function gp({blockTracker:e,provider:t}){const r={},n=lp({blockTracker:e,provider:t});let s=!1;const i=new ap,c=cp({eth_subscribe:Xo(u),eth_unsubscribe:Xo(h)});return c.destroy=g,{events:i,middleware:c};async function u(E,b){if(s)throw new Error("SubscriptionManager - attempting to use after destroying");const k=E.params[0],C=up(16);let R;switch(k){case"newHeads":R=I({subId:C});break;case"logs":const L=E.params[1],M=await n.newLogFilter(L);R=P({subId:C,filter:M});break;default:throw new Error(`SubscriptionManager - unsupported subscription type "${k}"`)}r[C]=R,b.result=C;return;function I({subId:L}){const M={type:k,destroy:async()=>{e.removeListener("sync",M.update)},update:async({oldBlock:j,newBlock:A})=>{const $=A,J=hp(j);(await dp({provider:t,fromBlock:J,toBlock:$})).map(pp).filter(Q=>Q!==null).forEach(Q=>{f(L,Q)})}};return e.on("sync",M.update),M}function P({subId:L,filter:M}){return M.on("update",A=>f(L,A)),{type:k,destroy:async()=>await n.uninstallFilter(M.idHex)}}}async function h(E,b){if(s)throw new Error("SubscriptionManager - attempting to use after destroying");const k=E.params[0],C=r[k];if(!C){b.result=!1;return}delete r[k],await C.destroy(),b.result=!0}function f(E,b){i.emit("notification",{jsonrpc:"2.0",method:"eth_subscription",params:{subscription:E,result:b}})}function g(){i.removeAllListeners();for(const E in r)r[E].destroy(),delete r[E];s=!0}}function pp(e){return e==null?null:{hash:e.hash,parentHash:e.parentHash,sha3Uncles:e.sha3Uncles,miner:e.miner,stateRoot:e.stateRoot,transactionsRoot:e.transactionsRoot,receiptsRoot:e.receiptsRoot,logsBloom:e.logsBloom,difficulty:e.difficulty,number:e.number,gasLimit:e.gasLimit,gasUsed:e.gasUsed,nonce:e.nonce,mixHash:e.mixHash,timestamp:e.timestamp,extraData:e.extraData}}Object.defineProperty(ps,"__esModule",{value:!0});ps.SubscriptionManager=void 0;const mp=Va,vp=fp,Yo=()=>{};class wp{constructor(t){const r=new mp.PollingBlockTracker({provider:t,pollingInterval:15e3,setSkipCacheFlag:!0}),{events:n,middleware:s}=vp({blockTracker:r,provider:t});this.events=n,this.subscriptionMiddleware=s}async handleRequest(t){const r={};return await this.subscriptionMiddleware(t,r,Yo,Yo),r}destroy(){this.subscriptionMiddleware.destroy()}}ps.SubscriptionManager=wp;var Dc=B&&B.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Cr,"__esModule",{value:!0});Cr.CoinbaseWalletProvider=void 0;const yp=Dc(qn),bp=El,V=nn,F=T,_p=cn,ea=it,jn=Br,Ye=Pr,si=Dc(rh),Kr=Or,Ep=Lr,Sp=ps,ta="DefaultChainId",ra="DefaultJsonRpcUrl";class kp extends bp.EventEmitter{constructor(t){var r,n;super(),this._filterPolyfill=new Ep.FilterPolyfill(this),this._subscriptionManager=new Sp.SubscriptionManager(this),this._relay=null,this._addresses=[],this.hasMadeFirstChainChangedEmission=!1,this.setProviderInfo=this.setProviderInfo.bind(this),this.updateProviderInfo=this.updateProviderInfo.bind(this),this.getChainId=this.getChainId.bind(this),this.setAppInfo=this.setAppInfo.bind(this),this.enable=this.enable.bind(this),this.close=this.close.bind(this),this.send=this.send.bind(this),this.sendAsync=this.sendAsync.bind(this),this.request=this.request.bind(this),this._setAddresses=this._setAddresses.bind(this),this.scanQRCode=this.scanQRCode.bind(this),this.genericRequest=this.genericRequest.bind(this),this._chainIdFromOpts=t.chainId,this._jsonRpcUrlFromOpts=t.jsonRpcUrl,this._overrideIsMetaMask=t.overrideIsMetaMask,this._relayProvider=t.relayProvider,this._storage=t.storage,this._relayEventManager=t.relayEventManager,this.diagnostic=t.diagnosticLogger,this.reloadOnDisconnect=!0,this.isCoinbaseWallet=(r=t.overrideIsCoinbaseWallet)!==null&&r!==void 0?r:!0,this.isCoinbaseBrowser=(n=t.overrideIsCoinbaseBrowser)!==null&&n!==void 0?n:!1,this.qrUrl=t.qrUrl;const s=this.getChainId(),i=(0,F.prepend0x)(s.toString(16));this.emit("connect",{chainIdStr:i});const c=this._storage.getItem(ea.LOCAL_STORAGE_ADDRESSES_KEY);if(c){const u=c.split(" ");u[0]!==""&&(this._addresses=u.map(h=>(0,F.ensureAddressString)(h)),this.emit("accountsChanged",u))}this._subscriptionManager.events.on("notification",u=>{this.emit("message",{type:u.method,data:u.params})}),this._isAuthorized()&&this.initializeRelay(),window.addEventListener("message",u=>{var h;if(!(u.origin!==location.origin||u.source!==window)&&u.data.type==="walletLinkMessage"&&u.data.data.action==="dappChainSwitched"){const f=u.data.data.chainId,g=(h=u.data.data.jsonRpcUrl)!==null&&h!==void 0?h:this.jsonRpcUrl;this.updateProviderInfo(g,Number(f))}})}get selectedAddress(){return this._addresses[0]||void 0}get networkVersion(){return this.getChainId().toString(10)}get chainId(){return(0,F.prepend0x)(this.getChainId().toString(16))}get isWalletLink(){return!0}get isMetaMask(){return this._overrideIsMetaMask}get host(){return this.jsonRpcUrl}get connected(){return!0}isConnected(){return!0}get jsonRpcUrl(){var t;return(t=this._storage.getItem(ra))!==null&&t!==void 0?t:this._jsonRpcUrlFromOpts}set jsonRpcUrl(t){this._storage.setItem(ra,t)}disableReloadOnDisconnect(){this.reloadOnDisconnect=!1}setProviderInfo(t,r){this.isCoinbaseBrowser||(this._chainIdFromOpts=r,this._jsonRpcUrlFromOpts=t),this.updateProviderInfo(this.jsonRpcUrl,this.getChainId())}updateProviderInfo(t,r){this.jsonRpcUrl=t;const n=this.getChainId();this._storage.setItem(ta,r.toString(10)),((0,F.ensureIntNumber)(r)!==n||!this.hasMadeFirstChainChangedEmission)&&(this.emit("chainChanged",this.getChainId()),this.hasMadeFirstChainChangedEmission=!0)}async watchAsset(t,r,n,s,i,c){const h=await(await this.initializeRelay()).watchAsset(t,r,n,s,i,c?.toString()).promise;return(0,Ye.isErrorResponse)(h)?!1:!!h.result}async addEthereumChain(t,r,n,s,i,c){var u,h;if((0,F.ensureIntNumber)(t)===this.getChainId())return!1;const f=await this.initializeRelay(),g=f.inlineAddEthereumChain(t.toString());!this._isAuthorized()&&!g&&await f.requestEthereumAccounts().promise;const E=await f.addEthereumChain(t.toString(),r,i,n,s,c).promise;return(0,Ye.isErrorResponse)(E)?!1:(((u=E.result)===null||u===void 0?void 0:u.isApproved)===!0&&this.updateProviderInfo(r[0],t),((h=E.result)===null||h===void 0?void 0:h.isApproved)===!0)}async switchEthereumChain(t){const n=await(await this.initializeRelay()).switchEthereumChain(t.toString(10),this.selectedAddress||void 0).promise;if((0,Ye.isErrorResponse)(n)){if(!n.errorCode)return;throw n.errorCode===V.standardErrorCodes.provider.unsupportedChain?V.standardErrors.provider.unsupportedChain():V.standardErrors.provider.custom({message:n.errorMessage,code:n.errorCode})}const s=n.result;s.isApproved&&s.rpcUrl.length>0&&this.updateProviderInfo(s.rpcUrl,t)}setAppInfo(t,r){this.initializeRelay().then(n=>n.setAppInfo(t,r))}async enable(){var t;return(t=this.diagnostic)===null||t===void 0||t.log(Kr.EVENTS.ETH_ACCOUNTS_STATE,{method:"provider::enable",addresses_length:this._addresses.length,sessionIdHash:this._relay?jn.Session.hash(this._relay.session.id):void 0}),this._isAuthorized()?[...this._addresses]:await this.send("eth_requestAccounts")}async close(){(await this.initializeRelay()).resetAndReload()}send(t,r){try{const n=this._send(t,r);if(n instanceof Promise)return n.catch(s=>{throw(0,V.serializeError)(s,t)})}catch(n){throw(0,V.serializeError)(n,t)}}_send(t,r){if(typeof t=="string"){const s=t,i=Array.isArray(r)?r:r!==void 0?[r]:[],c={jsonrpc:"2.0",id:0,method:s,params:i};return this._sendRequestAsync(c).then(u=>u.result)}if(typeof r=="function"){const s=t,i=r;return this._sendAsync(s,i)}if(Array.isArray(t))return t.map(i=>this._sendRequest(i));const n=t;return this._sendRequest(n)}async sendAsync(t,r){try{return this._sendAsync(t,r).catch(n=>{throw(0,V.serializeError)(n,t)})}catch(n){return Promise.reject((0,V.serializeError)(n,t))}}async _sendAsync(t,r){if(typeof r!="function")throw new Error("callback is required");if(Array.isArray(t)){const s=r;this._sendMultipleRequestsAsync(t).then(i=>s(null,i)).catch(i=>s(i,null));return}const n=r;return this._sendRequestAsync(t).then(s=>n(null,s)).catch(s=>n(s,null))}async request(t){try{return this._request(t).catch(r=>{throw(0,V.serializeError)(r,t.method)})}catch(r){return Promise.reject((0,V.serializeError)(r,t.method))}}async _request(t){if(!t||typeof t!="object"||Array.isArray(t))throw V.standardErrors.rpc.invalidRequest({message:"Expected a single, non-array, object argument.",data:t});const{method:r,params:n}=t;if(typeof r!="string"||r.length===0)throw V.standardErrors.rpc.invalidRequest({message:"'args.method' must be a non-empty string.",data:t});if(n!==void 0&&!Array.isArray(n)&&(typeof n!="object"||n===null))throw V.standardErrors.rpc.invalidRequest({message:"'args.params' must be an object or array if provided.",data:t});const s=n===void 0?[]:n,i=this._relayEventManager.makeRequestId();return(await this._sendRequestAsync({method:r,params:s,jsonrpc:"2.0",id:i})).result}async scanQRCode(t){const n=await(await this.initializeRelay()).scanQRCode((0,F.ensureRegExpString)(t)).promise;if((0,Ye.isErrorResponse)(n))throw(0,V.serializeError)(n.errorMessage,"scanQRCode");if(typeof n.result!="string")throw(0,V.serializeError)("result was not a string","scanQRCode");return n.result}async genericRequest(t,r){const s=await(await this.initializeRelay()).genericRequest(t,r).promise;if((0,Ye.isErrorResponse)(s))throw(0,V.serializeError)(s.errorMessage,"generic");if(typeof s.result!="string")throw(0,V.serializeError)("result was not a string","generic");return s.result}async connectAndSignIn(t){var r;(r=this.diagnostic)===null||r===void 0||r.log(Kr.EVENTS.ETH_ACCOUNTS_STATE,{method:"provider::connectAndSignIn",sessionIdHash:this._relay?jn.Session.hash(this._relay.session.id):void 0});let n;try{const i=await this.initializeRelay();if(!(i instanceof _p.MobileRelay))throw new Error("connectAndSignIn is only supported on mobile");if(n=await i.connectAndSignIn(t).promise,(0,Ye.isErrorResponse)(n))throw new Error(n.errorMessage)}catch(i){throw typeof i.message=="string"&&i.message.match(/(denied|rejected)/i)?V.standardErrors.provider.userRejectedRequest("User denied account authorization"):i}if(!n.result)throw new Error("accounts received is empty");const{accounts:s}=n.result;return this._setAddresses(s),this.isCoinbaseBrowser||await this.switchEthereumChain(this.getChainId()),n.result}async selectProvider(t){const n=await(await this.initializeRelay()).selectProvider(t).promise;if((0,Ye.isErrorResponse)(n))throw(0,V.serializeError)(n.errorMessage,"selectProvider");if(typeof n.result!="string")throw(0,V.serializeError)("result was not a string","selectProvider");return n.result}supportsSubscriptions(){return!1}subscribe(){throw new Error("Subscriptions are not supported")}unsubscribe(){throw new Error("Subscriptions are not supported")}disconnect(){return!0}_sendRequest(t){const r={jsonrpc:"2.0",id:t.id},{method:n}=t;if(r.result=this._handleSynchronousMethods(t),r.result===void 0)throw new Error(`Coinbase Wallet does not support calling ${n} synchronously without a callback. Please provide a callback parameter to call ${n} asynchronously.`);return r}_setAddresses(t,r){if(!Array.isArray(t))throw new Error("addresses is not an array");const n=t.map(s=>(0,F.ensureAddressString)(s));JSON.stringify(n)!==JSON.stringify(this._addresses)&&(this._addresses=n,this.emit("accountsChanged",this._addresses),this._storage.setItem(ea.LOCAL_STORAGE_ADDRESSES_KEY,n.join(" ")))}_sendRequestAsync(t){return new Promise((r,n)=>{try{const s=this._handleSynchronousMethods(t);if(s!==void 0)return r({jsonrpc:"2.0",id:t.id,result:s});const i=this._handleAsynchronousFilterMethods(t);if(i!==void 0){i.then(u=>r(Object.assign(Object.assign({},u),{id:t.id}))).catch(u=>n(u));return}const c=this._handleSubscriptionMethods(t);if(c!==void 0){c.then(u=>r({jsonrpc:"2.0",id:t.id,result:u.result})).catch(u=>n(u));return}}catch(s){return n(s)}this._handleAsynchronousMethods(t).then(s=>s&&r(Object.assign(Object.assign({},s),{id:t.id}))).catch(s=>n(s))})}_sendMultipleRequestsAsync(t){return Promise.all(t.map(r=>this._sendRequestAsync(r)))}_handleSynchronousMethods(t){const{method:r}=t,n=t.params||[];switch(r){case"eth_accounts":return this._eth_accounts();case"eth_coinbase":return this._eth_coinbase();case"eth_uninstallFilter":return this._eth_uninstallFilter(n);case"net_version":return this._net_version();case"eth_chainId":return this._eth_chainId();default:return}}async _handleAsynchronousMethods(t){const{method:r}=t,n=t.params||[];switch(r){case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_sign":return this._eth_sign(n);case"eth_ecRecover":return this._eth_ecRecover(n);case"personal_sign":return this._personal_sign(n);case"personal_ecRecover":return this._personal_ecRecover(n);case"eth_signTransaction":return this._eth_signTransaction(n);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(n);case"eth_sendTransaction":return this._eth_sendTransaction(n);case"eth_signTypedData_v1":return this._eth_signTypedData_v1(n);case"eth_signTypedData_v2":return this._throwUnsupportedMethodError();case"eth_signTypedData_v3":return this._eth_signTypedData_v3(n);case"eth_signTypedData_v4":case"eth_signTypedData":return this._eth_signTypedData_v4(n);case"cbWallet_arbitrary":return this._cbwallet_arbitrary(n);case"wallet_addEthereumChain":return this._wallet_addEthereumChain(n);case"wallet_switchEthereumChain":return this._wallet_switchEthereumChain(n);case"wallet_watchAsset":return this._wallet_watchAsset(n)}return(await this.initializeRelay()).makeEthereumJSONRPCRequest(t,this.jsonRpcUrl).catch(i=>{var c;throw(i.code===V.standardErrorCodes.rpc.methodNotFound||i.code===V.standardErrorCodes.rpc.methodNotSupported)&&((c=this.diagnostic)===null||c===void 0||c.log(Kr.EVENTS.METHOD_NOT_IMPLEMENTED,{method:t.method,sessionIdHash:this._relay?jn.Session.hash(this._relay.session.id):void 0})),i})}_handleAsynchronousFilterMethods(t){const{method:r}=t,n=t.params||[];switch(r){case"eth_newFilter":return this._eth_newFilter(n);case"eth_newBlockFilter":return this._eth_newBlockFilter();case"eth_newPendingTransactionFilter":return this._eth_newPendingTransactionFilter();case"eth_getFilterChanges":return this._eth_getFilterChanges(n);case"eth_getFilterLogs":return this._eth_getFilterLogs(n)}}_handleSubscriptionMethods(t){switch(t.method){case"eth_subscribe":case"eth_unsubscribe":return this._subscriptionManager.handleRequest(t)}}_isKnownAddress(t){try{const r=(0,F.ensureAddressString)(t);return this._addresses.map(s=>(0,F.ensureAddressString)(s)).includes(r)}catch{}return!1}_ensureKnownAddress(t){var r;if(!this._isKnownAddress(t))throw(r=this.diagnostic)===null||r===void 0||r.log(Kr.EVENTS.UNKNOWN_ADDRESS_ENCOUNTERED),new Error("Unknown Ethereum address")}_prepareTransactionParams(t){const r=t.from?(0,F.ensureAddressString)(t.from):this.selectedAddress;if(!r)throw new Error("Ethereum address is unavailable");this._ensureKnownAddress(r);const n=t.to?(0,F.ensureAddressString)(t.to):null,s=t.value!=null?(0,F.ensureBN)(t.value):new yp.default(0),i=t.data?(0,F.ensureBuffer)(t.data):Buffer.alloc(0),c=t.nonce!=null?(0,F.ensureIntNumber)(t.nonce):null,u=t.gasPrice!=null?(0,F.ensureBN)(t.gasPrice):null,h=t.maxFeePerGas!=null?(0,F.ensureBN)(t.maxFeePerGas):null,f=t.maxPriorityFeePerGas!=null?(0,F.ensureBN)(t.maxPriorityFeePerGas):null,g=t.gas!=null?(0,F.ensureBN)(t.gas):null,E=t.chainId?(0,F.ensureIntNumber)(t.chainId):this.getChainId();return{fromAddress:r,toAddress:n,weiValue:s,data:i,nonce:c,gasPriceInWei:u,maxFeePerGas:h,maxPriorityFeePerGas:f,gasLimit:g,chainId:E}}_isAuthorized(){return this._addresses.length>0}_requireAuthorization(){if(!this._isAuthorized())throw V.standardErrors.provider.unauthorized({})}_throwUnsupportedMethodError(){throw V.standardErrors.provider.unsupportedMethod({})}async _signEthereumMessage(t,r,n,s){this._ensureKnownAddress(r);try{const c=await(await this.initializeRelay()).signEthereumMessage(t,r,n,s).promise;if((0,Ye.isErrorResponse)(c))throw new Error(c.errorMessage);return{jsonrpc:"2.0",id:0,result:c.result}}catch(i){throw typeof i.message=="string"&&i.message.match(/(denied|rejected)/i)?V.standardErrors.provider.userRejectedRequest("User denied message signature"):i}}async _ethereumAddressFromSignedMessage(t,r,n){const i=await(await this.initializeRelay()).ethereumAddressFromSignedMessage(t,r,n).promise;if((0,Ye.isErrorResponse)(i))throw new Error(i.errorMessage);return{jsonrpc:"2.0",id:0,result:i.result}}_eth_accounts(){return[...this._addresses]}_eth_coinbase(){return this.selectedAddress||null}_net_version(){return this.getChainId().toString(10)}_eth_chainId(){return(0,F.hexStringFromIntNumber)(this.getChainId())}getChainId(){const t=this._storage.getItem(ta);if(!t)return(0,F.ensureIntNumber)(this._chainIdFromOpts);const r=parseInt(t,10);return(0,F.ensureIntNumber)(r)}async _eth_requestAccounts(){var t;if((t=this.diagnostic)===null||t===void 0||t.log(Kr.EVENTS.ETH_ACCOUNTS_STATE,{method:"provider::_eth_requestAccounts",addresses_length:this._addresses.length,sessionIdHash:this._relay?jn.Session.hash(this._relay.session.id):void 0}),this._isAuthorized())return Promise.resolve({jsonrpc:"2.0",id:0,result:this._addresses});let r;try{if(r=await(await this.initializeRelay()).requestEthereumAccounts().promise,(0,Ye.isErrorResponse)(r))throw new Error(r.errorMessage)}catch(n){throw typeof n.message=="string"&&n.message.match(/(denied|rejected)/i)?V.standardErrors.provider.userRejectedRequest("User denied account authorization"):n}if(!r.result)throw new Error("accounts received is empty");return this._setAddresses(r.result),this.isCoinbaseBrowser||await this.switchEthereumChain(this.getChainId()),{jsonrpc:"2.0",id:0,result:this._addresses}}_eth_sign(t){this._requireAuthorization();const r=(0,F.ensureAddressString)(t[0]),n=(0,F.ensureBuffer)(t[1]);return this._signEthereumMessage(n,r,!1)}_eth_ecRecover(t){const r=(0,F.ensureBuffer)(t[0]),n=(0,F.ensureBuffer)(t[1]);return this._ethereumAddressFromSignedMessage(r,n,!1)}_personal_sign(t){this._requireAuthorization();const r=(0,F.ensureBuffer)(t[0]),n=(0,F.ensureAddressString)(t[1]);return this._signEthereumMessage(r,n,!0)}_personal_ecRecover(t){const r=(0,F.ensureBuffer)(t[0]),n=(0,F.ensureBuffer)(t[1]);return this._ethereumAddressFromSignedMessage(r,n,!0)}async _eth_signTransaction(t){this._requireAuthorization();const r=this._prepareTransactionParams(t[0]||{});try{const s=await(await this.initializeRelay()).signEthereumTransaction(r).promise;if((0,Ye.isErrorResponse)(s))throw new Error(s.errorMessage);return{jsonrpc:"2.0",id:0,result:s.result}}catch(n){throw typeof n.message=="string"&&n.message.match(/(denied|rejected)/i)?V.standardErrors.provider.userRejectedRequest("User denied transaction signature"):n}}async _eth_sendRawTransaction(t){const r=(0,F.ensureBuffer)(t[0]),s=await(await this.initializeRelay()).submitEthereumTransaction(r,this.getChainId()).promise;if((0,Ye.isErrorResponse)(s))throw new Error(s.errorMessage);return{jsonrpc:"2.0",id:0,result:s.result}}async _eth_sendTransaction(t){this._requireAuthorization();const r=this._prepareTransactionParams(t[0]||{});try{const s=await(await this.initializeRelay()).signAndSubmitEthereumTransaction(r).promise;if((0,Ye.isErrorResponse)(s))throw new Error(s.errorMessage);return{jsonrpc:"2.0",id:0,result:s.result}}catch(n){throw typeof n.message=="string"&&n.message.match(/(denied|rejected)/i)?V.standardErrors.provider.userRejectedRequest("User denied transaction signature"):n}}async _eth_signTypedData_v1(t){this._requireAuthorization();const r=(0,F.ensureParsedJSONObject)(t[0]),n=(0,F.ensureAddressString)(t[1]);this._ensureKnownAddress(n);const s=si.default.hashForSignTypedDataLegacy({data:r}),i=JSON.stringify(r,null,2);return this._signEthereumMessage(s,n,!1,i)}async _eth_signTypedData_v3(t){this._requireAuthorization();const r=(0,F.ensureAddressString)(t[0]),n=(0,F.ensureParsedJSONObject)(t[1]);this._ensureKnownAddress(r);const s=si.default.hashForSignTypedData_v3({data:n}),i=JSON.stringify(n,null,2);return this._signEthereumMessage(s,r,!1,i)}async _eth_signTypedData_v4(t){this._requireAuthorization();const r=(0,F.ensureAddressString)(t[0]),n=(0,F.ensureParsedJSONObject)(t[1]);this._ensureKnownAddress(r);const s=si.default.hashForSignTypedData_v4({data:n}),i=JSON.stringify(n,null,2);return this._signEthereumMessage(s,r,!1,i)}async _cbwallet_arbitrary(t){const r=t[0],n=t[1];if(typeof n!="string")throw new Error("parameter must be a string");if(typeof r!="object"||r===null)throw new Error("parameter must be an object");return{jsonrpc:"2.0",id:0,result:await this.genericRequest(r,n)}}async _wallet_addEthereumChain(t){var r,n,s,i;const c=t[0];if(((r=c.rpcUrls)===null||r===void 0?void 0:r.length)===0)return{jsonrpc:"2.0",id:0,error:{code:2,message:"please pass in at least 1 rpcUrl"}};if(!c.chainName||c.chainName.trim()==="")throw V.standardErrors.rpc.invalidParams("chainName is a required field");if(!c.nativeCurrency)throw V.standardErrors.rpc.invalidParams("nativeCurrency is a required field");const u=parseInt(c.chainId,16);return await this.addEthereumChain(u,(n=c.rpcUrls)!==null&&n!==void 0?n:[],(s=c.blockExplorerUrls)!==null&&s!==void 0?s:[],c.chainName,(i=c.iconUrls)!==null&&i!==void 0?i:[],c.nativeCurrency)?{jsonrpc:"2.0",id:0,result:null}:{jsonrpc:"2.0",id:0,error:{code:2,message:"unable to add ethereum chain"}}}async _wallet_switchEthereumChain(t){const r=t[0];return await this.switchEthereumChain(parseInt(r.chainId,16)),{jsonrpc:"2.0",id:0,result:null}}async _wallet_watchAsset(t){const r=Array.isArray(t)?t[0]:t;if(!r.type)throw V.standardErrors.rpc.invalidParams("Type is required");if(r?.type!=="ERC20")throw V.standardErrors.rpc.invalidParams(`Asset of type '${r.type}' is not supported`);if(!r?.options)throw V.standardErrors.rpc.invalidParams("Options are required");if(!r?.options.address)throw V.standardErrors.rpc.invalidParams("Address is required");const n=this.getChainId(),{address:s,symbol:i,image:c,decimals:u}=r.options;return{jsonrpc:"2.0",id:0,result:await this.watchAsset(r.type,s,i,u,c,n)}}_eth_uninstallFilter(t){const r=(0,F.ensureHexString)(t[0]);return this._filterPolyfill.uninstallFilter(r)}async _eth_newFilter(t){const r=t[0];return{jsonrpc:"2.0",id:0,result:await this._filterPolyfill.newFilter(r)}}async _eth_newBlockFilter(){return{jsonrpc:"2.0",id:0,result:await this._filterPolyfill.newBlockFilter()}}async _eth_newPendingTransactionFilter(){return{jsonrpc:"2.0",id:0,result:await this._filterPolyfill.newPendingTransactionFilter()}}_eth_getFilterChanges(t){const r=(0,F.ensureHexString)(t[0]);return this._filterPolyfill.getFilterChanges(r)}_eth_getFilterLogs(t){const r=(0,F.ensureHexString)(t[0]);return this._filterPolyfill.getFilterLogs(r)}initializeRelay(){return this._relay?Promise.resolve(this._relay):this._relayProvider().then(t=>(t.setAccountsCallback((r,n)=>this._setAddresses(r,n)),t.setChainCallback((r,n)=>{this.updateProviderInfo(n,parseInt(r,10))}),t.setDappDefaultChainCallback(this._chainIdFromOpts),this._relay=t,t))}}Cr.CoinbaseWalletProvider=kp;var Ts={};Object.defineProperty(Ts,"__esModule",{value:!0});Ts.RelayEventManager=void 0;const Mp=T;class Rp{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%2147483647;const t=this._nextRequestId,r=(0,Mp.prepend0x)(t.toString(16));return this.callbacks.get(r)&&this.callbacks.delete(r),t}}Ts.RelayEventManager=Rp;Object.defineProperty(Yr,"__esModule",{value:!0});Yr.CoinbaseWalletSDK=void 0;const Ip=zn,Cp=Wn,na=T,Ap=Kn,Np=Cr,Lp=cn,xp=fn,Tp=Ts,Pp=un,$p=ln,jc=$r;class Ps{constructor(t){var r,n,s;this._appName="",this._appLogoUrl=null,this._relay=null,this._relayEventManager=null;const i=t.linkAPIUrl||Cp.LINK_API_URL;typeof t.overrideIsMetaMask>"u"?this._overrideIsMetaMask=!1:this._overrideIsMetaMask=t.overrideIsMetaMask,this._overrideIsCoinbaseWallet=(r=t.overrideIsCoinbaseWallet)!==null&&r!==void 0?r:!0,this._overrideIsCoinbaseBrowser=(n=t.overrideIsCoinbaseBrowser)!==null&&n!==void 0?n:!1,this._diagnosticLogger=t.diagnosticLogger,this._reloadOnDisconnect=(s=t.reloadOnDisconnect)!==null&&s!==void 0?s:!0;const c=new URL(i),u=`${c.protocol}//${c.host}`;if(this._storage=new Ap.ScopedLocalStorage(`-walletlink:${u}`),this._storage.setItem("version",Ps.VERSION),this.walletExtension||this.coinbaseBrowser)return;this._relayEventManager=new Tp.RelayEventManager;const h=(0,na.isMobileWeb)(),f=t.uiConstructor||(E=>h?new xp.MobileRelayUI(E):new Pp.WalletLinkRelayUI(E)),g={linkAPIUrl:i,version:jc.LIB_VERSION,darkMode:!!t.darkMode,headlessMode:!!t.headlessMode,uiConstructor:f,storage:this._storage,relayEventManager:this._relayEventManager,diagnosticLogger:this._diagnosticLogger,reloadOnDisconnect:this._reloadOnDisconnect,enableMobileWalletLink:t.enableMobileWalletLink};this._relay=h?new Lp.MobileRelay(g):new $p.WalletLinkRelay(g),this.setAppInfo(t.appName,t.appLogoUrl),!t.headlessMode&&this._relay.attachUI()}makeWeb3Provider(t="",r=1){const n=this.walletExtension;if(n)return this.isCipherProvider(n)||n.setProviderInfo(t,r),this._reloadOnDisconnect===!1&&typeof n.disableReloadOnDisconnect=="function"&&n.disableReloadOnDisconnect(),n;const s=this.coinbaseBrowser;if(s)return s;const i=this._relay;if(!i||!this._relayEventManager||!this._storage)throw new Error("Relay not initialized, should never happen");return t||i.setConnectDisabled(!0),new Np.CoinbaseWalletProvider({relayProvider:()=>Promise.resolve(i),relayEventManager:this._relayEventManager,storage:this._storage,jsonRpcUrl:t,chainId:r,qrUrl:this.getQrUrl(),diagnosticLogger:this._diagnosticLogger,overrideIsMetaMask:this._overrideIsMetaMask,overrideIsCoinbaseWallet:this._overrideIsCoinbaseWallet,overrideIsCoinbaseBrowser:this._overrideIsCoinbaseBrowser})}setAppInfo(t,r){var n;this._appName=t||"DApp",this._appLogoUrl=r||(0,na.getFavicon)();const s=this.walletExtension;s?this.isCipherProvider(s)||s.setAppInfo(this._appName,this._appLogoUrl):(n=this._relay)===null||n===void 0||n.setAppInfo(this._appName,this._appLogoUrl)}disconnect(){var t;const r=this===null||this===void 0?void 0:this.walletExtension;r?r.close():(t=this._relay)===null||t===void 0||t.resetAndReload()}getQrUrl(){var t,r;return(r=(t=this._relay)===null||t===void 0?void 0:t.getQRCodeUrl())!==null&&r!==void 0?r:null}getCoinbaseWalletLogo(t,r=240){return(0,Ip.walletLogo)(t,r)}get walletExtension(){var t;return(t=window.coinbaseWalletExtension)!==null&&t!==void 0?t:window.walletLinkExtension}get coinbaseBrowser(){var t,r;try{const n=(t=window.ethereum)!==null&&t!==void 0?t:(r=window.top)===null||r===void 0?void 0:r.ethereum;return n&&"isCoinbaseBrowser"in n&&n.isCoinbaseBrowser?n:void 0}catch{return}}isCipherProvider(t){return typeof t.isCipher=="boolean"&&t.isCipher}}Yr.CoinbaseWalletSDK=Ps;Ps.VERSION=jc.LIB_VERSION;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CoinbaseWalletProvider=e.CoinbaseWalletSDK=void 0;const t=Yr,r=Cr;var n=Yr;Object.defineProperty(e,"CoinbaseWalletSDK",{enumerable:!0,get:function(){return n.CoinbaseWalletSDK}});var s=Cr;Object.defineProperty(e,"CoinbaseWalletProvider",{enumerable:!0,get:function(){return s.CoinbaseWalletProvider}}),e.default=t.CoinbaseWalletSDK,typeof window<"u"&&(window.CoinbaseWalletSDK=t.CoinbaseWalletSDK,window.CoinbaseWalletProvider=r.CoinbaseWalletProvider,window.WalletLink=t.CoinbaseWalletSDK,window.WalletLinkProvider=r.CoinbaseWalletProvider)})(oa);const Op=Vc(oa),Qp=Object.freeze(Object.defineProperty({__proto__:null,default:Op},Symbol.toStringTag,{value:"Module"}));export{Qp as i}; diff --git a/dist/assets/index-sYri9oP4.js b/dist/assets/index-sYri9oP4.js new file mode 100644 index 0000000..a1c3b68 --- /dev/null +++ b/dist/assets/index-sYri9oP4.js @@ -0,0 +1 @@ +import{ag as _,ah as b,ai as k}from"./index-Cr5N_0pd.js";import{e as S}from"./index-Cl4M8jG7.js";function v(n,i){for(var c=0;ce[r]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}var w={},m={};const H=_(S);var p={};Object.defineProperty(p,"__esModule",{value:!0});p.numberToHex=p.getLowerCase=void 0;function y(n){return n&&n.toLowerCase()}p.getLowerCase=y;function C(n){return`0x${n.toString(16)}`}p.numberToHex=C;Object.defineProperty(m,"__esModule",{value:!0});m.SafeAppProvider=void 0;const f=H,A=b,o=p;class I extends A.EventEmitter{constructor(i,c){super(),this.submittedTxs=new Map,this.safe=i,this.sdk=c}async connect(){this.emit("connect",{chainId:this.chainId})}async disconnect(){}get chainId(){return this.safe.chainId}async request(i){const{method:c,params:e=[]}=i;switch(c){case"eth_accounts":return[this.safe.safeAddress];case"net_version":case"eth_chainId":return(0,o.numberToHex)(this.chainId);case"personal_sign":{const[t,s]=e;if(this.safe.safeAddress.toLowerCase()!==s.toLowerCase())throw new Error("The address or message hash is invalid");const a=await this.sdk.txs.signMessage(t);return("signature"in a?a.signature:void 0)||"0x"}case"eth_sign":{const[t,s]=e;if(this.safe.safeAddress.toLowerCase()!==t.toLowerCase()||!s.startsWith("0x"))throw new Error("The address or message hash is invalid");const a=await this.sdk.txs.signMessage(s);return("signature"in a?a.signature:void 0)||"0x"}case"eth_signTypedData":case"eth_signTypedData_v4":{const[t,s]=e,a=typeof s=="string"?JSON.parse(s):s;if(this.safe.safeAddress.toLowerCase()!==t.toLowerCase())throw new Error("The address is invalid");const d=await this.sdk.txs.signTypedMessage(a);return("signature"in d?d.signature:void 0)||"0x"}case"eth_sendTransaction":const r={...e[0],value:e[0].value||"0",data:e[0].data||"0x"};typeof r.gas=="string"&&r.gas.startsWith("0x")&&(r.gas=parseInt(r.gas,16));const u=await this.sdk.txs.send({txs:[r],params:{safeTxGas:r.gas}});return this.submittedTxs.set(u.safeTxHash,{from:this.safe.safeAddress,hash:u.safeTxHash,gas:0,gasPrice:"0x00",nonce:0,input:r.data,value:r.value,to:r.to,blockHash:null,blockNumber:null,transactionIndex:null}),u.safeTxHash;case"eth_blockNumber":return(await this.sdk.eth.getBlockByNumber(["latest"])).number;case"eth_getBalance":return this.sdk.eth.getBalance([(0,o.getLowerCase)(e[0]),e[1]]);case"eth_getCode":return this.sdk.eth.getCode([(0,o.getLowerCase)(e[0]),e[1]]);case"eth_getTransactionCount":return this.sdk.eth.getTransactionCount([(0,o.getLowerCase)(e[0]),e[1]]);case"eth_getStorageAt":return this.sdk.eth.getStorageAt([(0,o.getLowerCase)(e[0]),e[1],e[2]]);case"eth_getBlockByNumber":return this.sdk.eth.getBlockByNumber([e[0],e[1]]);case"eth_getBlockByHash":return this.sdk.eth.getBlockByHash([e[0],e[1]]);case"eth_getTransactionByHash":let g=e[0];try{g=(await this.sdk.txs.getBySafeTxHash(g)).txHash||g}catch{}return this.submittedTxs.has(g)?this.submittedTxs.get(g):this.sdk.eth.getTransactionByHash([g]).then(t=>(t&&(t.hash=e[0]),t));case"eth_getTransactionReceipt":{let t=e[0];try{t=(await this.sdk.txs.getBySafeTxHash(t)).txHash||t}catch{}return this.sdk.eth.getTransactionReceipt([t]).then(s=>(s&&(s.transactionHash=e[0]),s))}case"eth_estimateGas":return this.sdk.eth.getEstimateGas(e[0]);case"eth_call":return this.sdk.eth.call([e[0],e[1]]);case"eth_getLogs":return this.sdk.eth.getPastLogs([e[0]]);case"eth_gasPrice":return this.sdk.eth.getGasPrice();case"wallet_getPermissions":return this.sdk.wallet.getPermissions();case"wallet_requestPermissions":return this.sdk.wallet.requestPermissions(e[0]);case"safe_setSettings":return this.sdk.eth.setSafeSettings([e[0]]);case"wallet_sendCalls":{const{from:t,calls:s,chainId:a}=e[0];if(a!==(0,o.numberToHex)(this.chainId))throw new Error(`Safe is not on chain ${a}`);if(t!==this.safe.safeAddress)throw Error("Invalid from address");const d=s.map((l,x)=>{if(!l.to)throw new Error(`Invalid call #${x}: missing "to" field`);return{to:l.to,data:l.data??"0x",value:l.value??(0,o.numberToHex)(0)}}),{safeTxHash:h}=await this.sdk.txs.send({txs:d});return{id:h}}case"wallet_getCallsStatus":{const t=e[0],s={[f.TransactionStatus.AWAITING_CONFIRMATIONS]:100,[f.TransactionStatus.AWAITING_EXECUTION]:100,[f.TransactionStatus.SUCCESS]:200,[f.TransactionStatus.CANCELLED]:400,[f.TransactionStatus.FAILED]:500},a=await this.sdk.txs.getBySafeTxHash(t),d={version:"1.0",id:t,chainId:(0,o.numberToHex)(this.chainId),status:s[a.txStatus]};if(!a.txHash)return d;const h=await this.sdk.eth.getTransactionReceipt([a.txHash]);if(!h)return d;const T=a.txData?.dataDecoded?.method!=="multiSend"?1:a.txData.dataDecoded.parameters?.[0].valueDecoded?.length??1,l=Number(h.blockNumber),x=Number(h.gasUsed);return d.receipts=Array(T).fill({logs:h.logs,status:(0,o.numberToHex)(a.txStatus===f.TransactionStatus.SUCCESS?1:0),blockHash:h.blockHash,blockNumber:(0,o.numberToHex)(l),gasUsed:(0,o.numberToHex)(x),transactionHash:a.txHash}),d}case"wallet_showCallsStatus":throw new Error(`"${i.method}" not supported`);case"wallet_getCapabilities":return{[(0,o.numberToHex)(this.chainId)]:{atomicBatch:{supported:!0}}};default:throw Error(`"${i.method}" not implemented`)}}send(i,c){i||c("Undefined request"),this.request(i).then(e=>c(null,{jsonrpc:"2.0",id:i.id,result:e})).catch(e=>c(e,null))}}m.SafeAppProvider=I;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.SafeAppProvider=void 0;var i=m;Object.defineProperty(n,"SafeAppProvider",{enumerable:!0,get:function(){return i.SafeAppProvider}})})(w);const P=k(w),B=v({__proto__:null,default:P},[w]);export{B as i}; diff --git a/dist/assets/info-BzF0mPAp.js b/dist/assets/info-BzF0mPAp.js new file mode 100644 index 0000000..d1165d2 --- /dev/null +++ b/dist/assets/info-BzF0mPAp.js @@ -0,0 +1,3 @@ +import{b as C}from"./index-Cr5N_0pd.js";const t=C` + +`;export{t as infoSvg}; diff --git a/dist/assets/info-circle-CXT71X33.js b/dist/assets/info-circle-CXT71X33.js new file mode 100644 index 0000000..850d244 --- /dev/null +++ b/dist/assets/info-circle-CXT71X33.js @@ -0,0 +1,12 @@ +import{b as l}from"./index-Cr5N_0pd.js";const e=l` + + +`;export{e as infoCircleSvg}; diff --git a/dist/assets/lightbulb-DXUATdFd.js b/dist/assets/lightbulb-DXUATdFd.js new file mode 100644 index 0000000..f6b2c33 --- /dev/null +++ b/dist/assets/lightbulb-DXUATdFd.js @@ -0,0 +1,3 @@ +import{b as C}from"./index-Cr5N_0pd.js";const e=C` + +`;export{e as lightbulbSvg}; diff --git a/dist/assets/mail-D5Kz7lp0.js b/dist/assets/mail-D5Kz7lp0.js new file mode 100644 index 0000000..a57610b --- /dev/null +++ b/dist/assets/mail-D5Kz7lp0.js @@ -0,0 +1,8 @@ +import{b as c}from"./index-Cr5N_0pd.js";const e=c` + +`;export{e as mailSvg}; diff --git a/dist/assets/mobile-iSKvjbUf.js b/dist/assets/mobile-iSKvjbUf.js new file mode 100644 index 0000000..a8a9379 --- /dev/null +++ b/dist/assets/mobile-iSKvjbUf.js @@ -0,0 +1,9 @@ +import{b as l}from"./index-Cr5N_0pd.js";const e=l` + + +`;export{e as mobileSvg}; diff --git a/dist/assets/more-C8OTKC0g.js b/dist/assets/more-C8OTKC0g.js new file mode 100644 index 0000000..a63e5f1 --- /dev/null +++ b/dist/assets/more-C8OTKC0g.js @@ -0,0 +1,11 @@ +import{b as l}from"./index-Cr5N_0pd.js";const a=l` + + +`;export{a as moreSvg}; diff --git a/dist/assets/network-placeholder-C3ZqCyor.js b/dist/assets/network-placeholder-C3ZqCyor.js new file mode 100644 index 0000000..0f192f7 --- /dev/null +++ b/dist/assets/network-placeholder-C3ZqCyor.js @@ -0,0 +1,14 @@ +import{b as l}from"./index-Cr5N_0pd.js";const e=l` + + +`;export{e as networkPlaceholderSvg}; diff --git a/dist/assets/nftPlaceholder-1Liwzove.js b/dist/assets/nftPlaceholder-1Liwzove.js new file mode 100644 index 0000000..5d75edf --- /dev/null +++ b/dist/assets/nftPlaceholder-1Liwzove.js @@ -0,0 +1,8 @@ +import{b as c}from"./index-Cr5N_0pd.js";const a=c` + +`;export{a as nftPlaceholderSvg}; diff --git a/dist/assets/off-DkfF0_gL.js b/dist/assets/off-DkfF0_gL.js new file mode 100644 index 0000000..572a2c4 --- /dev/null +++ b/dist/assets/off-DkfF0_gL.js @@ -0,0 +1,4 @@ +import{b as C}from"./index-Cr5N_0pd.js";const l=C` + + +`;export{l as offSvg}; diff --git a/dist/assets/onramp-BiRdNRiA.js b/dist/assets/onramp-BiRdNRiA.js new file mode 100644 index 0000000..3bce6c4 --- /dev/null +++ b/dist/assets/onramp-BiRdNRiA.js @@ -0,0 +1,468 @@ +import{i as P,a as y,aG as l,aH as $,am as j,aj as _,x as u,a9 as h,ap as C,aa as c,c as b,a5 as p,K as I,a6 as M,a0 as E,a1 as z,a2 as N,T as W,L as U,$ as q,a8 as F,R as B}from"./index-Cr5N_0pd.js";const K=P` + :host > wui-grid { + max-height: 360px; + overflow: auto; + } + + wui-flex { + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + } + + wui-grid::-webkit-scrollbar { + display: none; + } + + wui-flex.disabled { + opacity: 0.3; + pointer-events: none; + user-select: none; + } +`;var A=function(s,e,i,r){var n=arguments.length,t=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(s,e,i,r);else for(var a=s.length-1;a>=0;a--)(o=s[a])&&(t=(n<3?o(t):n>3?o(e,i,t):o(e,i))||t);return n>3&&t&&Object.defineProperty(e,i,t),t};let k=class extends y{constructor(){super(),this.unsubscribe=[],this.selectedCurrency=l.state.paymentCurrency,this.currencies=l.state.paymentCurrencies,this.currencyImages=$.state.currencyImages,this.checked=j.state.isLegalCheckboxChecked,this.unsubscribe.push(l.subscribe(e=>{this.selectedCurrency=e.paymentCurrency,this.currencies=e.paymentCurrencies}),$.subscribeKey("currencyImages",e=>this.currencyImages=e),j.subscribeKey("isLegalCheckboxChecked",e=>{this.checked=e}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const{termsConditionsUrl:e,privacyPolicyUrl:i}=_.state,r=_.state.features?.legalCheckbox,o=!!(e||i)&&!!r&&!this.checked;return u` + + + ${this.currenciesTemplate(o)} + + + `}currenciesTemplate(e=!1){return this.currencies.map(i=>u` + this.selectCurrency(i)} + variant="image" + tabIdx=${h(e?-1:void 0)} + > + ${i.id} + + `)}selectCurrency(e){e&&(l.setPaymentCurrency(e),C.close())}};k.styles=K;A([c()],k.prototype,"selectedCurrency",void 0);A([c()],k.prototype,"currencies",void 0);A([c()],k.prototype,"currencyImages",void 0);A([c()],k.prototype,"checked",void 0);k=A([b("w3m-onramp-fiat-select-view")],k);const Y=P` + button { + padding: var(--wui-spacing-s); + border-radius: var(--wui-border-radius-xs); + border: none; + outline: none; + background-color: var(--wui-color-gray-glass-002); + width: 100%; + display: flex; + align-items: center; + justify-content: flex-start; + gap: var(--wui-spacing-s); + transition: background-color var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: background-color; + } + + button:hover { + background-color: var(--wui-color-gray-glass-005); + } + + .provider-image { + width: var(--wui-spacing-3xl); + min-width: var(--wui-spacing-3xl); + height: var(--wui-spacing-3xl); + border-radius: calc(var(--wui-border-radius-xs) - calc(var(--wui-spacing-s) / 2)); + position: relative; + overflow: hidden; + } + + .provider-image::after { + content: ''; + display: block; + width: 100%; + height: 100%; + position: absolute; + inset: 0; + border-radius: calc(var(--wui-border-radius-xs) - calc(var(--wui-spacing-s) / 2)); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-005); + } + + .network-icon { + width: var(--wui-spacing-m); + height: var(--wui-spacing-m); + border-radius: calc(var(--wui-spacing-m) / 2); + overflow: hidden; + box-shadow: + 0 0 0 3px var(--wui-color-gray-glass-002), + 0 0 0 3px var(--wui-color-modal-bg); + transition: box-shadow var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: box-shadow; + } + + button:hover .network-icon { + box-shadow: + 0 0 0 3px var(--wui-color-gray-glass-005), + 0 0 0 3px var(--wui-color-modal-bg); + } +`;var v=function(s,e,i,r){var n=arguments.length,t=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(s,e,i,r);else for(var a=s.length-1;a>=0;a--)(o=s[a])&&(t=(n<3?o(t):n>3?o(e,i,t):o(e,i))||t);return n>3&&t&&Object.defineProperty(e,i,t),t};let m=class extends y{constructor(){super(...arguments),this.disabled=!1,this.color="inherit",this.label="",this.feeRange="",this.loading=!1,this.onClick=null}render(){return u` + + `}networksTemplate(){const i=I.getAllRequestedCaipNetworks()?.filter(r=>r?.assets?.imageId)?.slice(0,5);return u` + + ${i?.map(r=>u` + + + + `)} + + `}};m.styles=[Y];v([p({type:Boolean})],m.prototype,"disabled",void 0);v([p()],m.prototype,"color",void 0);v([p()],m.prototype,"name",void 0);v([p()],m.prototype,"label",void 0);v([p()],m.prototype,"feeRange",void 0);v([p({type:Boolean})],m.prototype,"loading",void 0);v([p()],m.prototype,"onClick",void 0);m=v([b("w3m-onramp-provider-item")],m);const H=P` + wui-flex { + border-top: 1px solid var(--wui-color-gray-glass-005); + } + + a { + text-decoration: none; + color: var(--wui-color-fg-175); + font-weight: 500; + display: flex; + align-items: center; + justify-content: center; + gap: var(--wui-spacing-3xs); + } +`;var Q=function(s,e,i,r){var n=arguments.length,t=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(s,e,i,r);else for(var a=s.length-1;a>=0;a--)(o=s[a])&&(t=(n<3?o(t):n>3?o(e,i,t):o(e,i))||t);return n>3&&t&&Object.defineProperty(e,i,t),t};let L=class extends y{render(){const{termsConditionsUrl:e,privacyPolicyUrl:i}=_.state;return!e&&!i?null:u` + + + We work with the best providers to give you the lowest fees and best support. More options + coming soon! + + + ${this.howDoesItWorkTemplate()} + + `}howDoesItWorkTemplate(){return u` + + How does it work? + `}onWhatIsBuy(){E.sendEvent({type:"track",event:"SELECT_WHAT_IS_A_BUY",properties:{isSmartAccount:z(I.state.activeChain)===N.ACCOUNT_TYPES.SMART_ACCOUNT}}),W.push("WhatIsABuy")}};L.styles=[H];L=Q([b("w3m-onramp-providers-footer")],L);var V=function(s,e,i,r){var n=arguments.length,t=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(s,e,i,r);else for(var a=s.length-1;a>=0;a--)(o=s[a])&&(t=(n<3?o(t):n>3?o(e,i,t):o(e,i))||t);return n>3&&t&&Object.defineProperty(e,i,t),t};let S=class extends y{constructor(){super(),this.unsubscribe=[],this.providers=l.state.providers,this.unsubscribe.push(l.subscribeKey("providers",e=>{this.providers=e}))}render(){return u` + + ${this.onRampProvidersTemplate()} + + + `}onRampProvidersTemplate(){return this.providers.filter(e=>e.supportedChains.includes(I.state.activeChain??"eip155")).map(e=>u` + {this.onClickProvider(e)}} + ?disabled=${!e.url} + data-testid=${`onramp-provider-${e.name}`} + > + `)}onClickProvider(e){l.setSelectedProvider(e),W.push("BuyInProgress"),U.openHref(l.state.selectedProvider?.url||e.url,"popupWindow","width=600,height=800,scrollbars=yes"),E.sendEvent({type:"track",event:"SELECT_BUY_PROVIDER",properties:{provider:e.name,isSmartAccount:z(I.state.activeChain)===N.ACCOUNT_TYPES.SMART_ACCOUNT}})}};V([c()],S.prototype,"providers",void 0);S=V([b("w3m-onramp-providers-view")],S);const X=P` + :host > wui-grid { + max-height: 360px; + overflow: auto; + } + + wui-flex { + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + } + + wui-grid::-webkit-scrollbar { + display: none; + } + + wui-flex.disabled { + opacity: 0.3; + pointer-events: none; + user-select: none; + } +`;var T=function(s,e,i,r){var n=arguments.length,t=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(s,e,i,r);else for(var a=s.length-1;a>=0;a--)(o=s[a])&&(t=(n<3?o(t):n>3?o(e,i,t):o(e,i))||t);return n>3&&t&&Object.defineProperty(e,i,t),t};let R=class extends y{constructor(){super(),this.unsubscribe=[],this.selectedCurrency=l.state.purchaseCurrencies,this.tokens=l.state.purchaseCurrencies,this.tokenImages=$.state.tokenImages,this.checked=j.state.isLegalCheckboxChecked,this.unsubscribe.push(l.subscribe(e=>{this.selectedCurrency=e.purchaseCurrencies,this.tokens=e.purchaseCurrencies}),$.subscribeKey("tokenImages",e=>this.tokenImages=e),j.subscribeKey("isLegalCheckboxChecked",e=>{this.checked=e}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const{termsConditionsUrl:e,privacyPolicyUrl:i}=_.state,r=_.state.features?.legalCheckbox,o=!!(e||i)&&!!r&&!this.checked;return u` + + + ${this.currenciesTemplate(o)} + + + `}currenciesTemplate(e=!1){return this.tokens.map(i=>u` + this.selectToken(i)} + variant="image" + tabIdx=${h(e?-1:void 0)} + > + + ${i.name} + ${i.symbol} + + + `)}selectToken(e){e&&(l.setPurchaseCurrency(e),C.close())}};R.styles=X;T([c()],R.prototype,"selectedCurrency",void 0);T([c()],R.prototype,"tokens",void 0);T([c()],R.prototype,"tokenImages",void 0);T([c()],R.prototype,"checked",void 0);R=T([b("w3m-onramp-token-select-view")],R);const G=P` + @keyframes shake { + 0% { + transform: translateX(0); + } + 25% { + transform: translateX(3px); + } + 50% { + transform: translateX(-3px); + } + 75% { + transform: translateX(3px); + } + 100% { + transform: translateX(0); + } + } + + wui-flex:first-child:not(:only-child) { + position: relative; + } + + wui-loading-thumbnail { + position: absolute; + } + + wui-visual { + width: var(--wui-wallet-image-size-lg); + height: var(--wui-wallet-image-size-lg); + border-radius: calc(var(--wui-border-radius-5xs) * 9 - var(--wui-border-radius-xxs)); + position: relative; + overflow: hidden; + } + + wui-visual::after { + content: ''; + display: block; + width: 100%; + height: 100%; + position: absolute; + inset: 0; + border-radius: calc(var(--wui-border-radius-5xs) * 9 - var(--wui-border-radius-xxs)); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-005); + } + + wui-icon-box { + position: absolute; + right: calc(var(--wui-spacing-3xs) * -1); + bottom: calc(var(--wui-spacing-3xs) * -1); + opacity: 0; + transform: scale(0.5); + transition: + opacity var(--wui-ease-out-power-2) var(--wui-duration-lg), + transform var(--wui-ease-out-power-2) var(--wui-duration-lg); + will-change: opacity, transform; + } + + wui-text[align='center'] { + width: 100%; + padding: 0px var(--wui-spacing-l); + } + + [data-error='true'] wui-icon-box { + opacity: 1; + transform: scale(1); + } + + [data-error='true'] > wui-flex:first-child { + animation: shake 250ms cubic-bezier(0.36, 0.07, 0.19, 0.97) both; + } + + [data-retry='false'] wui-link { + display: none; + } + + [data-retry='true'] wui-link { + display: block; + opacity: 1; + } + + wui-link { + padding: var(--wui-spacing-4xs) var(--wui-spacing-xxs); + } +`;var f=function(s,e,i,r){var n=arguments.length,t=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(s,e,i,r);else for(var a=s.length-1;a>=0;a--)(o=s[a])&&(t=(n<3?o(t):n>3?o(e,i,t):o(e,i))||t);return n>3&&t&&Object.defineProperty(e,i,t),t};let d=class extends y{constructor(){super(),this.unsubscribe=[],this.selectedOnRampProvider=l.state.selectedProvider,this.uri=q.state.wcUri,this.ready=!1,this.showRetry=!1,this.buffering=!1,this.error=!1,this.isMobile=!1,this.onRetry=void 0,this.unsubscribe.push(l.subscribeKey("selectedProvider",e=>{this.selectedOnRampProvider=e}))}disconnectedCallback(){this.intervalId&&clearInterval(this.intervalId)}render(){let e="Continue in external window";this.error?e="Buy failed":this.selectedOnRampProvider&&(e=`Buy in ${this.selectedOnRampProvider?.label}`);const i=this.error?"Buy can be declined from your side or due to and error on the provider app":"We’ll notify you once your Buy is processed";return u` + + + + + + ${this.error?null:this.loaderTemplate()} + + + + + + + ${e} + + ${i} + + + ${this.error?this.tryAgainTemplate():null} + + + + + + Copy link + + + `}onTryAgain(){this.selectedOnRampProvider&&(this.error=!1,U.openHref(this.selectedOnRampProvider.url,"popupWindow","width=600,height=800,scrollbars=yes"))}tryAgainTemplate(){return this.selectedOnRampProvider?.url?u` + + Try again + `:null}loaderTemplate(){const e=F.state.themeVariables["--w3m-border-radius-master"],i=e?parseInt(e.replace("px",""),10):4;return u``}onCopyUri(){if(!this.selectedOnRampProvider?.url){B.showError("No link found"),W.goBack();return}try{U.copyToClopboard(this.selectedOnRampProvider.url),B.showSuccess("Link copied")}catch{B.showError("Failed to copy")}}};d.styles=G;f([c()],d.prototype,"intervalId",void 0);f([c()],d.prototype,"selectedOnRampProvider",void 0);f([c()],d.prototype,"uri",void 0);f([c()],d.prototype,"ready",void 0);f([c()],d.prototype,"showRetry",void 0);f([c()],d.prototype,"buffering",void 0);f([c()],d.prototype,"error",void 0);f([p({type:Boolean})],d.prototype,"isMobile",void 0);f([p()],d.prototype,"onRetry",void 0);d=f([b("w3m-buy-in-progress-view")],d);var J=function(s,e,i,r){var n=arguments.length,t=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(s,e,i,r);else for(var a=s.length-1;a>=0;a--)(o=s[a])&&(t=(n<3?o(t):n>3?o(e,i,t):o(e,i))||t);return n>3&&t&&Object.defineProperty(e,i,t),t};let D=class extends y{render(){return u` + + + + + Quickly and easily buy digital assets! + + + Simply select your preferred onramp provider and add digital assets to your account + using your credit card or bank transfer + + + + + Buy + + + `}};D=J([b("w3m-what-is-a-buy-view")],D);const Z=P` + :host { + width: 100%; + } + + wui-loading-spinner { + position: absolute; + top: 50%; + right: 20px; + transform: translateY(-50%); + } + + .currency-container { + position: absolute; + top: 50%; + transform: translateY(-50%); + right: var(--wui-spacing-1xs); + height: 40px; + padding: var(--wui-spacing-xs) var(--wui-spacing-1xs) var(--wui-spacing-xs) + var(--wui-spacing-xs); + min-width: 95px; + border-radius: var(--FULL, 1000px); + border: 1px solid var(--wui-color-gray-glass-002); + background: var(--wui-color-gray-glass-002); + cursor: pointer; + } + + .currency-container > wui-image { + height: 24px; + width: 24px; + border-radius: 50%; + } +`;var O=function(s,e,i,r){var n=arguments.length,t=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(s,e,i,r);else for(var a=s.length-1;a>=0;a--)(o=s[a])&&(t=(n<3?o(t):n>3?o(e,i,t):o(e,i))||t);return n>3&&t&&Object.defineProperty(e,i,t),t};let g=class extends y{constructor(){super(),this.unsubscribe=[],this.type="Token",this.value=0,this.currencies=[],this.selectedCurrency=this.currencies?.[0],this.currencyImages=$.state.currencyImages,this.tokenImages=$.state.tokenImages,this.unsubscribe.push(l.subscribeKey("purchaseCurrency",e=>{!e||this.type==="Fiat"||(this.selectedCurrency=this.formatPurchaseCurrency(e))}),l.subscribeKey("paymentCurrency",e=>{!e||this.type==="Token"||(this.selectedCurrency=this.formatPaymentCurrency(e))}),l.subscribe(e=>{this.type==="Fiat"?this.currencies=e.purchaseCurrencies.map(this.formatPurchaseCurrency):this.currencies=e.paymentCurrencies.map(this.formatPaymentCurrency)}),$.subscribe(e=>{this.currencyImages={...e.currencyImages},this.tokenImages={...e.tokenImages}}))}firstUpdated(){l.getAvailableCurrencies()}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const e=this.selectedCurrency?.symbol||"",i=this.currencyImages[e]||this.tokenImages[e];return u` + ${this.selectedCurrency?u` C.open({view:`OnRamp${this.type}Select`})} + > + + ${this.selectedCurrency.symbol} + `:u``} + `}formatPaymentCurrency(e){return{name:e.id,symbol:e.id}}formatPurchaseCurrency(e){return{name:e.name,symbol:e.symbol}}};g.styles=Z;O([p({type:String})],g.prototype,"type",void 0);O([p({type:Number})],g.prototype,"value",void 0);O([c()],g.prototype,"currencies",void 0);O([c()],g.prototype,"selectedCurrency",void 0);O([c()],g.prototype,"currencyImages",void 0);O([c()],g.prototype,"tokenImages",void 0);g=O([b("w3m-onramp-input")],g);const ee=P` + :host > wui-flex { + width: 100%; + max-width: 360px; + } + + :host > wui-flex > wui-flex { + border-radius: var(--wui-border-radius-l); + width: 100%; + } + + .amounts-container { + width: 100%; + } +`;var x=function(s,e,i,r){var n=arguments.length,t=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(s,e,i,r);else for(var a=s.length-1;a>=0;a--)(o=s[a])&&(t=(n<3?o(t):n>3?o(e,i,t):o(e,i))||t);return n>3&&t&&Object.defineProperty(e,i,t),t};const te={USD:"$",EUR:"€",GBP:"£"},ie=[100,250,500,1e3];let w=class extends y{constructor(){super(),this.unsubscribe=[],this.disabled=!1,this.caipAddress=I.state.activeCaipAddress,this.loading=C.state.loading,this.paymentCurrency=l.state.paymentCurrency,this.paymentAmount=l.state.paymentAmount,this.purchaseAmount=l.state.purchaseAmount,this.quoteLoading=l.state.quotesLoading,this.unsubscribe.push(I.subscribeKey("activeCaipAddress",e=>this.caipAddress=e),C.subscribeKey("loading",e=>{this.loading=e}),l.subscribe(e=>{this.paymentCurrency=e.paymentCurrency,this.paymentAmount=e.paymentAmount,this.purchaseAmount=e.purchaseAmount,this.quoteLoading=e.quotesLoading}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return u` + + + + + + ${ie.map(e=>u`this.selectPresetAmount(e)} + >${`${te[this.paymentCurrency?.id||"USD"]} ${e}`}`)} + + ${this.templateButton()} + + + `}templateButton(){return this.caipAddress?u` + Get quotes + `:u` + Connect wallet + `}getQuotes(){this.loading||C.open({view:"OnRampProviders"})}openModal(){C.open({view:"Connect"})}async onPaymentAmountChange(e){l.setPaymentAmount(Number(e.detail)),await l.getQuote()}async selectPresetAmount(e){l.setPaymentAmount(e),await l.getQuote()}};w.styles=ee;x([p({type:Boolean})],w.prototype,"disabled",void 0);x([c()],w.prototype,"caipAddress",void 0);x([c()],w.prototype,"loading",void 0);x([c()],w.prototype,"paymentCurrency",void 0);x([c()],w.prototype,"paymentAmount",void 0);x([c()],w.prototype,"purchaseAmount",void 0);x([c()],w.prototype,"quoteLoading",void 0);w=x([b("w3m-onramp-widget")],w);export{d as W3mBuyInProgressView,S as W3mOnRampProvidersView,k as W3mOnrampFiatSelectView,R as W3mOnrampTokensView,w as W3mOnrampWidget,D as W3mWhatIsABuyView}; diff --git a/dist/assets/play-store-D-_ekw15.js b/dist/assets/play-store-D-_ekw15.js new file mode 100644 index 0000000..92d51bf --- /dev/null +++ b/dist/assets/play-store-D-_ekw15.js @@ -0,0 +1,32 @@ +import{b as a}from"./index-Cr5N_0pd.js";const t=a` + + + + + + +`;export{t as playStoreSvg}; diff --git a/dist/assets/plus-DaZ9pOJ-.js b/dist/assets/plus-DaZ9pOJ-.js new file mode 100644 index 0000000..abc33f1 --- /dev/null +++ b/dist/assets/plus-DaZ9pOJ-.js @@ -0,0 +1,13 @@ +import{b as e}from"./index-Cr5N_0pd.js";const o=e` + `;export{o as plusSvg}; diff --git a/dist/assets/qr-code-zSuzYj6q.js b/dist/assets/qr-code-zSuzYj6q.js new file mode 100644 index 0000000..70527a2 --- /dev/null +++ b/dist/assets/qr-code-zSuzYj6q.js @@ -0,0 +1,6 @@ +import{b as a}from"./index-Cr5N_0pd.js";const o=a` + +`;export{o as qrCodeIcon}; diff --git a/dist/assets/receive-dL28-83Q.js b/dist/assets/receive-dL28-83Q.js new file mode 100644 index 0000000..5d6bf2d --- /dev/null +++ b/dist/assets/receive-dL28-83Q.js @@ -0,0 +1,83 @@ +import{i as b,a3 as y,a4 as C,a5 as v,c as x,a as N,x as c,Y as p,K as u,R as m,a6 as h,a7 as $,a8 as k,a9 as R,a1 as I,a2 as A,T,L as S,aa as f}from"./index-Cr5N_0pd.js";const O=b` + button { + display: flex; + gap: var(--wui-spacing-xl); + width: 100%; + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xxs); + padding: var(--wui-spacing-m) var(--wui-spacing-s); + } + + wui-text { + width: 100%; + } + + wui-flex { + width: auto; + } + + .network-icon { + width: var(--wui-spacing-2l); + height: var(--wui-spacing-2l); + border-radius: calc(var(--wui-spacing-2l) / 2); + overflow: hidden; + box-shadow: + 0 0 0 3px var(--wui-color-gray-glass-002), + 0 0 0 3px var(--wui-color-modal-bg); + } +`;var g=function(n,e,i,r){var o=arguments.length,t=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(n,e,i,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(t=(o<3?s(t):o>3?s(e,i,t):s(e,i))||t);return o>3&&t&&Object.defineProperty(e,i,t),t};let w=class extends N{constructor(){super(...arguments),this.networkImages=[""],this.text=""}render(){return c` + + `}networksTemplate(){const e=this.networkImages.slice(0,5);return c` + ${e?.map(i=>c` `)} + `}};w.styles=[y,C,O];g([v({type:Array})],w.prototype,"networkImages",void 0);g([v()],w.prototype,"text",void 0);w=g([x("wui-compatible-network")],w);const _=b` + wui-compatible-network { + margin-top: var(--wui-spacing-l); + } +`;var d=function(n,e,i,r){var o=arguments.length,t=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(n,e,i,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(t=(o<3?s(t):o>3?s(e,i,t):s(e,i))||t);return o>3&&t&&Object.defineProperty(e,i,t),t};let l=class extends N{constructor(){super(),this.unsubscribe=[],this.address=p.state.address,this.profileName=p.state.profileName,this.network=u.state.activeCaipNetwork,this.unsubscribe.push(p.subscribe(e=>{e.address?(this.address=e.address,this.profileName=e.profileName):m.showError("Account not found")}),u.subscribeKey("activeCaipNetwork",e=>{e?.id&&(this.network=e)}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){if(!this.address)throw new Error("w3m-wallet-receive-view: No account provided");const e=h.getNetworkImage(this.network);return c` + + + + + Copy your address or scan this QR code + + + ${this.networkTemplate()} + `}networkTemplate(){const e=u.getAllRequestedCaipNetworks(),i=u.checkIfSmartAccountEnabled(),r=u.state.activeCaipNetwork,o=e.filter(a=>a?.chainNamespace===r?.chainNamespace);if(I(r?.chainNamespace)===A.ACCOUNT_TYPES.SMART_ACCOUNT&&i)return r?c``:null;const s=(o?.filter(a=>a?.assets?.imageId)?.slice(0,5)).map(h.getNetworkImage).filter(Boolean);return c``}onReceiveClick(){T.push("WalletCompatibleNetworks")}onCopyClick(){try{this.address&&(S.copyToClopboard(this.address),m.showSuccess("Address copied"))}catch{m.showError("Failed to copy")}}};l.styles=_;d([f()],l.prototype,"address",void 0);d([f()],l.prototype,"profileName",void 0);d([f()],l.prototype,"network",void 0);l=d([x("w3m-wallet-receive-view")],l);export{l as W3mWalletReceiveView}; diff --git a/dist/assets/recycle-horizontal-B85mmaoN.js b/dist/assets/recycle-horizontal-B85mmaoN.js new file mode 100644 index 0000000..e1c297e --- /dev/null +++ b/dist/assets/recycle-horizontal-B85mmaoN.js @@ -0,0 +1,9 @@ +import{b as C}from"./index-Cr5N_0pd.js";const o=C` + `;export{o as recycleHorizontalSvg}; diff --git a/dist/assets/refresh-CsELgs90.js b/dist/assets/refresh-CsELgs90.js new file mode 100644 index 0000000..18f5291 --- /dev/null +++ b/dist/assets/refresh-CsELgs90.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + +`;export{o as refreshSvg}; diff --git a/dist/assets/reown-logo-CHoXyyWe.js b/dist/assets/reown-logo-CHoXyyWe.js new file mode 100644 index 0000000..ed3bec6 --- /dev/null +++ b/dist/assets/reown-logo-CHoXyyWe.js @@ -0,0 +1,12 @@ +import{b as C}from"./index-Cr5N_0pd.js";const l=C` + + + + + + + + + + +`;export{l as reownSvg}; diff --git a/dist/assets/search-DCC0JOe_.js b/dist/assets/search-DCC0JOe_.js new file mode 100644 index 0000000..fe0d31a --- /dev/null +++ b/dist/assets/search-DCC0JOe_.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + +`;export{o as searchSvg}; diff --git a/dist/assets/secp256k1-BjJYwyg8.js b/dist/assets/secp256k1-BjJYwyg8.js new file mode 100644 index 0000000..f11b509 --- /dev/null +++ b/dist/assets/secp256k1-BjJYwyg8.js @@ -0,0 +1 @@ +import{ab as ce,ac as ae,ad as le,ae as ue,af as de}from"./index-Cr5N_0pd.js";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const zt=BigInt(0),It=BigInt(1);function lt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Tt(e){if(!lt(e))throw new Error("Uint8Array expected")}function ct(e,n){if(typeof n!="boolean")throw new Error(e+" boolean expected, got "+n)}function dt(e){const n=e.toString(16);return n.length&1?"0"+n:n}function $t(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?zt:BigInt("0x"+e)}const Wt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",he=Array.from({length:256},(e,n)=>n.toString(16).padStart(2,"0"));function at(e){if(Tt(e),Wt)return e.toHex();let n="";for(let t=0;t=D._0&&e<=D._9)return e-D._0;if(e>=D.A&&e<=D.F)return e-(D.A-10);if(e>=D.a&&e<=D.f)return e-(D.a-10)}function ht(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(Wt)return Uint8Array.fromHex(e);const n=e.length,t=n/2;if(n%2)throw new Error("hex string expected, got unpadded hex of length "+n);const r=new Uint8Array(t);for(let i=0,s=0;itypeof e=="bigint"&&zt<=e;function Ut(e,n,t){return Et(e)&&Et(n)&&Et(t)&&n<=e&&ezt;e>>=It,n+=1);return n}const gt=e=>(It<new Uint8Array(e),Ct=e=>Uint8Array.from(e);function ge(e,n,t){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof n!="number"||n<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=bt(e),i=bt(e),s=0;const a=()=>{r.fill(1),i.fill(0),s=0},u=(...A)=>t(i,r,...A),o=(A=bt(0))=>{i=u(Ct([0]),A),r=u(),A.length!==0&&(i=u(Ct([1]),A),r=u())},d=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let A=0;const I=[];for(;A{a(),o(A);let z;for(;!(z=I(d()));)o();return a(),z}}const me={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||lt(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,n)=>n.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function mt(e,n,t={}){const r=(i,s,a)=>{const u=me[s];if(typeof u!="function")throw new Error("invalid validator function");const o=e[i];if(!(a&&o===void 0)&&!u(o,e))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+o)};for(const[i,s]of Object.entries(n))r(i,s,!1);for(const[i,s]of Object.entries(t))r(i,s,!0);return e}function Vt(e){const n=new WeakMap;return(t,...r)=>{const i=n.get(t);if(i!==void 0)return i;const s=e(t,...r);return n.set(t,s),s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Y=BigInt(0),V=BigInt(1),tt=BigInt(2),pe=BigInt(3),Xt=BigInt(4),Ft=BigInt(5),Qt=BigInt(8);function M(e,n){const t=e%n;return t>=Y?t:n+t}function j(e,n,t){let r=e;for(;n-- >Y;)r*=r,r%=t;return r}function Ot(e,n){if(e===Y)throw new Error("invert: expected non-zero number");if(n<=Y)throw new Error("invert: expected positive modulus, got "+n);let t=M(e,n),r=n,i=Y,s=V;for(;t!==Y;){const u=r/t,o=r%t,d=i-s*u;r=t,t=o,i=s,s=d}if(r!==V)throw new Error("invert: does not exist");return M(i,n)}function Jt(e,n){const t=(e.ORDER+V)/Xt,r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw new Error("Cannot find square root");return r}function ye(e,n){const t=(e.ORDER-Ft)/Qt,r=e.mul(n,tt),i=e.pow(r,t),s=e.mul(n,i),a=e.mul(e.mul(s,tt),i),u=e.mul(s,e.sub(a,e.ONE));if(!e.eql(e.sqr(u),n))throw new Error("Cannot find square root");return u}function Ee(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Jt;let s=i.pow(r,n);const a=(n+V)/tt;return function(o,d){if(o.is0(d))return d;if(Ht(o,d)!==1)throw new Error("Cannot find square root");let m=t,A=o.mul(o.ONE,s),I=o.pow(d,n),z=o.pow(d,a);for(;!o.eql(I,o.ONE);){if(o.is0(I))return o.ZERO;let T=1,g=o.sqr(I);for(;!o.eql(g,o.ONE);)if(T++,g=o.sqr(g),T===m)throw new Error("Cannot find square root");const k=V<(r[i]="function",r),n);return mt(e,t)}function xe(e,n,t){if(tY;)t&V&&(r=e.mul(r,i)),i=e.sqr(i),t>>=V;return r}function te(e,n,t=!1){const r=new Array(n.length).fill(t?e.ZERO:void 0),i=n.reduce((a,u,o)=>e.is0(u)?a:(r[o]=a,e.mul(a,u)),e.ONE),s=e.inv(i);return n.reduceRight((a,u,o)=>e.is0(u)?a:(r[o]=e.mul(a,r[o]),e.mul(a,u)),s),r}function Ht(e,n){const t=(e.ORDER-V)/tt,r=e.pow(n,t),i=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),a=e.eql(r,e.neg(e.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function ee(e,n){n!==void 0&&ce(n);const t=n!==void 0?n:e.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Lt(e,n,t=!1,r={}){if(e<=Y)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:i,nByteLength:s}=ee(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let a;const u=Object.freeze({ORDER:e,isLE:t,BITS:i,BYTES:s,MASK:gt(i),ZERO:Y,ONE:V,create:o=>M(o,e),isValid:o=>{if(typeof o!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof o);return Y<=o&&oo===Y,isOdd:o=>(o&V)===V,neg:o=>M(-o,e),eql:(o,d)=>o===d,sqr:o=>M(o*o,e),add:(o,d)=>M(o+d,e),sub:(o,d)=>M(o-d,e),mul:(o,d)=>M(o*d,e),pow:(o,d)=>xe(u,o,d),div:(o,d)=>M(o*Ot(d,e),e),sqrN:o=>o*o,addN:(o,d)=>o+d,subN:(o,d)=>o-d,mulN:(o,d)=>o*d,inv:o=>Ot(o,e),sqrt:r.sqrt||(o=>(a||(a=be(e)),a(u,o))),toBytes:o=>t?Gt(o,s):ut(o,s),fromBytes:o=>{if(o.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+o.length);return t?Dt(o):et(o)},invertBatch:o=>te(u,o),cmov:(o,d,m)=>m?d:o});return Object.freeze(u)}function ne(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const n=e.toString(2).length;return Math.ceil(n/8)}function re(e){const n=ne(e);return n+Math.ceil(n/2)}function Se(e,n,t=!1){const r=e.length,i=ne(n),s=re(n);if(r<16||r1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const a=t?Dt(e):et(e),u=M(a,n-V)+V;return t?Gt(u,i):ut(u,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mt=BigInt(0),qt=BigInt(1);function Bt(e,n){const t=n.negate();return e?t:n}function oe(e,n){if(!Number.isSafeInteger(e)||e<=0||e>n)throw new Error("invalid window size, expected [1.."+n+"], got W="+e)}function vt(e,n){oe(e,n);const t=Math.ceil(n/e)+1,r=2**(e-1),i=2**e,s=gt(e),a=BigInt(e);return{windows:t,windowSize:r,mask:s,maxNumber:i,shiftBy:a}}function Yt(e,n,t){const{windowSize:r,mask:i,maxNumber:s,shiftBy:a}=t;let u=Number(e&i),o=e>>a;u>r&&(u-=s,o+=qt);const d=n*r,m=d+Math.abs(u)-1,A=u===0,I=u<0,z=n%2!==0;return{nextN:o,offset:m,isZero:A,isNeg:I,isNegF:z,offsetF:d}}function Ae(e,n){if(!Array.isArray(e))throw new Error("array expected");e.forEach((t,r)=>{if(!(t instanceof n))throw new Error("invalid point at index "+r)})}function Ne(e,n){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((t,r)=>{if(!n.isValid(t))throw new Error("invalid scalar at index "+r)})}const xt=new WeakMap,ie=new WeakMap;function St(e){return ie.get(e)||1}function Ie(e,n){return{constTimeNegate:Bt,hasPrecomputes(t){return St(t)!==1},unsafeLadder(t,r,i=e.ZERO){let s=t;for(;r>Mt;)r&qt&&(i=i.add(s)),s=s.double(),r>>=qt;return i},precomputeWindow(t,r){const{windows:i,windowSize:s}=vt(r,n),a=[];let u=t,o=u;for(let d=0;d12?o=u-3:u>4?o=u-2:u>0&&(o=2);const d=gt(o),m=new Array(Number(d)+1).fill(a),A=Math.floor((n.BITS-1)/o)*o;let I=a;for(let z=A;z>=0;z-=o){m.fill(a);for(let g=0;g>BigInt(z)&d);m[U]=m[U].add(t[g])}let T=a;for(let g=m.length-1,k=a;g>0;g--)k=k.add(m[g]),T=T.add(k);if(I=I.add(T),z!==0)for(let g=0;g{const{Err:t}=G;if(e<0||e>256)throw new t("tlv.encode: wrong tag");if(n.length&1)throw new t("tlv.encode: unpadded data");const r=n.length/2,i=dt(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");const s=r>127?dt(i.length/2|128):"";return dt(e)+s+i+n},decode(e,n){const{Err:t}=G;let r=0;if(e<0||e>256)throw new t("tlv.encode: wrong tag");if(n.length<2||n[r++]!==e)throw new t("tlv.decode: wrong tlv");const i=n[r++],s=!!(i&128);let a=0;if(!s)a=i;else{const o=i&127;if(!o)throw new t("tlv.decode(long): indefinite length not supported");if(o>4)throw new t("tlv.decode(long): byte length is too big");const d=n.subarray(r,r+o);if(d.length!==o)throw new t("tlv.decode: length bytes not complete");if(d[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const m of d)a=a<<8|m;if(r+=o,a<128)throw new t("tlv.decode(long): not minimal encoding")}const u=n.subarray(r,r+a);if(u.length!==a)throw new t("tlv.decode: wrong value length");return{v:u,l:n.subarray(r+a)}}},_int:{encode(e){const{Err:n}=G;if(e{const p=f.toAffine();return wt(Uint8Array.from([4]),t.toBytes(p.x),t.toBytes(p.y))}),s=n.fromBytes||(x=>{const f=x.subarray(1),h=t.fromBytes(f.subarray(0,t.BYTES)),p=t.fromBytes(f.subarray(t.BYTES,2*t.BYTES));return{x:h,y:p}});function a(x){const{a:f,b:h}=n,p=t.sqr(x),B=t.mul(p,x);return t.add(t.add(B,t.mul(x,f)),h)}function u(x,f){const h=t.sqr(f),p=a(x);return t.eql(h,p)}if(!u(n.Gx,n.Gy))throw new Error("bad curve params: generator point");const o=t.mul(t.pow(n.a,Nt),Ze),d=t.mul(t.sqr(n.b),BigInt(27));if(t.is0(t.add(o,d)))throw new Error("bad curve params: a or b");function m(x){return Ut(x,L,n.n)}function A(x){const{allowedPrivateKeyLengths:f,nByteLength:h,wrapPrivateKey:p,n:B}=n;if(f&&typeof x!="bigint"){if(lt(x)&&(x=at(x)),typeof x!="string"||!f.includes(x.length))throw new Error("invalid private key");x=x.padStart(h*2,"0")}let O;try{O=typeof x=="bigint"?x:et(K("private key",x,h))}catch{throw new Error("invalid private key, expected hex or "+h+" bytes, got "+typeof x)}return p&&(O=M(O,B)),it("private key",O,L,B),O}function I(x){if(!(x instanceof g))throw new Error("ProjectivePoint expected")}const z=Vt((x,f)=>{const{px:h,py:p,pz:B}=x;if(t.eql(B,t.ONE))return{x:h,y:p};const O=x.is0();f==null&&(f=O?t.ONE:t.inv(B));const R=t.mul(h,f),q=t.mul(p,f),y=t.mul(B,f);if(O)return{x:t.ZERO,y:t.ZERO};if(!t.eql(y,t.ONE))throw new Error("invZ was invalid");return{x:R,y:q}}),T=Vt(x=>{if(x.is0()){if(n.allowInfinityPoint&&!t.is0(x.py))return;throw new Error("bad point: ZERO")}const{x:f,y:h}=x.toAffine();if(!t.isValid(f)||!t.isValid(h))throw new Error("bad point: x or y not FE");if(!u(f,h))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(f,h,p){if(f==null||!t.isValid(f))throw new Error("x required");if(h==null||!t.isValid(h)||t.is0(h))throw new Error("y required");if(p==null||!t.isValid(p))throw new Error("z required");this.px=f,this.py=h,this.pz=p,Object.freeze(this)}static fromAffine(f){const{x:h,y:p}=f||{};if(!f||!t.isValid(h)||!t.isValid(p))throw new Error("invalid affine point");if(f instanceof g)throw new Error("projective point not allowed");const B=O=>t.eql(O,t.ZERO);return B(h)&&B(p)?g.ZERO:new g(h,p,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const h=te(t,f.map(p=>p.pz));return f.map((p,B)=>p.toAffine(h[B])).map(g.fromAffine)}static fromHex(f){const h=g.fromAffine(s(K("pointHex",f)));return h.assertValidity(),h}static fromPrivateKey(f){return g.BASE.multiply(A(f))}static msm(f,h){return Oe(g,r,f,h)}_setWindowSize(f){$.setWindowSize(this,f)}assertValidity(){T(this)}hasEvenY(){const{y:f}=this.toAffine();if(t.isOdd)return!t.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){I(f);const{px:h,py:p,pz:B}=this,{px:O,py:R,pz:q}=f,y=t.eql(t.mul(h,q),t.mul(O,B)),N=t.eql(t.mul(p,q),t.mul(R,B));return y&&N}negate(){return new g(this.px,t.neg(this.py),this.pz)}double(){const{a:f,b:h}=n,p=t.mul(h,Nt),{px:B,py:O,pz:R}=this;let q=t.ZERO,y=t.ZERO,N=t.ZERO,E=t.mul(B,B),_=t.mul(O,O),l=t.mul(R,R),c=t.mul(B,O);return c=t.add(c,c),N=t.mul(B,R),N=t.add(N,N),q=t.mul(f,N),y=t.mul(p,l),y=t.add(q,y),q=t.sub(_,y),y=t.add(_,y),y=t.mul(q,y),q=t.mul(c,q),N=t.mul(p,N),l=t.mul(f,l),c=t.sub(E,l),c=t.mul(f,c),c=t.add(c,N),N=t.add(E,E),E=t.add(N,E),E=t.add(E,l),E=t.mul(E,c),y=t.add(y,E),l=t.mul(O,R),l=t.add(l,l),E=t.mul(l,c),q=t.sub(q,E),N=t.mul(l,_),N=t.add(N,N),N=t.add(N,N),new g(q,y,N)}add(f){I(f);const{px:h,py:p,pz:B}=this,{px:O,py:R,pz:q}=f;let y=t.ZERO,N=t.ZERO,E=t.ZERO;const _=n.a,l=t.mul(n.b,Nt);let c=t.mul(h,O),w=t.mul(p,R),S=t.mul(B,q),b=t.add(h,p),v=t.add(O,R);b=t.mul(b,v),v=t.add(c,w),b=t.sub(b,v),v=t.add(h,B);let Z=t.add(O,q);return v=t.mul(v,Z),Z=t.add(c,S),v=t.sub(v,Z),Z=t.add(p,B),y=t.add(R,q),Z=t.mul(Z,y),y=t.add(w,S),Z=t.sub(Z,y),E=t.mul(_,v),y=t.mul(l,S),E=t.add(y,E),y=t.sub(w,E),E=t.add(w,E),N=t.mul(y,E),w=t.add(c,c),w=t.add(w,c),S=t.mul(_,S),v=t.mul(l,v),w=t.add(w,S),S=t.sub(c,S),S=t.mul(_,S),v=t.add(v,S),c=t.mul(w,v),N=t.add(N,c),c=t.mul(Z,v),y=t.mul(b,y),y=t.sub(y,c),c=t.mul(b,w),E=t.mul(Z,E),E=t.add(E,c),new g(y,N,E)}subtract(f){return this.add(f.negate())}is0(){return this.equals(g.ZERO)}wNAF(f){return $.wNAFCached(this,f,g.normalizeZ)}multiplyUnsafe(f){const{endo:h,n:p}=n;it("scalar",f,X,p);const B=g.ZERO;if(f===X)return B;if(this.is0()||f===L)return this;if(!h||$.hasPrecomputes(this))return $.wNAFCachedUnsafe(this,f,g.normalizeZ);let{k1neg:O,k1:R,k2neg:q,k2:y}=h.splitScalar(f),N=B,E=B,_=this;for(;R>X||y>X;)R&L&&(N=N.add(_)),y&L&&(E=E.add(_)),_=_.double(),R>>=L,y>>=L;return O&&(N=N.negate()),q&&(E=E.negate()),E=new g(t.mul(E.px,h.beta),E.py,E.pz),N.add(E)}multiply(f){const{endo:h,n:p}=n;it("scalar",f,L,p);let B,O;if(h){const{k1neg:R,k1:q,k2neg:y,k2:N}=h.splitScalar(f);let{p:E,f:_}=this.wNAF(q),{p:l,f:c}=this.wNAF(N);E=$.constTimeNegate(R,E),l=$.constTimeNegate(y,l),l=new g(t.mul(l.px,h.beta),l.py,l.pz),B=E.add(l),O=_.add(c)}else{const{p:R,f:q}=this.wNAF(f);B=R,O=q}return g.normalizeZ([B,O])[0]}multiplyAndAddUnsafe(f,h,p){const B=g.BASE,O=(q,y)=>y===X||y===L||!q.equals(B)?q.multiplyUnsafe(y):q.multiply(y),R=O(this,h).add(O(f,p));return R.is0()?void 0:R}toAffine(f){return z(this,f)}isTorsionFree(){const{h:f,isTorsionFree:h}=n;if(f===L)return!0;if(h)return h(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:h}=n;return f===L?this:h?h(g,this):this.multiplyUnsafe(n.h)}toRawBytes(f=!0){return ct("isCompressed",f),this.assertValidity(),i(g,this,f)}toHex(f=!0){return ct("isCompressed",f),at(this.toRawBytes(f))}}g.BASE=new g(n.Gx,n.Gy,t.ONE),g.ZERO=new g(t.ZERO,t.ONE,t.ZERO);const{endo:k,nBitLength:U}=n,$=Ie(g,k?Math.ceil(U/2):U);return{CURVE:n,ProjectivePoint:g,normPrivateKeyToScalar:A,weierstrassEquation:a,isWithinCurveOrder:m}}function Te(e){const n=se(e);return mt(n,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...n})}function Ue(e){const n=Te(e),{Fp:t,n:r,nByteLength:i,nBitLength:s}=n,a=t.BYTES+1,u=2*t.BYTES+1;function o(l){return M(l,r)}function d(l){return Ot(l,r)}const{ProjectivePoint:m,normPrivateKeyToScalar:A,weierstrassEquation:I,isWithinCurveOrder:z}=ze({...n,toBytes(l,c,w){const S=c.toAffine(),b=t.toBytes(S.x),v=wt;return ct("isCompressed",w),w?v(Uint8Array.from([c.hasEvenY()?2:3]),b):v(Uint8Array.from([4]),b,t.toBytes(S.y))},fromBytes(l){const c=l.length,w=l[0],S=l.subarray(1);if(c===a&&(w===2||w===3)){const b=et(S);if(!Ut(b,L,t.ORDER))throw new Error("Point is not on curve");const v=I(b);let Z;try{Z=t.sqrt(v)}catch(P){const H=P instanceof Error?": "+P.message:"";throw new Error("Point is not on curve"+H)}const C=(Z&L)===L;return(w&1)===1!==C&&(Z=t.neg(Z)),{x:b,y:Z}}else if(c===u&&w===4){const b=t.fromBytes(S.subarray(0,t.BYTES)),v=t.fromBytes(S.subarray(t.BYTES,2*t.BYTES));return{x:b,y:v}}else{const b=a,v=u;throw new Error("invalid Point, expected length of "+b+", or uncompressed "+v+", got "+c)}}});function T(l){const c=r>>L;return l>c}function g(l){return T(l)?o(-l):l}const k=(l,c,w)=>et(l.slice(c,w));class U{constructor(c,w,S){it("r",c,L,r),it("s",w,L,r),this.r=c,this.s=w,S!=null&&(this.recovery=S),Object.freeze(this)}static fromCompact(c){const w=i;return c=K("compactSignature",c,w*2),new U(k(c,0,w),k(c,w,2*w))}static fromDER(c){const{r:w,s:S}=G.toSig(K("DER",c));return new U(w,S)}assertValidity(){}addRecoveryBit(c){return new U(this.r,this.s,c)}recoverPublicKey(c){const{r:w,s:S,recovery:b}=this,v=B(K("msgHash",c));if(b==null||![0,1,2,3].includes(b))throw new Error("recovery id invalid");const Z=b===2||b===3?w+n.n:w;if(Z>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const C=b&1?"03":"02",W=m.fromHex(C+At(Z,t.BYTES)),P=d(Z),H=o(-v*P),nt=o(S*P),F=m.BASE.multiplyAndAddUnsafe(W,H,nt);if(!F)throw new Error("point at infinify");return F.assertValidity(),F}hasHighS(){return T(this.s)}normalizeS(){return this.hasHighS()?new U(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return ht(this.toDERHex())}toDERHex(){return G.hexFromSig(this)}toCompactRawBytes(){return ht(this.toCompactHex())}toCompactHex(){const c=i;return At(this.r,c)+At(this.s,c)}}const $={isValidPrivateKey(l){try{return A(l),!0}catch{return!1}},normPrivateKeyToScalar:A,randomPrivateKey:()=>{const l=re(n.n);return Se(n.randomBytes(l),n.n)},precompute(l=8,c=m.BASE){return c._setWindowSize(l),c.multiply(BigInt(3)),c}};function x(l,c=!0){return m.fromPrivateKey(l).toRawBytes(c)}function f(l){if(typeof l=="bigint")return!1;if(l instanceof m)return!0;const w=K("key",l).length,S=t.BYTES,b=S+1,v=2*S+1;if(!(n.allowedPrivateKeyLengths||i===b))return w===b||w===v}function h(l,c,w=!0){if(f(l)===!0)throw new Error("first arg must be private key");if(f(c)===!1)throw new Error("second arg must be public key");return m.fromHex(c).multiply(A(l)).toRawBytes(w)}const p=n.bits2int||function(l){if(l.length>8192)throw new Error("input is too large");const c=et(l),w=l.length*8-s;return w>0?c>>BigInt(w):c},B=n.bits2int_modN||function(l){return o(p(l))},O=gt(s);function R(l){return it("num < 2^"+s,l,X,O),ut(l,i)}function q(l,c,w=y){if(["recovered","canonical"].some(Q=>Q in w))throw new Error("sign() legacy options not supported");const{hash:S,randomBytes:b}=n;let{lowS:v,prehash:Z,extraEntropy:C}=w;v==null&&(v=!0),l=K("msgHash",l),jt(w),Z&&(l=K("prehashed msgHash",S(l)));const W=B(l),P=A(c),H=[R(P),R(W)];if(C!=null&&C!==!1){const Q=C===!0?b(t.BYTES):C;H.push(K("extraEntropy",Q))}const nt=wt(...H),F=W;function pt(Q){const rt=p(Q);if(!z(rt))return;const yt=d(rt),st=m.BASE.multiply(rt).toAffine(),J=o(st.x);if(J===X)return;const ft=o(yt*o(F+J*P));if(ft===X)return;let ot=(st.x===J?0:2)|Number(st.y&L),_t=ft;return v&&T(ft)&&(_t=g(ft),ot^=1),new U(J,_t,ot)}return{seed:nt,k2sig:pt}}const y={lowS:n.lowS,prehash:!1},N={lowS:n.lowS,prehash:!1};function E(l,c,w=y){const{seed:S,k2sig:b}=q(l,c,w),v=n;return ge(v.hash.outputLen,v.nByteLength,v.hmac)(S,b)}m.BASE._setWindowSize(8);function _(l,c,w,S=N){const b=l;c=K("msgHash",c),w=K("publicKey",w);const{lowS:v,prehash:Z,format:C}=S;if(jt(S),"strict"in S)throw new Error("options.strict was renamed to lowS");if(C!==void 0&&C!=="compact"&&C!=="der")throw new Error("format must be compact or der");const W=typeof b=="string"||lt(b),P=!W&&!C&&typeof b=="object"&&b!==null&&typeof b.r=="bigint"&&typeof b.s=="bigint";if(!W&&!P)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let H,nt;try{if(P&&(H=new U(b.r,b.s)),W){try{C!=="compact"&&(H=U.fromDER(b))}catch(ot){if(!(ot instanceof G.Err))throw ot}!H&&C!=="der"&&(H=U.fromCompact(b))}nt=m.fromHex(w)}catch{return!1}if(!H||v&&H.hasHighS())return!1;Z&&(c=n.hash(c));const{r:F,s:pt}=H,Q=B(c),rt=d(pt),yt=o(Q*rt),st=o(F*rt),J=m.BASE.multiplyAndAddUnsafe(nt,yt,st)?.toAffine();return J?o(J.x)===F:!1}return{CURVE:n,getPublicKey:x,getSharedSecret:h,sign:E,verify:_,ProjectivePoint:m,Signature:U,utils:$}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Le(e){return{hash:e,hmac:(n,...t)=>ae(e,n,le(...t)),randomBytes:ue}}function _e(e,n){const t=r=>Ue({...e,...Le(r)});return{...t(n),create:t}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const fe=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Kt=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ke=BigInt(0),Ce=BigInt(1),Rt=BigInt(2),Pt=(e,n)=>(e+n/Rt)/n;function Ve(e){const n=fe,t=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),u=BigInt(44),o=BigInt(88),d=e*e*e%n,m=d*d*e%n,A=j(m,t,n)*m%n,I=j(A,t,n)*m%n,z=j(I,Rt,n)*d%n,T=j(z,i,n)*z%n,g=j(T,s,n)*T%n,k=j(g,u,n)*g%n,U=j(k,o,n)*k%n,$=j(U,u,n)*g%n,x=j($,t,n)*m%n,f=j(x,a,n)*T%n,h=j(f,r,n)*d%n,p=j(h,Rt,n);if(!Zt.eql(Zt.sqr(p),e))throw new Error("Cannot find square root");return p}const Zt=Lt(fe,void 0,void 0,{sqrt:Ve}),Me=_e({a:ke,b:BigInt(7),Fp:Zt,n:Kt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const n=Kt,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Ce*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,a=BigInt("0x100000000000000000000000000000000"),u=Pt(s*e,n),o=Pt(-r*e,n);let d=M(e-u*t-o*i,n),m=M(-u*r-o*s,n);const A=d>a,I=m>a;if(A&&(d=n-d),I&&(m=n-m),d>a||m>a)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:A,k1:d,k2neg:I,k2:m}}}},de);export{Me as secp256k1}; diff --git a/dist/assets/send-DbOL9rGQ.js b/dist/assets/send-DbOL9rGQ.js new file mode 100644 index 0000000..73a2c79 --- /dev/null +++ b/dist/assets/send-DbOL9rGQ.js @@ -0,0 +1,15 @@ +import{b as C}from"./index-Cr5N_0pd.js";const l=C` + + `;export{l as sendSvg}; diff --git a/dist/assets/send-Ncb2jADE.js b/dist/assets/send-Ncb2jADE.js new file mode 100644 index 0000000..6662bf5 --- /dev/null +++ b/dist/assets/send-Ncb2jADE.js @@ -0,0 +1,535 @@ +import{i as f,a5 as d,aa as c,c as w,a as m,ay as O,L as I,K as x,$ as H,aL as l,x as u,aA as D,a3 as z,a4 as W,aM as q,aN as F,T as g,a7 as b,N as M,a9 as Y,a6 as K,R as _,a0 as G,a1 as J,a2 as Q}from"./index-Cr5N_0pd.js";import{S as L}from"./index-DUeQylCA.js";const X=f` + :host { + width: 100%; + height: 100px; + border-radius: var(--wui-border-radius-s); + border: 1px solid var(--wui-color-gray-glass-002); + background-color: var(--wui-color-gray-glass-002); + transition: background-color var(--wui-ease-out-power-1) var(--wui-duration-lg); + will-change: background-color; + position: relative; + } + + :host(:hover) { + background-color: var(--wui-color-gray-glass-005); + } + + wui-flex { + width: 100%; + height: fit-content; + } + + wui-button { + display: ruby; + color: var(--wui-color-fg-100); + margin: 0 var(--wui-spacing-xs); + } + + .instruction { + position: absolute; + top: 50%; + transform: translateY(-50%); + z-index: 2; + } + + .paste { + display: inline-flex; + } + + textarea { + background: transparent; + width: 100%; + font-family: var(--w3m-font-family); + font-size: var(--wui-font-size-medium); + font-style: normal; + font-weight: var(--wui-font-weight-light); + line-height: 130%; + letter-spacing: var(--wui-letter-spacing-medium); + color: var(--wui-color-fg-100); + caret-color: var(--wui-color-accent-100); + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: textfield; + padding: 0px; + border: none; + outline: none; + appearance: none; + resize: none; + overflow: hidden; + } +`;var E=function(o,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(o,e,i,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(t=(r<3?s(t):r>3?s(e,i,t):s(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let A=class extends m{constructor(){super(...arguments),this.inputElementRef=O(),this.instructionElementRef=O(),this.instructionHidden=!!this.value,this.pasting=!1,this.onDebouncedSearch=I.debounce(async e=>{if(!e.length){this.setReceiverAddress("");return}const i=x.state.activeChain;if(I.isAddress(e,i)){this.setReceiverAddress(e);return}try{const r=await H.getEnsAddress(e);if(r){l.setReceiverProfileName(e),l.setReceiverAddress(r);const t=await H.getEnsAvatar(e);l.setReceiverProfileImageUrl(t||void 0)}}catch{this.setReceiverAddress(e)}finally{l.setLoading(!1)}})}firstUpdated(){this.value&&(this.instructionHidden=!0),this.checkHidden()}render(){return u` + + Type or + + + Paste + + address + + + `}async focusInput(){this.instructionElementRef.value&&(this.instructionHidden=!0,await this.toggleInstructionFocus(!1),this.instructionElementRef.value.style.pointerEvents="none",this.inputElementRef.value?.focus(),this.inputElementRef.value&&(this.inputElementRef.value.selectionStart=this.inputElementRef.value.selectionEnd=this.inputElementRef.value.value.length))}async focusInstruction(){this.instructionElementRef.value&&(this.instructionHidden=!1,await this.toggleInstructionFocus(!0),this.instructionElementRef.value.style.pointerEvents="auto",this.inputElementRef.value?.blur())}async toggleInstructionFocus(e){this.instructionElementRef.value&&await this.instructionElementRef.value.animate([{opacity:e?0:1},{opacity:e?1:0}],{duration:100,easing:"ease",fill:"forwards"}).finished}onBoxClick(){!this.value&&!this.instructionHidden&&this.focusInput()}onBlur(){!this.value&&this.instructionHidden&&!this.pasting&&this.focusInstruction()}checkHidden(){this.instructionHidden&&this.focusInput()}async onPasteClick(){this.pasting=!0;const e=await navigator.clipboard.readText();l.setReceiverAddress(e),this.focusInput()}onInputChange(e){const i=e.target;this.pasting=!1,this.value=e.target?.value,i.value&&!this.instructionHidden&&this.focusInput(),l.setLoading(!0),this.onDebouncedSearch(i.value)}setReceiverAddress(e){l.setReceiverAddress(e),l.setReceiverProfileName(void 0),l.setReceiverProfileImageUrl(void 0),l.setLoading(!1)}};A.styles=X;E([d()],A.prototype,"value",void 0);E([c()],A.prototype,"instructionHidden",void 0);E([c()],A.prototype,"pasting",void 0);A=E([w("w3m-input-address")],A);const Z=f` + :host { + position: relative; + display: inline-block; + } + + input { + background: transparent; + width: 100%; + height: auto; + font-family: var(--wui-font-family); + color: var(--wui-color-fg-100); + + font-feature-settings: 'case' on; + font-size: 32px; + font-weight: var(--wui-font-weight-light); + caret-color: var(--wui-color-accent-100); + line-height: 130%; + letter-spacing: -1.28px; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: textfield; + padding: 0px; + } + + input::-webkit-outer-spin-button, + input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; + } + + input::placeholder { + color: var(--wui-color-fg-275); + } +`;var B=function(o,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(o,e,i,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(t=(r<3?s(t):r>3?s(e,i,t):s(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let C=class extends m{constructor(){super(...arguments),this.inputElementRef=O(),this.disabled=!1,this.value="",this.placeholder="0"}render(){return this.inputElementRef?.value&&this.value&&(this.inputElementRef.value.value=this.value),u` `}dispatchInputChangeEvent(e){const i=e.data;if(i&&this.inputElementRef?.value)if(i===","){const n=this.inputElementRef.value.value.replace(",",".");this.inputElementRef.value.value=n,this.value=`${this.value}${n}`}else q.test(i)||(this.inputElementRef.value.value=this.value.replace(new RegExp(i.replace(F,"\\$&"),"gu"),""));this.dispatchEvent(new CustomEvent("inputChange",{detail:this.inputElementRef.value?.value,bubbles:!0,composed:!0}))}};C.styles=[z,W,Z];B([d({type:Boolean})],C.prototype,"disabled",void 0);B([d({type:String})],C.prototype,"value",void 0);B([d({type:String})],C.prototype,"placeholder",void 0);C=B([w("wui-input-amount")],C);const ee=f` + :host { + width: 100%; + height: 100px; + border-radius: var(--wui-border-radius-s); + border: 1px solid var(--wui-color-gray-glass-002); + background-color: var(--wui-color-gray-glass-002); + transition: background-color var(--wui-ease-out-power-1) var(--wui-duration-lg); + will-change: background-color; + } + + :host(:hover) { + background-color: var(--wui-color-gray-glass-005); + } + + wui-flex { + width: 100%; + height: fit-content; + } + + wui-button { + width: 100%; + display: flex; + justify-content: flex-end; + } + + wui-input-amount { + mask-image: linear-gradient( + 270deg, + transparent 0px, + transparent 8px, + black 24px, + black 25px, + black 32px, + black 100% + ); + } + + .totalValue { + width: 100%; + } +`;var V=function(o,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(o,e,i,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(t=(r<3?s(t):r>3?s(e,i,t):s(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let R=class extends m{render(){return u` + + + ${this.buttonTemplate()} + + + ${this.sendValueTemplate()} + + ${this.maxAmountTemplate()} ${this.actionTemplate()} + + + `}buttonTemplate(){return this.token?u` + `:u`Select token`}handleSelectButtonClick(){g.push("WalletSendSelectToken")}sendValueTemplate(){if(this.token&&this.sendTokenAmount){const i=this.token.price*this.sendTokenAmount;return u`${i?`$${b.formatNumberToLocalString(i,2)}`:"Incorrect value"}`}return null}maxAmountTemplate(){return this.token?this.sendTokenAmount&&this.sendTokenAmount>Number(this.token.quantity.numeric)?u` + ${b.roundNumber(Number(this.token.quantity.numeric),6,5)} + `:u` + ${b.roundNumber(Number(this.token.quantity.numeric),6,5)} + `:null}actionTemplate(){return this.token?this.sendTokenAmount&&this.sendTokenAmount>Number(this.token.quantity.numeric)?u`Buy`:u`Max`:null}onInputChange(e){l.setTokenAmount(e.detail)}onMaxClick(){if(this.token){const e=M.bigNumber(this.token.quantity.numeric);l.setTokenAmount(Number(e.toFixed(20)))}}onBuyClick(){g.push("OnRampProviders")}};R.styles=ee;V([d({type:Object})],R.prototype,"token",void 0);V([d({type:Number})],R.prototype,"sendTokenAmount",void 0);R=V([w("w3m-input-token")],R);const te=f` + :host { + display: block; + } + + wui-flex { + position: relative; + } + + wui-icon-box { + width: 40px; + height: 40px; + border-radius: var(--wui-border-radius-xs) !important; + border: 5px solid var(--wui-color-bg-125); + background: var(--wui-color-bg-175); + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + z-index: 3; + } + + wui-button { + --local-border-radius: var(--wui-border-radius-xs) !important; + } + + .inputContainer { + height: fit-content; + } +`;var $=function(o,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(o,e,i,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(t=(r<3?s(t):r>3?s(e,i,t):s(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let p=class extends m{constructor(){super(),this.unsubscribe=[],this.token=l.state.token,this.sendTokenAmount=l.state.sendTokenAmount,this.receiverAddress=l.state.receiverAddress,this.receiverProfileName=l.state.receiverProfileName,this.loading=l.state.loading,this.message="Preview Send",this.token&&(this.fetchBalances(),this.fetchNetworkPrice()),this.unsubscribe.push(l.subscribe(e=>{this.token=e.token,this.sendTokenAmount=e.sendTokenAmount,this.receiverAddress=e.receiverAddress,this.receiverProfileName=e.receiverProfileName,this.loading=e.loading}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return this.getMessage(),u` + + + + + + + + ${this.message} + + + `}async fetchBalances(){await l.fetchTokenBalance(),l.fetchNetworkBalance()}async fetchNetworkPrice(){await L.getNetworkTokenPrice()}onButtonClick(){g.push("WalletSendPreview")}getMessage(){this.message="Preview Send",this.receiverAddress&&!I.isAddress(this.receiverAddress,x.state.activeChain)&&(this.message="Invalid Address"),this.receiverAddress||(this.message="Add Address"),this.sendTokenAmount&&this.token&&this.sendTokenAmount>Number(this.token.quantity.numeric)&&(this.message="Insufficient Funds"),this.sendTokenAmount||(this.message="Add Amount"),this.sendTokenAmount&&this.token?.price&&(this.sendTokenAmount*this.token.price||(this.message="Incorrect Value")),this.token||(this.message="Select Token")}};p.styles=te;$([c()],p.prototype,"token",void 0);$([c()],p.prototype,"sendTokenAmount",void 0);$([c()],p.prototype,"receiverAddress",void 0);$([c()],p.prototype,"receiverProfileName",void 0);$([c()],p.prototype,"loading",void 0);$([c()],p.prototype,"message",void 0);p=$([w("w3m-wallet-send-view")],p);const ie=f` + .contentContainer { + height: 440px; + overflow: scroll; + scrollbar-width: none; + } + + .contentContainer::-webkit-scrollbar { + display: none; + } + + wui-icon-box { + width: 40px; + height: 40px; + border-radius: var(--wui-border-radius-xxs); + } +`;var S=function(o,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(o,e,i,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(t=(r<3?s(t):r>3?s(e,i,t):s(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let k=class extends m{constructor(){super(),this.unsubscribe=[],this.tokenBalances=l.state.tokenBalances,this.search="",this.onDebouncedSearch=I.debounce(e=>{this.search=e}),this.fetchBalancesAndNetworkPrice(),this.unsubscribe.push(l.subscribe(e=>{this.tokenBalances=e.tokenBalances}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return u` + + ${this.templateSearchInput()} ${this.templateTokens()} + + `}async fetchBalancesAndNetworkPrice(){(!this.tokenBalances||this.tokenBalances?.length===0)&&(await this.fetchBalances(),await this.fetchNetworkPrice())}async fetchBalances(){await l.fetchTokenBalance(),l.fetchNetworkBalance()}async fetchNetworkPrice(){await L.getNetworkTokenPrice()}templateSearchInput(){return u` + + + + `}templateTokens(){return this.tokens=this.tokenBalances?.filter(e=>e.chainId===x.state.activeCaipNetwork?.caipNetworkId),this.search?this.filteredTokens=this.tokenBalances?.filter(e=>e.name.toLowerCase().includes(this.search.toLowerCase())):this.filteredTokens=this.tokens,u` + + + Your tokens + + + ${this.filteredTokens&&this.filteredTokens.length>0?this.filteredTokens.map(e=>u``):u` + + + No tokens found + Your tokens will appear here + + Buy + `} + + + `}onBuyClick(){g.push("OnRampProviders")}onInputChange(e){this.onDebouncedSearch(e.detail)}handleTokenClick(e){l.setToken(e),l.setTokenAmount(void 0),g.goBack()}};k.styles=ie;S([c()],k.prototype,"tokenBalances",void 0);S([c()],k.prototype,"tokens",void 0);S([c()],k.prototype,"filteredTokens",void 0);S([c()],k.prototype,"search",void 0);k=S([w("w3m-wallet-send-select-token-view")],k);const ne=f` + :host { + display: flex; + gap: var(--wui-spacing-xs); + border-radius: var(--wui-border-radius-3xl); + border: 1px solid var(--wui-color-gray-glass-002); + background: var(--wui-color-gray-glass-002); + padding: var(--wui-spacing-2xs) var(--wui-spacing-xs) var(--wui-spacing-2xs) + var(--wui-spacing-s); + align-items: center; + } + + wui-avatar, + wui-icon, + wui-image { + width: 32px; + height: 32px; + border: 1px solid var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-3xl); + box-shadow: 0 0 0 2px var(--wui-color-gray-glass-002); + } +`;var N=function(o,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(o,e,i,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(t=(r<3?s(t):r>3?s(e,i,t):s(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let y=class extends m{constructor(){super(...arguments),this.text="",this.address="",this.isAddress=!1}render(){return u`${this.text} + ${this.imageTemplate()}`}imageTemplate(){return this.isAddress?u``:this.imageSrc?u``:u``}};y.styles=[z,W,ne];N([d()],y.prototype,"text",void 0);N([d()],y.prototype,"address",void 0);N([d()],y.prototype,"imageSrc",void 0);N([d({type:Boolean})],y.prototype,"isAddress",void 0);y=N([w("wui-preview-item")],y);const re=f` + :host { + display: flex; + column-gap: var(--wui-spacing-s); + padding: 17px 18px 17px var(--wui-spacing-m); + width: 100%; + background-color: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xs); + color: var(--wui-color-fg-250); + } + + wui-image { + width: var(--wui-icon-size-lg); + height: var(--wui-icon-size-lg); + border-radius: var(--wui-border-radius-3xl); + } + + wui-icon { + width: var(--wui-icon-size-lg); + height: var(--wui-icon-size-lg); + } +`;var j=function(o,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(o,e,i,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(t=(r<3?s(t):r>3?s(e,i,t):s(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let T=class extends m{constructor(){super(...arguments),this.imageSrc=void 0,this.textTitle="",this.textValue=void 0}render(){return u` + + + ${this.textTitle} + + ${this.templateContent()} + + `}templateContent(){return this.imageSrc?u``:this.textValue?u` ${this.textValue} `:u``}};T.styles=[z,W,re];j([d()],T.prototype,"imageSrc",void 0);j([d()],T.prototype,"textTitle",void 0);j([d()],T.prototype,"textValue",void 0);T=j([w("wui-list-content")],T);const oe=f` + :host { + display: flex; + width: auto; + flex-direction: column; + gap: var(--wui-border-radius-1xs); + border-radius: var(--wui-border-radius-s); + background: var(--wui-color-gray-glass-002); + padding: var(--wui-spacing-s) var(--wui-spacing-1xs) var(--wui-spacing-1xs) + var(--wui-spacing-1xs); + } + + wui-text { + padding: 0 var(--wui-spacing-1xs); + } + + wui-flex { + margin-top: var(--wui-spacing-1xs); + } + + .network { + cursor: pointer; + transition: background-color var(--wui-ease-out-power-1) var(--wui-duration-lg); + will-change: background-color; + } + + .network:focus-visible { + border: 1px solid var(--wui-color-accent-100); + background-color: var(--wui-color-gray-glass-005); + -webkit-box-shadow: 0px 0px 0px 4px var(--wui-box-shadow-blue); + -moz-box-shadow: 0px 0px 0px 4px var(--wui-box-shadow-blue); + box-shadow: 0px 0px 0px 4px var(--wui-box-shadow-blue); + } + + .network:hover { + background-color: var(--wui-color-gray-glass-005); + } + + .network:active { + background-color: var(--wui-color-gray-glass-010); + } +`;var U=function(o,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(o,e,i,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(t=(r<3?s(t):r>3?s(e,i,t):s(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let P=class extends m{render(){return u` Details + + + + ${this.networkTemplate()} + `}networkTemplate(){return this.caipNetwork?.name?u` this.onNetworkClick(this.caipNetwork)} + class="network" + textTitle="Network" + imageSrc=${Y(K.getNetworkImage(this.caipNetwork))} + >`:null}onNetworkClick(e){e&&g.push("Networks",{network:e})}};P.styles=oe;U([d()],P.prototype,"receiverAddress",void 0);U([d({type:Object})],P.prototype,"caipNetwork",void 0);P=U([w("w3m-wallet-send-details")],P);const se=f` + wui-avatar, + wui-image { + display: ruby; + width: 32px; + height: 32px; + border-radius: var(--wui-border-radius-3xl); + } + + .sendButton { + width: 70%; + --local-width: 100% !important; + --local-border-radius: var(--wui-border-radius-xs) !important; + } + + .cancelButton { + width: 30%; + --local-width: 100% !important; + --local-border-radius: var(--wui-border-radius-xs) !important; + } +`;var v=function(o,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(o,e,i,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(t=(r<3?s(t):r>3?s(e,i,t):s(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let h=class extends m{constructor(){super(),this.unsubscribe=[],this.token=l.state.token,this.sendTokenAmount=l.state.sendTokenAmount,this.receiverAddress=l.state.receiverAddress,this.receiverProfileName=l.state.receiverProfileName,this.receiverProfileImageUrl=l.state.receiverProfileImageUrl,this.caipNetwork=x.state.activeCaipNetwork,this.loading=l.state.loading,this.unsubscribe.push(l.subscribe(e=>{this.token=e.token,this.sendTokenAmount=e.sendTokenAmount,this.receiverAddress=e.receiverAddress,this.receiverProfileName=e.receiverProfileName,this.receiverProfileImageUrl=e.receiverProfileImageUrl,this.loading=e.loading}),x.subscribeKey("activeCaipNetwork",e=>this.caipNetwork=e))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){return u` + + + + Send + ${this.sendValueTemplate()} + + + + + + + + To + + + + + + + + Review transaction carefully + + + + Cancel + + + Send + + + `}sendValueTemplate(){if(this.token&&this.sendTokenAmount){const i=this.token.price*this.sendTokenAmount;return u`$${i.toFixed(2)}`}return null}async onSendClick(){if(!this.sendTokenAmount||!this.receiverAddress){_.showError("Please enter a valid amount and receiver address");return}try{await l.sendToken(),_.showSuccess("Transaction started"),g.replace("Account")}catch(e){_.showError("Failed to send transaction. Please try again."),console.error("SendController:sendToken - failed to send transaction",e);const i=e instanceof Error?e.message:"Unknown error";G.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:i,isSmartAccount:J(x.state.activeChain)===Q.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.token?.symbol||"",amount:this.sendTokenAmount,network:x.state.activeCaipNetwork?.caipNetworkId||""}})}}onCancelClick(){g.goBack()}};h.styles=se;v([c()],h.prototype,"token",void 0);v([c()],h.prototype,"sendTokenAmount",void 0);v([c()],h.prototype,"receiverAddress",void 0);v([c()],h.prototype,"receiverProfileName",void 0);v([c()],h.prototype,"receiverProfileImageUrl",void 0);v([c()],h.prototype,"caipNetwork",void 0);v([c()],h.prototype,"loading",void 0);h=v([w("w3m-wallet-send-preview-view")],h);export{k as W3mSendSelectTokenView,h as W3mWalletSendPreviewView,p as W3mWalletSendView}; diff --git a/dist/assets/socials-DtOZCIFp.js b/dist/assets/socials-DtOZCIFp.js new file mode 100644 index 0000000..a996838 --- /dev/null +++ b/dist/assets/socials-DtOZCIFp.js @@ -0,0 +1,262 @@ +import{i as L,a5 as U,aa as c,c as I,a as _,O as $,aj as u,T as m,F as A,x as l,ak as F,L as P,al as N,Z as D,am as R,a9 as y,Y as d,$ as E,K as b,an as j,a0 as p,ao as W,R as v,ap as O,a8 as S,aq as q}from"./index-Cr5N_0pd.js";const M=L` + :host { + margin-top: var(--wui-spacing-3xs); + } + wui-separator { + margin: var(--wui-spacing-m) calc(var(--wui-spacing-m) * -1) var(--wui-spacing-xs) + calc(var(--wui-spacing-m) * -1); + width: calc(100% + var(--wui-spacing-s) * 2); + } +`;var x=function(a,e,t,o){var r=arguments.length,i=r<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,t):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,o);else for(var n=a.length-1;n>=0;n--)(s=a[n])&&(i=(r<3?s(i):r>3?s(e,t,i):s(e,t))||i);return r>3&&i&&Object.defineProperty(e,t,i),i};let w=class extends _{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=$.state.connectors,this.authConnector=this.connectors.find(e=>e.type==="AUTH"),this.remoteFeatures=u.state.remoteFeatures,this.isPwaLoading=!1,this.unsubscribe.push($.subscribeKey("connectors",e=>{this.connectors=e,this.authConnector=this.connectors.find(t=>t.type==="AUTH")}),u.subscribeKey("remoteFeatures",e=>this.remoteFeatures=e))}connectedCallback(){super.connectedCallback(),this.handlePwaFrameLoad()}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){let e=this.remoteFeatures?.socials||[];const t=!!this.authConnector,o=e?.length,r=m.state.view==="ConnectSocials";return(!t||!o)&&!r?null:(r&&!o&&(e=A.DEFAULT_SOCIALS),l` + ${e.map(i=>l`{this.onSocialClick(i)}} + data-testid=${`social-selector-${i}`} + name=${i} + logo=${i} + ?disabled=${this.isPwaLoading} + >`)} + `)}async onSocialClick(e){e&&await F(e)}async handlePwaFrameLoad(){if(P.isPWA()){this.isPwaLoading=!0;try{this.authConnector?.provider instanceof N&&await this.authConnector.provider.init()}catch(e){D.open({displayMessage:"Error loading embedded wallet in PWA",debugMessage:e.message},"error")}finally{this.isPwaLoading=!1}}}};w.styles=M;x([U()],w.prototype,"tabIdx",void 0);x([c()],w.prototype,"connectors",void 0);x([c()],w.prototype,"authConnector",void 0);x([c()],w.prototype,"remoteFeatures",void 0);x([c()],w.prototype,"isPwaLoading",void 0);w=x([I("w3m-social-login-list")],w);const z=L` + wui-flex { + max-height: clamp(360px, 540px, 80vh); + overflow: scroll; + scrollbar-width: none; + transition: opacity var(--wui-ease-out-power-1) var(--wui-duration-md); + will-change: opacity; + } + wui-flex::-webkit-scrollbar { + display: none; + } + wui-flex.disabled { + opacity: 0.3; + pointer-events: none; + user-select: none; + } +`;var T=function(a,e,t,o){var r=arguments.length,i=r<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,t):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,o);else for(var n=a.length-1;n>=0;n--)(s=a[n])&&(i=(r<3?s(i):r>3?s(e,t,i):s(e,t))||i);return r>3&&i&&Object.defineProperty(e,t,i),i};let k=class extends _{constructor(){super(),this.unsubscribe=[],this.checked=R.state.isLegalCheckboxChecked,this.unsubscribe.push(R.subscribeKey("isLegalCheckboxChecked",e=>{this.checked=e}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const{termsConditionsUrl:e,privacyPolicyUrl:t}=u.state,o=u.state.features?.legalCheckbox,i=!!(e||t)&&!!o,s=i&&!this.checked,n=s?-1:void 0;return l` + + + + + + `}};k.styles=z;T([c()],k.prototype,"checked",void 0);k=T([I("w3m-connect-socials-view")],k);const B=L` + wui-logo { + width: 80px; + height: 80px; + border-radius: var(--wui-border-radius-m); + } + @keyframes shake { + 0% { + transform: translateX(0); + } + 25% { + transform: translateX(3px); + } + 50% { + transform: translateX(-3px); + } + 75% { + transform: translateX(3px); + } + 100% { + transform: translateX(0); + } + } + wui-flex:first-child:not(:only-child) { + position: relative; + } + wui-loading-thumbnail { + position: absolute; + } + wui-icon-box { + position: absolute; + right: calc(var(--wui-spacing-3xs) * -1); + bottom: calc(var(--wui-spacing-3xs) * -1); + opacity: 0; + transform: scale(0.5); + transition: all var(--wui-ease-out-power-2) var(--wui-duration-lg); + } + wui-text[align='center'] { + width: 100%; + padding: 0px var(--wui-spacing-l); + } + [data-error='true'] wui-icon-box { + opacity: 1; + transform: scale(1); + } + [data-error='true'] > wui-flex:first-child { + animation: shake 250ms cubic-bezier(0.36, 0.07, 0.19, 0.97) both; + } + .capitalize { + text-transform: capitalize; + } +`;var g=function(a,e,t,o){var r=arguments.length,i=r<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,t):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,o);else for(var n=a.length-1;n>=0;n--)(s=a[n])&&(i=(r<3?s(i):r>3?s(e,t,i):s(e,t))||i);return r>3&&i&&Object.defineProperty(e,t,i),i};let h=class extends _{constructor(){super(),this.unsubscribe=[],this.socialProvider=d.state.socialProvider,this.socialWindow=d.state.socialWindow,this.error=!1,this.connecting=!1,this.message="Connect in the provider window",this.remoteFeatures=u.state.remoteFeatures,this.address=d.state.address,this.connectionsByNamespace=E.getConnections(b.state.activeChain),this.hasMultipleConnections=this.connectionsByNamespace.length>0,this.authConnector=$.getAuthConnector(),this.handleSocialConnection=async t=>{if(t.data?.resultUri)if(t.origin===j.SECURE_SITE_ORIGIN){window.removeEventListener("message",this.handleSocialConnection,!1);try{if(this.authConnector&&!this.connecting){this.socialWindow&&(this.socialWindow.close(),d.setSocialWindow(void 0,b.state.activeChain)),this.connecting=!0,this.updateMessage();const o=t.data.resultUri;this.socialProvider&&p.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:this.socialProvider}}),await E.connectExternal({id:this.authConnector.id,type:this.authConnector.type,socialUri:o},this.authConnector.chain),this.socialProvider&&(W.setConnectedSocialProvider(this.socialProvider),p.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:this.socialProvider,caipNetworkId:b.getActiveCaipNetwork()?.caipNetworkId}}))}}catch{this.error=!0,this.updateMessage(),this.socialProvider&&p.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:this.socialProvider}})}}else m.goBack(),v.showError("Untrusted Origin"),this.socialProvider&&p.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:this.socialProvider}})},q.EmbeddedWalletAbortController.signal.addEventListener("abort",()=>{this.socialWindow&&(this.socialWindow.close(),d.setSocialWindow(void 0,b.state.activeChain))}),this.unsubscribe.push(d.subscribe(t=>{t.socialProvider&&(this.socialProvider=t.socialProvider),t.socialWindow&&(this.socialWindow=t.socialWindow)}),u.subscribeKey("remoteFeatures",t=>{this.remoteFeatures=t}),d.subscribeKey("address",t=>{const o=this.remoteFeatures?.multiWallet;t&&t!==this.address&&(this.hasMultipleConnections&&o?(m.replace("ProfileWallets"),v.showSuccess("New Wallet Added")):(O.state.open||u.state.enableEmbedded)&&O.close())})),this.authConnector&&this.connectSocial()}disconnectedCallback(){this.unsubscribe.forEach(e=>e()),window.removeEventListener("message",this.handleSocialConnection,!1),this.socialWindow?.close(),d.setSocialWindow(void 0,b.state.activeChain)}render(){return l` + + + + ${this.error?null:this.loaderTemplate()} + + + + Log in with + ${this.socialProvider??"Social"} + ${this.message} + + `}loaderTemplate(){const e=S.state.themeVariables["--w3m-border-radius-master"],t=e?parseInt(e.replace("px",""),10):4;return l``}connectSocial(){const e=setInterval(()=>{this.socialWindow?.closed&&(!this.connecting&&m.state.view==="ConnectingSocial"&&(this.socialProvider&&p.sendEvent({type:"track",event:"SOCIAL_LOGIN_CANCELED",properties:{provider:this.socialProvider}}),m.goBack()),clearInterval(e))},1e3);window.addEventListener("message",this.handleSocialConnection,!1)}updateMessage(){this.error?this.message="Something went wrong":this.connecting?this.message="Retrieving user data":this.message="Connect in the provider window"}};h.styles=B;g([c()],h.prototype,"socialProvider",void 0);g([c()],h.prototype,"socialWindow",void 0);g([c()],h.prototype,"error",void 0);g([c()],h.prototype,"connecting",void 0);g([c()],h.prototype,"message",void 0);g([c()],h.prototype,"remoteFeatures",void 0);h=g([I("w3m-connecting-social-view")],h);const V=L` + @keyframes fadein { + from { + opacity: 0; + } + to { + opacity: 1; + } + } + + wui-shimmer { + width: 100%; + aspect-ratio: 1 / 1; + border-radius: clamp(0px, var(--wui-border-radius-l), 40px) !important; + } + + wui-qr-code { + opacity: 0; + animation-duration: 200ms; + animation-timing-function: ease; + animation-name: fadein; + animation-fill-mode: forwards; + } + + wui-logo { + width: 80px; + height: 80px; + border-radius: var(--wui-border-radius-m); + } + + wui-flex:first-child:not(:only-child) { + position: relative; + } + wui-loading-thumbnail { + position: absolute; + } + wui-icon-box { + position: absolute; + right: calc(var(--wui-spacing-3xs) * -1); + bottom: calc(var(--wui-spacing-3xs) * -1); + opacity: 0; + transform: scale(0.5); + transition: all var(--wui-ease-out-power-2) var(--wui-duration-lg); + } +`;var C=function(a,e,t,o){var r=arguments.length,i=r<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,t):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(a,e,t,o);else for(var n=a.length-1;n>=0;n--)(s=a[n])&&(i=(r<3?s(i):r>3?s(e,t,i):s(e,t))||i);return r>3&&i&&Object.defineProperty(e,t,i),i};let f=class extends _{constructor(){super(),this.unsubscribe=[],this.timeout=void 0,this.socialProvider=d.state.socialProvider,this.uri=d.state.farcasterUrl,this.ready=!1,this.loading=!1,this.remoteFeatures=u.state.remoteFeatures,this.authConnector=$.getAuthConnector(),this.forceUpdate=()=>{this.requestUpdate()},this.unsubscribe.push(d.subscribeKey("farcasterUrl",e=>{e&&(this.uri=e,this.connectFarcaster())}),d.subscribeKey("socialProvider",e=>{e&&(this.socialProvider=e)}),u.subscribeKey("remoteFeatures",e=>{this.remoteFeatures=e})),window.addEventListener("resize",this.forceUpdate)}disconnectedCallback(){super.disconnectedCallback(),clearTimeout(this.timeout),window.removeEventListener("resize",this.forceUpdate)}render(){return this.onRenderProxy(),l`${this.platformTemplate()}`}platformTemplate(){return P.isMobile()?l`${this.mobileTemplate()}`:l`${this.desktopTemplate()}`}desktopTemplate(){return this.loading?l`${this.loadingTemplate()}`:l`${this.qrTemplate()}`}qrTemplate(){return l` + ${this.qrCodeTemplate()} + + + Scan this QR Code with your phone + + ${this.copyTemplate()} + `}loadingTemplate(){return l` + + + + ${this.loaderTemplate()} + + + + + Loading user data + + + Please wait a moment while we load your data. + + + + `}mobileTemplate(){return l` + + + ${this.loaderTemplate()} + + + + Continue in Farcaster + Accept connection request in the app + ${this.mobileLinkTemplate()} + `}loaderTemplate(){const e=S.state.themeVariables["--w3m-border-radius-master"],t=e?parseInt(e.replace("px",""),10):4;return l``}async connectFarcaster(){if(this.authConnector)try{await this.authConnector?.provider.connectFarcaster(),this.socialProvider&&(W.setConnectedSocialProvider(this.socialProvider),p.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:this.socialProvider}})),this.loading=!0;const t=E.getConnections(this.authConnector.chain).length>0;await E.connectExternal(this.authConnector,this.authConnector.chain);const o=this.remoteFeatures?.multiWallet;this.socialProvider&&p.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:this.socialProvider,caipNetworkId:b.getActiveCaipNetwork()?.caipNetworkId}}),this.loading=!1,t&&o?(m.replace("ProfileWallets"),v.showSuccess("New Wallet Added")):O.close()}catch(e){this.socialProvider&&p.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:this.socialProvider}}),m.goBack(),v.showError(e)}}mobileLinkTemplate(){return l`{this.uri&&P.openHref(this.uri,"_blank")}} + > + Open farcaster`}onRenderProxy(){!this.ready&&this.uri&&(this.timeout=setTimeout(()=>{this.ready=!0},200))}qrCodeTemplate(){if(!this.uri||!this.ready)return null;const e=this.getBoundingClientRect().width-40;return l` `}copyTemplate(){const e=!this.uri||!this.ready;return l` + + Copy link + `}onCopyUri(){try{this.uri&&(P.copyToClopboard(this.uri),v.showSuccess("Link copied"))}catch{v.showError("Failed to copy")}}};f.styles=V;C([c()],f.prototype,"socialProvider",void 0);C([c()],f.prototype,"uri",void 0);C([c()],f.prototype,"ready",void 0);C([c()],f.prototype,"loading",void 0);C([c()],f.prototype,"remoteFeatures",void 0);f=C([I("w3m-connecting-farcaster-view")],f);export{k as W3mConnectSocialsView,f as W3mConnectingFarcasterView,h as W3mConnectingSocialView}; diff --git a/dist/assets/solana-wnPogKuz.js b/dist/assets/solana-wnPogKuz.js new file mode 100644 index 0000000..a25e1bc --- /dev/null +++ b/dist/assets/solana-wnPogKuz.js @@ -0,0 +1,13 @@ +import{b as C}from"./index-Cr5N_0pd.js";const i=C` + + + + + + + + + + + +`;export{i as solanaSvg}; diff --git a/dist/assets/swapHorizontal-iQa05UE_.js b/dist/assets/swapHorizontal-iQa05UE_.js new file mode 100644 index 0000000..4afbf55 --- /dev/null +++ b/dist/assets/swapHorizontal-iQa05UE_.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + +`;export{o as swapHorizontalSvg}; diff --git a/dist/assets/swapHorizontalBold-CxDNxTSc.js b/dist/assets/swapHorizontalBold-CxDNxTSc.js new file mode 100644 index 0000000..afb9aaf --- /dev/null +++ b/dist/assets/swapHorizontalBold-CxDNxTSc.js @@ -0,0 +1,8 @@ +import{b as C}from"./index-Cr5N_0pd.js";const e=C` + +`;export{e as swapHorizontalBoldSvg}; diff --git a/dist/assets/swapHorizontalMedium-KeWOduSV.js b/dist/assets/swapHorizontalMedium-KeWOduSV.js new file mode 100644 index 0000000..86920f9 --- /dev/null +++ b/dist/assets/swapHorizontalMedium-KeWOduSV.js @@ -0,0 +1,16 @@ +import{b as C}from"./index-Cr5N_0pd.js";const e=C` + + + +`;export{e as swapHorizontalMediumSvg}; diff --git a/dist/assets/swapHorizontalRoundedBold-BKa1b4V9.js b/dist/assets/swapHorizontalRoundedBold-BKa1b4V9.js new file mode 100644 index 0000000..a1c19a2 --- /dev/null +++ b/dist/assets/swapHorizontalRoundedBold-BKa1b4V9.js @@ -0,0 +1,8 @@ +import{b as C}from"./index-Cr5N_0pd.js";const L=C` + +`;export{L as swapHorizontalRoundedBoldSvg}; diff --git a/dist/assets/swapVertical-BkcJfrl6.js b/dist/assets/swapVertical-BkcJfrl6.js new file mode 100644 index 0000000..9af0401 --- /dev/null +++ b/dist/assets/swapVertical-BkcJfrl6.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const e=l` + +`;export{e as swapVerticalSvg}; diff --git a/dist/assets/swaps-2zeCrlxq.js b/dist/assets/swaps-2zeCrlxq.js new file mode 100644 index 0000000..7bd1baa --- /dev/null +++ b/dist/assets/swaps-2zeCrlxq.js @@ -0,0 +1,976 @@ +import{i as A,aa as s,a5 as w,c as P,a as C,K as I,N as D,x as u,a7 as x,F as z,a0 as O,T,Y as U,L as K,ap as F,a1 as M,a2 as Q,a3 as H,a4 as q,aF as L}from"./index-Cr5N_0pd.js";import{S as o}from"./index-DUeQylCA.js";const G={numericInputKeyDown(l,e,i){const n=["Backspace","Meta","Ctrl","a","A","c","C","x","X","v","V","ArrowLeft","ArrowRight","Tab"],r=l.metaKey||l.ctrlKey,t=l.key,a=t.toLocaleLowerCase(),c=a==="a",E=a==="c",V=a==="v",W=a==="x",N=t===",",j=t===".",R=t>="0"&&t<="9";!r&&(c||E||V||W)&&l.preventDefault(),e==="0"&&!N&&!j&&t==="0"&&l.preventDefault(),e==="0"&&R&&(i(t),l.preventDefault()),(N||j)&&(e||(i("0."),l.preventDefault()),(e?.includes(".")||e?.includes(","))&&l.preventDefault()),!R&&!n.includes(t)&&!j&&!N&&l.preventDefault()}},Y=A` + :host { + width: 100%; + } + + .details-container > wui-flex { + background: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xxs); + width: 100%; + } + + .details-container > wui-flex > button { + border: none; + background: none; + padding: var(--wui-spacing-s); + border-radius: var(--wui-border-radius-xxs); + cursor: pointer; + } + + .details-content-container { + padding: var(--wui-spacing-1xs); + padding-top: 0px; + display: flex; + align-items: center; + justify-content: center; + } + + .details-content-container > wui-flex { + width: 100%; + } + + .details-row { + width: 100%; + padding: var(--wui-spacing-s); + padding-left: var(--wui-spacing-s); + padding-right: var(--wui-spacing-1xs); + border-radius: calc(var(--wui-border-radius-5xs) + var(--wui-border-radius-4xs)); + background: var(--wui-color-gray-glass-002); + } + + .details-row-title { + white-space: nowrap; + } + + .details-row.provider-free-row { + padding-right: var(--wui-spacing-xs); + } +`;var b=function(l,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(l,e,i,n);else for(var c=l.length-1;c>=0;c--)(a=l[c])&&(t=(r<3?a(t):r>3?a(e,i,t):a(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};const X=z.CONVERT_SLIPPAGE_TOLERANCE;let f=class extends C{constructor(){super(),this.unsubscribe=[],this.networkName=I.state.activeCaipNetwork?.name,this.detailsOpen=!1,this.sourceToken=o.state.sourceToken,this.toToken=o.state.toToken,this.toTokenAmount=o.state.toTokenAmount,this.sourceTokenPriceInUSD=o.state.sourceTokenPriceInUSD,this.toTokenPriceInUSD=o.state.toTokenPriceInUSD,this.priceImpact=o.state.priceImpact,this.maxSlippage=o.state.maxSlippage,this.networkTokenSymbol=o.state.networkTokenSymbol,this.inputError=o.state.inputError,this.unsubscribe.push(o.subscribe(e=>{this.sourceToken=e.sourceToken,this.toToken=e.toToken,this.toTokenAmount=e.toTokenAmount,this.priceImpact=e.priceImpact,this.maxSlippage=e.maxSlippage,this.sourceTokenPriceInUSD=e.sourceTokenPriceInUSD,this.toTokenPriceInUSD=e.toTokenPriceInUSD,this.inputError=e.inputError}))}render(){const e=this.toTokenAmount&&this.maxSlippage?D.bigNumber(this.toTokenAmount).minus(this.maxSlippage).toString():null;if(!this.sourceToken||!this.toToken||this.inputError)return null;const i=this.sourceTokenPriceInUSD&&this.toTokenPriceInUSD?1/this.toTokenPriceInUSD*this.sourceTokenPriceInUSD:0;return u` + + + + ${this.detailsOpen?u` + + ${this.priceImpact?u` + + + + Price impact + + + + + + + + ${x.formatNumberToLocalString(this.priceImpact,3)}% + + + + `:null} + ${this.maxSlippage&&this.sourceToken.symbol?u` + + + + Max. slippage + + + + + + + + ${x.formatNumberToLocalString(this.maxSlippage,6)} + ${this.toToken.symbol} ${X}% + + + + `:null} + + + + + Provider fee + + + + 0.85% + + + + + `:null} + + + `}toggleDetails(){this.detailsOpen=!this.detailsOpen}};f.styles=[Y];b([s()],f.prototype,"networkName",void 0);b([w()],f.prototype,"detailsOpen",void 0);b([s()],f.prototype,"sourceToken",void 0);b([s()],f.prototype,"toToken",void 0);b([s()],f.prototype,"toTokenAmount",void 0);b([s()],f.prototype,"sourceTokenPriceInUSD",void 0);b([s()],f.prototype,"toTokenPriceInUSD",void 0);b([s()],f.prototype,"priceImpact",void 0);b([s()],f.prototype,"maxSlippage",void 0);b([s()],f.prototype,"networkTokenSymbol",void 0);b([s()],f.prototype,"inputError",void 0);f=b([P("w3m-swap-details")],f);const Z=A` + :host { + width: 100%; + } + + :host > wui-flex { + display: flex; + flex-direction: row; + justify-content: space-between; + align-items: center; + border-radius: var(--wui-border-radius-s); + padding: var(--wui-spacing-xl); + padding-right: var(--wui-spacing-s); + background-color: var(--wui-color-gray-glass-002); + box-shadow: inset 0px 0px 0px 1px var(--wui-color-gray-glass-002); + width: 100%; + height: 100px; + box-sizing: border-box; + position: relative; + } + + wui-shimmer.market-value { + opacity: 0; + } + + :host > wui-flex > svg.input_mask { + position: absolute; + inset: 0; + z-index: 5; + } + + :host wui-flex .input_mask__border, + :host wui-flex .input_mask__background { + transition: fill var(--wui-duration-md) var(--wui-ease-out-power-1); + will-change: fill; + } + + :host wui-flex .input_mask__border { + fill: var(--wui-color-gray-glass-020); + } + + :host wui-flex .input_mask__background { + fill: var(--wui-color-gray-glass-002); + } +`;var B=function(l,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(l,e,i,n);else for(var c=l.length-1;c>=0;c--)(a=l[c])&&(t=(r<3?a(t):r>3?a(e,i,t):a(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let _=class extends C{constructor(){super(...arguments),this.target="sourceToken"}render(){return u` + + + + + ${this.templateTokenSelectButton()} + + `}templateTokenSelectButton(){return u` + + + + `}};_.styles=[Z];B([w()],_.prototype,"target",void 0);_=B([P("w3m-swap-input-skeleton")],_);const J=A` + :host > wui-flex { + display: flex; + flex-direction: row; + justify-content: space-between; + align-items: center; + border-radius: var(--wui-border-radius-s); + background-color: var(--wui-color-gray-glass-002); + padding: var(--wui-spacing-xl); + padding-right: var(--wui-spacing-s); + width: 100%; + height: 100px; + box-sizing: border-box; + box-shadow: inset 0px 0px 0px 1px var(--wui-color-gray-glass-002); + position: relative; + transition: box-shadow var(--wui-ease-out-power-1) var(--wui-duration-lg); + will-change: background-color; + } + + :host wui-flex.focus { + box-shadow: inset 0px 0px 0px 1px var(--wui-color-gray-glass-005); + } + + :host > wui-flex .swap-input, + :host > wui-flex .swap-token-button { + z-index: 10; + } + + :host > wui-flex .swap-input { + -webkit-mask-image: linear-gradient( + 270deg, + transparent 0px, + transparent 8px, + black 24px, + black 25px, + black 32px, + black 100% + ); + mask-image: linear-gradient( + 270deg, + transparent 0px, + transparent 8px, + black 24px, + black 25px, + black 32px, + black 100% + ); + } + + :host > wui-flex .swap-input input { + background: none; + border: none; + height: 42px; + width: 100%; + font-size: 32px; + font-style: normal; + font-weight: 400; + line-height: 130%; + letter-spacing: -1.28px; + outline: none; + caret-color: var(--wui-color-accent-100); + color: var(--wui-color-fg-100); + padding: 0px; + } + + :host > wui-flex .swap-input input:focus-visible { + outline: none; + } + + :host > wui-flex .swap-input input::-webkit-outer-spin-button, + :host > wui-flex .swap-input input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; + } + + .max-value-button { + background-color: transparent; + border: none; + cursor: pointer; + color: var(--wui-color-gray-glass-020); + padding-left: 0px; + } + + .market-value { + min-height: 18px; + } +`;var v=function(l,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(l,e,i,n);else for(var c=l.length-1;c>=0;c--)(a=l[c])&&(t=(r<3?a(t):r>3?a(e,i,t):a(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};const ee=5e-5;let m=class extends C{constructor(){super(...arguments),this.focused=!1,this.price=0,this.target="sourceToken",this.onSetAmount=null,this.onSetMaxValue=null}render(){const e=this.marketValue||"0",i=D.bigNumber(e).gt("0");return u` + + + this.onFocusChange(!0)} + @focusout=${()=>this.onFocusChange(!1)} + ?disabled=${this.disabled} + .value=${this.value} + @input=${this.dispatchInputChangeEvent} + @keydown=${this.handleKeydown} + placeholder="0" + type="text" + inputmode="decimal" + /> + + ${i?`$${x.formatNumberToLocalString(this.marketValue,2)}`:null} + + + ${this.templateTokenSelectButton()} + + `}handleKeydown(e){return G.numericInputKeyDown(e,this.value,i=>this.onSetAmount?.(this.target,i))}dispatchInputChangeEvent(e){if(!this.onSetAmount)return;const i=e.target.value.replace(/[^0-9.]/gu,"");i===","||i==="."?this.onSetAmount(this.target,"0."):i.endsWith(",")?this.onSetAmount(this.target,i.replace(",",".")):this.onSetAmount(this.target,i)}setMaxValueToInput(){this.onSetMaxValue?.(this.target,this.balance)}templateTokenSelectButton(){return this.token?u` + + + + ${this.tokenBalanceTemplate()} + + `:u` + Select token + `}tokenBalanceTemplate(){const e=D.multiply(this.balance,this.price),i=e?e?.gt(ee):!1;return u` + ${i?u` + ${x.formatNumberToLocalString(this.balance,2)} + `:null} + ${this.target==="sourceToken"?this.tokenActionButtonTemplate(i):null} + `}tokenActionButtonTemplate(e){return e?u` `:u` `}onFocusChange(e){this.focused=e}onSelectToken(){O.sendEvent({type:"track",event:"CLICK_SELECT_TOKEN_TO_SWAP"}),T.push("SwapSelectToken",{target:this.target})}onBuyToken(){T.push("OnRampProviders")}};m.styles=[J];v([w()],m.prototype,"focused",void 0);v([w()],m.prototype,"balance",void 0);v([w()],m.prototype,"value",void 0);v([w()],m.prototype,"price",void 0);v([w()],m.prototype,"marketValue",void 0);v([w()],m.prototype,"disabled",void 0);v([w()],m.prototype,"target",void 0);v([w()],m.prototype,"token",void 0);v([w()],m.prototype,"onSetAmount",void 0);v([w()],m.prototype,"onSetMaxValue",void 0);m=v([P("w3m-swap-input")],m);const te=A` + :host > wui-flex:first-child { + overflow-y: auto; + overflow-x: hidden; + scrollbar-width: none; + } + + :host > wui-flex:first-child::-webkit-scrollbar { + display: none; + } + + wui-loading-hexagon { + position: absolute; + } + + .action-button { + width: 100%; + border-radius: var(--wui-border-radius-xs); + } + + .action-button:disabled { + border-color: 1px solid var(--wui-color-gray-glass-005); + } + + .swap-inputs-container { + position: relative; + } + + .replace-tokens-button-container { + display: flex; + justify-content: center; + align-items: center; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + gap: var(--wui-spacing-1xs); + border-radius: var(--wui-border-radius-xs); + background-color: var(--wui-color-modal-bg-base); + padding: var(--wui-spacing-xxs); + } + + .replace-tokens-button-container > button { + display: flex; + justify-content: center; + align-items: center; + height: 40px; + width: 40px; + padding: var(--wui-spacing-xs); + border: none; + border-radius: var(--wui-border-radius-xxs); + background: var(--wui-color-gray-glass-002); + transition: background-color var(--wui-duration-md) var(--wui-ease-out-power-1); + will-change: background-color; + z-index: 20; + } + + .replace-tokens-button-container > button:hover { + background: var(--wui-color-gray-glass-005); + } + + .details-container > wui-flex { + background: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xxs); + width: 100%; + } + + .details-container > wui-flex > button { + border: none; + background: none; + padding: var(--wui-spacing-s); + border-radius: var(--wui-border-radius-xxs); + transition: background 0.2s linear; + } + + .details-container > wui-flex > button:hover { + background: var(--wui-color-gray-glass-002); + } + + .details-content-container { + padding: var(--wui-spacing-1xs); + display: flex; + align-items: center; + justify-content: center; + } + + .details-content-container > wui-flex { + width: 100%; + } + + .details-row { + width: 100%; + padding: var(--wui-spacing-s) var(--wui-spacing-xl); + border-radius: var(--wui-border-radius-xxs); + background: var(--wui-color-gray-glass-002); + } +`;var h=function(l,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(l,e,i,n);else for(var c=l.length-1;c>=0;c--)(a=l[c])&&(t=(r<3?a(t):r>3?a(e,i,t):a(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let p=class extends C{constructor(){super(),this.unsubscribe=[],this.initialParams=T.state.data?.swap,this.detailsOpen=!1,this.caipAddress=U.state.caipAddress,this.caipNetworkId=I.state.activeCaipNetwork?.caipNetworkId,this.initialized=o.state.initialized,this.loadingQuote=o.state.loadingQuote,this.loadingPrices=o.state.loadingPrices,this.loadingTransaction=o.state.loadingTransaction,this.sourceToken=o.state.sourceToken,this.sourceTokenAmount=o.state.sourceTokenAmount,this.sourceTokenPriceInUSD=o.state.sourceTokenPriceInUSD,this.toToken=o.state.toToken,this.toTokenAmount=o.state.toTokenAmount,this.toTokenPriceInUSD=o.state.toTokenPriceInUSD,this.inputError=o.state.inputError,this.fetchError=o.state.fetchError,this.lastTokenPriceUpdate=0,this.minTokenPriceUpdateInterval=1e4,this.visibilityChangeHandler=()=>{document?.hidden?(clearInterval(this.interval),this.interval=void 0):this.startTokenPriceInterval()},this.startTokenPriceInterval=()=>{this.interval&&Date.now()-this.lastTokenPriceUpdatethis.minTokenPriceUpdateInterval&&this.fetchTokensAndValues(),clearInterval(this.interval),this.interval=setInterval(()=>{this.fetchTokensAndValues()},this.minTokenPriceUpdateInterval))},this.watchTokensAndValues=()=>{!this.sourceToken||!this.toToken||(this.subscribeToVisibilityChange(),this.startTokenPriceInterval())},this.onDebouncedGetSwapCalldata=K.debounce(async()=>{await o.swapTokens()},200),I.subscribeKey("activeCaipNetwork",e=>this.onCaipNetworkChange({newCaipNetwork:e,resetSwapState:!0,initializeSwapState:!1})),U.subscribeKey("caipAddress",e=>this.onCaipAddressChange({newCaipAddress:e,resetSwapState:!0,initializeSwapState:!1})),this.unsubscribe.push(I.subscribeKey("activeCaipNetwork",e=>this.onCaipNetworkChange({newCaipNetwork:e,resetSwapState:!1,initializeSwapState:!0})),U.subscribeKey("caipAddress",e=>this.onCaipAddressChange({newCaipAddress:e,resetSwapState:!1,initializeSwapState:!0})),F.subscribeKey("open",e=>{e||o.resetState()}),T.subscribeKey("view",e=>{e.includes("Swap")||o.resetValues()}),o.subscribe(e=>{this.initialized=e.initialized,this.loadingQuote=e.loadingQuote,this.loadingPrices=e.loadingPrices,this.loadingTransaction=e.loadingTransaction,this.sourceToken=e.sourceToken,this.sourceTokenAmount=e.sourceTokenAmount,this.sourceTokenPriceInUSD=e.sourceTokenPriceInUSD,this.toToken=e.toToken,this.toTokenAmount=e.toTokenAmount,this.toTokenPriceInUSD=e.toTokenPriceInUSD,this.inputError=e.inputError,this.fetchError=e.fetchError,e.sourceToken&&e.toToken&&this.watchTokensAndValues()}))}async firstUpdated(){o.initializeState(),this.watchTokensAndValues(),await this.handleSwapParameters()}disconnectedCallback(){this.unsubscribe.forEach(e=>e?.()),clearInterval(this.interval),document?.removeEventListener("visibilitychange",this.visibilityChangeHandler)}render(){return u` + + ${this.initialized?this.templateSwap():this.templateLoading()} + + `}subscribeToVisibilityChange(){document?.removeEventListener("visibilitychange",this.visibilityChangeHandler),document?.addEventListener("visibilitychange",this.visibilityChangeHandler)}fetchTokensAndValues(){o.getNetworkTokenPrice(),o.getMyTokensWithBalance(),o.swapTokens(),this.lastTokenPriceUpdate=Date.now()}templateSwap(){return u` + + + ${this.templateTokenInput("sourceToken",this.sourceToken)} + ${this.templateTokenInput("toToken",this.toToken)} ${this.templateReplaceTokensButton()} + + ${this.templateDetails()} ${this.templateActionButton()} + + `}actionButtonLabel(){return this.fetchError?"Swap":!this.sourceToken||!this.toToken?"Select token":this.sourceTokenAmount?this.inputError?this.inputError:"Review swap":"Enter amount"}templateReplaceTokensButton(){return u` + + + + `}templateLoading(){return u` + + + + + ${this.templateReplaceTokensButton()} + + ${this.templateActionButton()} + + `}templateTokenInput(e,i){const n=o.state.myTokensWithBalance?.find(c=>c?.address===i?.address),r=e==="toToken"?this.toTokenAmount:this.sourceTokenAmount,t=e==="toToken"?this.toTokenPriceInUSD:this.sourceTokenPriceInUSD,a=D.parseLocalStringToNumber(r)*t;return u``}onSetMaxValue(e,i){const n=D.bigNumber(i||"0");this.handleChangeAmount(e,n.gt(0)?n.toFixed(20):"0")}templateDetails(){return!this.sourceToken||!this.toToken||this.inputError?null:u``}handleChangeAmount(e,i){o.clearError(),e==="sourceToken"?o.setSourceTokenAmount(i):o.setToTokenAmount(i),this.onDebouncedGetSwapCalldata()}templateActionButton(){const e=!this.toToken||!this.sourceToken,i=!this.sourceTokenAmount,n=this.loadingQuote||this.loadingPrices||this.loadingTransaction,r=n||e||i||this.inputError;return u` + + ${this.actionButtonLabel()} + + `}onSwitchTokens(){o.switchTokens()}async onSwapPreview(){this.fetchError&&await o.swapTokens(),O.sendEvent({type:"track",event:"INITIATE_SWAP",properties:{network:this.caipNetworkId||"",swapFromToken:this.sourceToken?.symbol||"",swapToToken:this.toToken?.symbol||"",swapFromAmount:this.sourceTokenAmount||"",swapToAmount:this.toTokenAmount||"",isSmartAccount:M(I.state.activeChain)===Q.ACCOUNT_TYPES.SMART_ACCOUNT}}),T.push("SwapPreview")}async handleSwapParameters(){this.initialParams&&(o.state.initialized||await new Promise(i=>{const n=o.subscribeKey("initialized",r=>{r&&(n?.(),i())})}),await this.setSwapParameters(this.initialParams))}async setSwapParameters({amount:e,fromToken:i,toToken:n}){(!o.state.tokens||!o.state.myTokensWithBalance)&&await new Promise(a=>{const c=o.subscribeKey("myTokensWithBalance",E=>{E&&E.length>0&&(c?.(),a())});setTimeout(()=>{c?.(),a()},5e3)});const r=[...o.state.tokens||[],...o.state.myTokensWithBalance||[]];if(i){const t=r.find(a=>a.symbol.toLowerCase()===i.toLowerCase());t&&o.setSourceToken(t)}if(n){const t=r.find(a=>a.symbol.toLowerCase()===n.toLowerCase());t&&o.setToToken(t)}e&&!isNaN(Number(e))&&o.setSourceTokenAmount(e)}onCaipAddressChange({newCaipAddress:e,resetSwapState:i,initializeSwapState:n}){this.caipAddress!==e&&(this.caipAddress=e,i&&o.resetState(),n&&o.initializeState())}onCaipNetworkChange({newCaipNetwork:e,resetSwapState:i,initializeSwapState:n}){this.caipNetworkId!==e?.caipNetworkId&&(this.caipNetworkId=e?.caipNetworkId,i&&o.resetState(),n&&o.initializeState())}};p.styles=te;h([w({type:Object})],p.prototype,"initialParams",void 0);h([s()],p.prototype,"interval",void 0);h([s()],p.prototype,"detailsOpen",void 0);h([s()],p.prototype,"caipAddress",void 0);h([s()],p.prototype,"caipNetworkId",void 0);h([s()],p.prototype,"initialized",void 0);h([s()],p.prototype,"loadingQuote",void 0);h([s()],p.prototype,"loadingPrices",void 0);h([s()],p.prototype,"loadingTransaction",void 0);h([s()],p.prototype,"sourceToken",void 0);h([s()],p.prototype,"sourceTokenAmount",void 0);h([s()],p.prototype,"sourceTokenPriceInUSD",void 0);h([s()],p.prototype,"toToken",void 0);h([s()],p.prototype,"toTokenAmount",void 0);h([s()],p.prototype,"toTokenPriceInUSD",void 0);h([s()],p.prototype,"inputError",void 0);h([s()],p.prototype,"fetchError",void 0);h([s()],p.prototype,"lastTokenPriceUpdate",void 0);p=h([P("w3m-swap-view")],p);const ie=A` + :host > wui-flex:first-child { + overflow-y: auto; + overflow-x: hidden; + scrollbar-width: none; + } + + :host > wui-flex:first-child::-webkit-scrollbar { + display: none; + } + + .preview-container, + .details-container { + width: 100%; + } + + .token-image { + width: 24px; + height: 24px; + box-shadow: 0 0 0 2px var(--wui-color-gray-glass-005); + border-radius: 12px; + } + + wui-loading-hexagon { + position: absolute; + } + + .token-item { + display: flex; + align-items: center; + justify-content: center; + gap: var(--wui-spacing-xxs); + padding: var(--wui-spacing-xs); + height: 40px; + border: none; + border-radius: 80px; + background: var(--wui-color-gray-glass-002); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-002); + cursor: pointer; + transition: background 0.2s linear; + } + + .token-item:hover { + background: var(--wui-color-gray-glass-005); + } + + .preview-token-details-container { + width: 100%; + } + + .details-row { + width: 100%; + padding: var(--wui-spacing-s) var(--wui-spacing-xl); + border-radius: var(--wui-border-radius-xxs); + background: var(--wui-color-gray-glass-002); + } + + .action-buttons-container { + width: 100%; + gap: var(--wui-spacing-xs); + } + + .action-buttons-container > button { + display: flex; + align-items: center; + justify-content: center; + background: transparent; + height: 48px; + border-radius: var(--wui-border-radius-xs); + border: none; + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + } + + .action-buttons-container > button:disabled { + opacity: 0.8; + cursor: not-allowed; + } + + .action-button > wui-loading-spinner { + display: inline-block; + } + + .cancel-button:hover, + .action-button:hover { + cursor: pointer; + } + + .action-buttons-container > wui-button.cancel-button { + flex: 2; + } + + .action-buttons-container > wui-button.action-button { + flex: 4; + } + + .action-buttons-container > button.action-button > wui-text { + color: white; + } + + .details-container > wui-flex { + background: var(--wui-color-gray-glass-002); + border-radius: var(--wui-border-radius-xxs); + width: 100%; + } + + .details-container > wui-flex > button { + border: none; + background: none; + padding: var(--wui-spacing-s); + border-radius: var(--wui-border-radius-xxs); + transition: background 0.2s linear; + } + + .details-container > wui-flex > button:hover { + background: var(--wui-color-gray-glass-002); + } + + .details-content-container { + padding: var(--wui-spacing-1xs); + display: flex; + align-items: center; + justify-content: center; + } + + .details-content-container > wui-flex { + width: 100%; + } + + .details-row { + width: 100%; + padding: var(--wui-spacing-s) var(--wui-spacing-xl); + border-radius: var(--wui-border-radius-xxs); + background: var(--wui-color-gray-glass-002); + } +`;var g=function(l,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(l,e,i,n);else for(var c=l.length-1;c>=0;c--)(a=l[c])&&(t=(r<3?a(t):r>3?a(e,i,t):a(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let d=class extends C{constructor(){super(),this.unsubscribe=[],this.detailsOpen=!0,this.approvalTransaction=o.state.approvalTransaction,this.swapTransaction=o.state.swapTransaction,this.sourceToken=o.state.sourceToken,this.sourceTokenAmount=o.state.sourceTokenAmount??"",this.sourceTokenPriceInUSD=o.state.sourceTokenPriceInUSD,this.toToken=o.state.toToken,this.toTokenAmount=o.state.toTokenAmount??"",this.toTokenPriceInUSD=o.state.toTokenPriceInUSD,this.caipNetwork=I.state.activeCaipNetwork,this.balanceSymbol=U.state.balanceSymbol,this.inputError=o.state.inputError,this.loadingQuote=o.state.loadingQuote,this.loadingApprovalTransaction=o.state.loadingApprovalTransaction,this.loadingBuildTransaction=o.state.loadingBuildTransaction,this.loadingTransaction=o.state.loadingTransaction,this.unsubscribe.push(U.subscribeKey("balanceSymbol",e=>{this.balanceSymbol!==e&&T.goBack()}),I.subscribeKey("activeCaipNetwork",e=>{this.caipNetwork!==e&&(this.caipNetwork=e)}),o.subscribe(e=>{this.approvalTransaction=e.approvalTransaction,this.swapTransaction=e.swapTransaction,this.sourceToken=e.sourceToken,this.toToken=e.toToken,this.toTokenPriceInUSD=e.toTokenPriceInUSD,this.sourceTokenAmount=e.sourceTokenAmount??"",this.toTokenAmount=e.toTokenAmount??"",this.inputError=e.inputError,e.inputError&&T.goBack(),this.loadingQuote=e.loadingQuote,this.loadingApprovalTransaction=e.loadingApprovalTransaction,this.loadingBuildTransaction=e.loadingBuildTransaction,this.loadingTransaction=e.loadingTransaction}))}firstUpdated(){o.getTransaction(),this.refreshTransaction()}disconnectedCallback(){this.unsubscribe.forEach(e=>e?.()),clearInterval(this.interval)}render(){return u` + + ${this.templateSwap()} + + `}refreshTransaction(){this.interval=setInterval(()=>{o.getApprovalLoadingState()||o.getTransaction()},1e4)}templateSwap(){const e=`${x.formatNumberToLocalString(parseFloat(this.sourceTokenAmount))} ${this.sourceToken?.symbol}`,i=`${x.formatNumberToLocalString(parseFloat(this.toTokenAmount))} ${this.toToken?.symbol}`,n=parseFloat(this.sourceTokenAmount)*this.sourceTokenPriceInUSD,r=parseFloat(this.toTokenAmount)*this.toTokenPriceInUSD,t=x.formatNumberToLocalString(n),a=x.formatNumberToLocalString(r),c=this.loadingQuote||this.loadingBuildTransaction||this.loadingTransaction||this.loadingApprovalTransaction;return u` + + + + + Send + $${t} + + + + + + + + Receive + $${a} + + + + + + + ${this.templateDetails()} + + + + Review transaction carefully + + + + + Cancel + + + + ${this.actionButtonLabel()} + + + + + `}templateDetails(){return!this.sourceToken||!this.toToken||this.inputError?null:u``}actionButtonLabel(){return this.loadingApprovalTransaction?"Approving...":this.approvalTransaction?"Approve":"Swap"}onCancelTransaction(){T.goBack()}onSendTransaction(){this.approvalTransaction?o.sendTransactionForApproval(this.approvalTransaction):o.sendTransactionForSwap(this.swapTransaction)}};d.styles=ie;g([s()],d.prototype,"interval",void 0);g([s()],d.prototype,"detailsOpen",void 0);g([s()],d.prototype,"approvalTransaction",void 0);g([s()],d.prototype,"swapTransaction",void 0);g([s()],d.prototype,"sourceToken",void 0);g([s()],d.prototype,"sourceTokenAmount",void 0);g([s()],d.prototype,"sourceTokenPriceInUSD",void 0);g([s()],d.prototype,"toToken",void 0);g([s()],d.prototype,"toTokenAmount",void 0);g([s()],d.prototype,"toTokenPriceInUSD",void 0);g([s()],d.prototype,"caipNetwork",void 0);g([s()],d.prototype,"balanceSymbol",void 0);g([s()],d.prototype,"inputError",void 0);g([s()],d.prototype,"loadingQuote",void 0);g([s()],d.prototype,"loadingApprovalTransaction",void 0);g([s()],d.prototype,"loadingBuildTransaction",void 0);g([s()],d.prototype,"loadingTransaction",void 0);d=g([P("w3m-swap-preview-view")],d);const oe=A` + :host { + height: 60px; + min-height: 60px; + } + + :host > wui-flex { + cursor: pointer; + height: 100%; + display: flex; + column-gap: var(--wui-spacing-s); + padding: var(--wui-spacing-xs); + padding-right: var(--wui-spacing-l); + width: 100%; + background-color: transparent; + border-radius: var(--wui-border-radius-xs); + color: var(--wui-color-fg-250); + transition: + background-color var(--wui-ease-out-power-1) var(--wui-duration-lg), + opacity var(--wui-ease-out-power-1) var(--wui-duration-lg); + will-change: background-color, opacity; + } + + @media (hover: hover) and (pointer: fine) { + :host > wui-flex:hover { + background-color: var(--wui-color-gray-glass-002); + } + + :host > wui-flex:active { + background-color: var(--wui-color-gray-glass-005); + } + } + + :host([disabled]) > wui-flex { + opacity: 0.6; + } + + :host([disabled]) > wui-flex:hover { + background-color: transparent; + } + + :host > wui-flex > wui-flex { + flex: 1; + } + + :host > wui-flex > wui-image, + :host > wui-flex > .token-item-image-placeholder { + width: 40px; + max-width: 40px; + height: 40px; + border-radius: var(--wui-border-radius-3xl); + position: relative; + } + + :host > wui-flex > .token-item-image-placeholder { + display: flex; + align-items: center; + justify-content: center; + } + + :host > wui-flex > wui-image::after, + :host > wui-flex > .token-item-image-placeholder::after { + position: absolute; + content: ''; + inset: 0; + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + border-radius: var(--wui-border-radius-l); + } + + button > wui-icon-box[data-variant='square-blue'] { + border-radius: var(--wui-border-radius-3xs); + position: relative; + border: none; + width: 36px; + height: 36px; + } +`;var $=function(l,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(l,e,i,n);else for(var c=l.length-1;c>=0;c--)(a=l[c])&&(t=(r<3?a(t):r>3?a(e,i,t):a(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let y=class extends C{constructor(){super(),this.observer=new IntersectionObserver(()=>{}),this.imageSrc=void 0,this.name=void 0,this.symbol=void 0,this.price=void 0,this.amount=void 0,this.visible=!1,this.imageError=!1,this.observer=new IntersectionObserver(e=>{e.forEach(i=>{i.isIntersecting?this.visible=!0:this.visible=!1})},{threshold:.1})}firstUpdated(){this.observer.observe(this)}disconnectedCallback(){this.observer.disconnect()}render(){if(!this.visible)return null;const e=this.amount&&this.price?D.multiply(this.price,this.amount)?.toFixed(3):null;return u` + + ${this.visualTemplate()} + + + ${this.name} + ${e?u` + + $${x.formatNumberToLocalString(e,3)} + + `:null} + + + ${this.symbol} + ${this.amount?u` + ${x.formatNumberToLocalString(this.amount,3)} + `:null} + + + + `}visualTemplate(){return this.imageError?u` + + `:this.imageSrc?u``:null}imageLoadError(){this.imageError=!0}};y.styles=[H,q,oe];$([w()],y.prototype,"imageSrc",void 0);$([w()],y.prototype,"name",void 0);$([w()],y.prototype,"symbol",void 0);$([w()],y.prototype,"price",void 0);$([w()],y.prototype,"amount",void 0);$([s()],y.prototype,"visible",void 0);$([s()],y.prototype,"imageError",void 0);y=$([P("wui-token-list-item")],y);const ne=A` + :host { + --tokens-scroll--top-opacity: 0; + --tokens-scroll--bottom-opacity: 1; + --suggested-tokens-scroll--left-opacity: 0; + --suggested-tokens-scroll--right-opacity: 1; + } + + :host > wui-flex:first-child { + overflow-y: hidden; + overflow-x: hidden; + scrollbar-width: none; + scrollbar-height: none; + } + + :host > wui-flex:first-child::-webkit-scrollbar { + display: none; + } + + wui-loading-hexagon { + position: absolute; + } + + .suggested-tokens-container { + overflow-x: auto; + mask-image: linear-gradient( + to right, + rgba(0, 0, 0, calc(1 - var(--suggested-tokens-scroll--left-opacity))) 0px, + rgba(200, 200, 200, calc(1 - var(--suggested-tokens-scroll--left-opacity))) 1px, + black 50px, + black 90px, + black calc(100% - 90px), + black calc(100% - 50px), + rgba(155, 155, 155, calc(1 - var(--suggested-tokens-scroll--right-opacity))) calc(100% - 1px), + rgba(0, 0, 0, calc(1 - var(--suggested-tokens-scroll--right-opacity))) 100% + ); + } + + .suggested-tokens-container::-webkit-scrollbar { + display: none; + } + + .tokens-container { + border-top: 1px solid var(--wui-color-gray-glass-005); + height: 100%; + max-height: 390px; + } + + .tokens { + width: 100%; + overflow-y: auto; + mask-image: linear-gradient( + to bottom, + rgba(0, 0, 0, calc(1 - var(--tokens-scroll--top-opacity))) 0px, + rgba(200, 200, 200, calc(1 - var(--tokens-scroll--top-opacity))) 1px, + black 50px, + black 90px, + black calc(100% - 90px), + black calc(100% - 50px), + rgba(155, 155, 155, calc(1 - var(--tokens-scroll--bottom-opacity))) calc(100% - 1px), + rgba(0, 0, 0, calc(1 - var(--tokens-scroll--bottom-opacity))) 100% + ); + } + + .network-search-input, + .select-network-button { + height: 40px; + } + + .select-network-button { + border: none; + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; + gap: var(--wui-spacing-xs); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-005); + background-color: transparent; + border-radius: var(--wui-border-radius-xxs); + padding: var(--wui-spacing-xs); + align-items: center; + transition: background-color 0.2s linear; + } + + .select-network-button:hover { + background-color: var(--wui-color-gray-glass-002); + } + + .select-network-button > wui-image { + width: 26px; + height: 26px; + border-radius: var(--wui-border-radius-xs); + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010); + } +`;var S=function(l,e,i,n){var r=arguments.length,t=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(l,e,i,n);else for(var c=l.length-1;c>=0;c--)(a=l[c])&&(t=(r<3?a(t):r>3?a(e,i,t):a(e,i))||t);return r>3&&t&&Object.defineProperty(e,i,t),t};let k=class extends C{constructor(){super(),this.unsubscribe=[],this.targetToken=T.state.data?.target,this.sourceToken=o.state.sourceToken,this.sourceTokenAmount=o.state.sourceTokenAmount,this.toToken=o.state.toToken,this.myTokensWithBalance=o.state.myTokensWithBalance,this.popularTokens=o.state.popularTokens,this.searchValue="",this.unsubscribe.push(o.subscribe(e=>{this.sourceToken=e.sourceToken,this.toToken=e.toToken,this.myTokensWithBalance=e.myTokensWithBalance}))}updated(){this.renderRoot?.querySelector(".suggested-tokens-container")?.addEventListener("scroll",this.handleSuggestedTokensScroll.bind(this)),this.renderRoot?.querySelector(".tokens")?.addEventListener("scroll",this.handleTokenListScroll.bind(this))}disconnectedCallback(){super.disconnectedCallback();const e=this.renderRoot?.querySelector(".suggested-tokens-container"),i=this.renderRoot?.querySelector(".tokens");e?.removeEventListener("scroll",this.handleSuggestedTokensScroll.bind(this)),i?.removeEventListener("scroll",this.handleTokenListScroll.bind(this)),clearInterval(this.interval)}render(){return u` + + ${this.templateSearchInput()} ${this.templateSuggestedTokens()} ${this.templateTokens()} + + `}onSelectToken(e){this.targetToken==="sourceToken"?o.setSourceToken(e):(o.setToToken(e),this.sourceToken&&this.sourceTokenAmount&&o.swapTokens()),T.goBack()}templateSearchInput(){return u` + + + + `}templateTokens(){const e=this.myTokensWithBalance?Object.values(this.myTokensWithBalance):[],i=this.popularTokens?this.popularTokens:[],n=this.filterTokensWithText(e,this.searchValue),r=this.filterTokensWithText(i,this.searchValue);return u` + + + ${n?.length>0?u` + + Your tokens + + ${n.map(t=>{const a=t.symbol===this.sourceToken?.symbol||t.symbol===this.toToken?.symbol;return u` + {a||this.onSelectToken(t)}} + > + + `})} + `:null} + + + Tokens + + ${r?.length>0?r.map(t=>u` + this.onSelectToken(t)} + > + + `):null} + + + `}templateSuggestedTokens(){const e=o.state.suggestedTokens?o.state.suggestedTokens.slice(0,8):null;return e?u` + + ${e.map(i=>u` + this.onSelectToken(i)} + > + + `)} + + `:null}onSearchInputChange(e){this.searchValue=e.detail}handleSuggestedTokensScroll(){const e=this.renderRoot?.querySelector(".suggested-tokens-container");e&&(e.style.setProperty("--suggested-tokens-scroll--left-opacity",L.interpolate([0,100],[0,1],e.scrollLeft).toString()),e.style.setProperty("--suggested-tokens-scroll--right-opacity",L.interpolate([0,100],[0,1],e.scrollWidth-e.scrollLeft-e.offsetWidth).toString()))}handleTokenListScroll(){const e=this.renderRoot?.querySelector(".tokens");e&&(e.style.setProperty("--tokens-scroll--top-opacity",L.interpolate([0,100],[0,1],e.scrollTop).toString()),e.style.setProperty("--tokens-scroll--bottom-opacity",L.interpolate([0,100],[0,1],e.scrollHeight-e.scrollTop-e.offsetHeight).toString()))}filterTokensWithText(e,i){return e.filter(n=>`${n.symbol} ${n.name} ${n.address}`.toLowerCase().includes(i.toLowerCase()))}};k.styles=ne;S([s()],k.prototype,"interval",void 0);S([s()],k.prototype,"targetToken",void 0);S([s()],k.prototype,"sourceToken",void 0);S([s()],k.prototype,"sourceTokenAmount",void 0);S([s()],k.prototype,"toToken",void 0);S([s()],k.prototype,"myTokensWithBalance",void 0);S([s()],k.prototype,"popularTokens",void 0);S([s()],k.prototype,"searchValue",void 0);k=S([P("w3m-swap-select-token-view")],k);export{d as W3mSwapPreviewView,k as W3mSwapSelectTokenView,p as W3mSwapView}; diff --git a/dist/assets/telegram-APKTNwpu.js b/dist/assets/telegram-APKTNwpu.js new file mode 100644 index 0000000..2127aba --- /dev/null +++ b/dist/assets/telegram-APKTNwpu.js @@ -0,0 +1,16 @@ +import{b as t}from"./index-Cr5N_0pd.js";const l=t` + + + + + + + + + + + + + + +`;export{l as telegramSvg}; diff --git a/dist/assets/three-dots-8jGyRbgm.js b/dist/assets/three-dots-8jGyRbgm.js new file mode 100644 index 0000000..b2ea6ed --- /dev/null +++ b/dist/assets/three-dots-8jGyRbgm.js @@ -0,0 +1,5 @@ +import{b as t}from"./index-Cr5N_0pd.js";const l=t` + + + +`;export{l as threeDotsSvg}; diff --git a/dist/assets/transactions-QUhMMh8E.js b/dist/assets/transactions-QUhMMh8E.js new file mode 100644 index 0000000..75e578f --- /dev/null +++ b/dist/assets/transactions-QUhMMh8E.js @@ -0,0 +1,16 @@ +import{i as f,a,x as d,c as u}from"./index-Cr5N_0pd.js";const w=f` + :host > wui-flex:first-child { + height: 500px; + overflow-y: auto; + overflow-x: hidden; + scrollbar-width: none; + } + + :host > wui-flex:first-child::-webkit-scrollbar { + display: none; + } +`;var m=function(n,t,i,l){var o=arguments.length,e=o<3?t:l===null?l=Object.getOwnPropertyDescriptor(t,i):l,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")e=Reflect.decorate(n,t,i,l);else for(var c=n.length-1;c>=0;c--)(r=n[c])&&(e=(o<3?r(e):o>3?r(t,i,e):r(t,i))||e);return o>3&&e&&Object.defineProperty(t,i,e),e};let s=class extends a{render(){return d` + + + + `}};s.styles=w;s=m([u("w3m-transactions-view")],s);export{s as W3mTransactionsView}; diff --git a/dist/assets/twitch-BUKiRB8R.js b/dist/assets/twitch-BUKiRB8R.js new file mode 100644 index 0000000..008291e --- /dev/null +++ b/dist/assets/twitch-BUKiRB8R.js @@ -0,0 +1,18 @@ +import{b as l}from"./index-Cr5N_0pd.js";const i=l` + + + + + + + + + + + + + +`;export{i as twitchSvg}; diff --git a/dist/assets/twitterIcon-CzR_RgAK.js b/dist/assets/twitterIcon-CzR_RgAK.js new file mode 100644 index 0000000..2de022a --- /dev/null +++ b/dist/assets/twitterIcon-CzR_RgAK.js @@ -0,0 +1,6 @@ +import{b as o}from"./index-Cr5N_0pd.js";const c=o` + +`;export{c as twitterIconSvg}; diff --git a/dist/assets/ui-CTdGiFlJ.js b/dist/assets/ui-CTdGiFlJ.js new file mode 100644 index 0000000..cfe7b68 --- /dev/null +++ b/dist/assets/ui-CTdGiFlJ.js @@ -0,0 +1,246 @@ +import{K as g,ar as P,as as b,at as j,Q as k,au as m,W as U,Y as K,av as L,aw as x,i as z,a as N,x as c,a5 as O,c as $,T as f,aj as w,R as v,a7 as M,aa as u}from"./index-Cr5N_0pd.js";import{W3mEmailOtpWidget as R}from"./email-OHUMhOV6.js";class V{constructor(e){this.expiration=e.expiration,this.getNonce=e.getNonce,this.getRequestId=e.getRequestId,this.domain=e.domain,this.uri=e.uri,this.statement=e.statement,this.resources=e.resources}async createMessage(e){const t={accountAddress:e.accountAddress,chainId:e.chainId,version:this.version,domain:this.domain,uri:this.uri,statement:this.statement,resources:this.resources,nonce:await this.getNonce(e),requestId:await this.getRequestId?.(),expirationTime:this.getExpirationTime(e),issuedAt:this.getIssuedAt(),notBefore:this.getNotBefore(e)};return Object.assign(t,{toString:()=>this.stringify(t)})}getExpirationTime({notBefore:e}){if(typeof this.expiration>"u")return;const t=e?new Date(e).getTime():Date.now();return this.stringifyDate(new Date(t+this.expiration))}getNotBefore({notBefore:e}){return e?this.stringifyDate(new Date(e)):void 0}getIssuedAt(){return this.stringifyDate(new Date)}stringifyDate(e){return e.toISOString()}}class X extends V{constructor({clearChainIdNamespace:e,...t}){super(t),this.version="1",this.clearChainIdNamespace=e||!1}getNetworkName(e){const t=g.getAllRequestedCaipNetworks();return P.getNetworkNameByCaipNetworkId(t,e)}stringify(e){const t=this.clearChainIdNamespace?e.chainId.split(":")[1]:e.chainId,i=this.getNetworkName(e.chainId);return[`${e.domain} wants you to sign in with your ${i} account:`,e.accountAddress,e.statement?` +${e.statement} +`:"",`URI: ${e.uri}`,`Version: ${e.version}`,`Chain ID: ${t}`,`Nonce: ${e.nonce}`,e.issuedAt&&`Issued At: ${e.issuedAt}`,e.expirationTime&&`Expiration Time: ${e.expirationTime}`,e.notBefore&&`Not Before: ${e.notBefore}`,e.requestId&&`Request ID: ${e.requestId}`,e.resources?.length&&e.resources.reduce((s,n)=>`${s} +- ${n}`,"Resources:")].filter(s=>typeof s=="string").join(` +`).trim()}}class T{constructor(e={}){this.otpUuid=null,this.listeners={sessionChanged:[]},this.localAuthStorageKey=e.localAuthStorageKey||b.SIWX_AUTH_TOKEN,this.localNonceStorageKey=e.localNonceStorageKey||b.SIWX_NONCE_TOKEN,this.required=e.required??!0,this.messenger=new X({domain:typeof document>"u"?"Unknown Domain":document.location.host,uri:typeof document>"u"?"Unknown URI":document.location.href,getNonce:this.getNonce.bind(this),clearChainIdNamespace:!1})}async createMessage(e){return this.messenger.createMessage(e)}async addSession(e){const t=await this.request({method:"POST",key:"authenticate",body:{data:e.data,message:e.message,signature:e.signature,clientId:this.getClientId(),walletInfo:this.getWalletInfo()},headers:["nonce","otp"]});this.setStorageToken(t.token,this.localAuthStorageKey),this.emit("sessionChanged",e),this.setAppKitAccountUser(B(t.token)),this.otpUuid=null}async getSessions(e,t){try{if(!this.getStorageToken(this.localAuthStorageKey))return[];const i=await this.request({method:"GET",key:"me",query:{},headers:["auth"]});if(!i)return[];const s=i.address.toLowerCase()===t.toLowerCase(),n=i.caip2Network===e;if(!s||!n)return[];const a={data:{accountAddress:i.address,chainId:i.caip2Network},message:"",signature:""};return this.emit("sessionChanged",a),this.setAppKitAccountUser(i),[a]}catch{return[]}}async revokeSession(e,t){return Promise.resolve(this.clearStorageTokens())}async setSessions(e){if(e.length===0)this.clearStorageTokens();else{const t=e.find(i=>i.data.chainId===j()?.caipNetworkId)||e[0];await this.addSession(t)}}getRequired(){return this.required}async getSessionAccount(){if(!this.getStorageToken(this.localAuthStorageKey))throw new Error("Not authenticated");return this.request({method:"GET",key:"me",body:void 0,query:{includeAppKitAccount:!0},headers:["auth"]})}async setSessionAccountMetadata(e=null){if(!this.getStorageToken(this.localAuthStorageKey))throw new Error("Not authenticated");return this.request({method:"PUT",key:"account-metadata",body:{metadata:e},headers:["auth"]})}on(e,t){return this.listeners[e].push(t),()=>{this.listeners[e]=this.listeners[e].filter(i=>i!==t)}}removeAllListeners(){Object.keys(this.listeners).forEach(t=>{this.listeners[t]=[]})}async requestEmailOtp({email:e,account:t}){const i=await this.request({method:"POST",key:"otp",body:{email:e,account:t}});return this.otpUuid=i.uuid,this.messenger.resources=[`email:${e}`],i}confirmEmailOtp({code:e}){return this.request({method:"PUT",key:"otp",body:{code:e},headers:["otp"]})}async request({method:e,key:t,query:i,body:s,headers:n}){const{projectId:a,st:o,sv:W}=this.getSDKProperties(),p=new URL(`${k.W3M_API_URL}/auth/v1/${String(t)}`);p.searchParams.set("projectId",a),p.searchParams.set("st",o),p.searchParams.set("sv",W),i&&Object.entries(i).forEach(([h,C])=>p.searchParams.set(h,String(C)));const y=await fetch(p,{method:e,body:s?JSON.stringify(s):void 0,headers:Array.isArray(n)?n.reduce((h,C)=>{switch(C){case"nonce":h["x-nonce-jwt"]=`Bearer ${this.getStorageToken(this.localNonceStorageKey)}`;break;case"auth":h.Authorization=`Bearer ${this.getStorageToken(this.localAuthStorageKey)}`;break;case"otp":this.otpUuid&&(h["x-otp"]=this.otpUuid);break}return h},{}):void 0});if(!y.ok)throw new Error(await y.text());return y.headers.get("content-type")?.includes("application/json")?y.json():null}getStorageToken(e){return m.getItem(e)}setStorageToken(e,t){m.setItem(t,e)}clearStorageTokens(){this.otpUuid=null,m.removeItem(this.localAuthStorageKey),m.removeItem(this.localNonceStorageKey),this.emit("sessionChanged",void 0)}async getNonce(){const{nonce:e,token:t}=await this.request({method:"GET",key:"nonce"});return this.setStorageToken(t,this.localNonceStorageKey),e}getClientId(){return U.state.clientId}getWalletInfo(){const{connectedWalletInfo:e}=K.state;if(!e)return;if("social"in e){const n=e.social,a=e.identifier;return{type:"social",social:n,identifier:a}}const{name:t,icon:i}=e;let s="unknown";switch(e.type){case x.CONNECTOR_TYPE_EXTERNAL:case x.CONNECTOR_TYPE_INJECTED:case x.CONNECTOR_TYPE_ANNOUNCED:s="extension";break;case x.CONNECTOR_TYPE_WALLET_CONNECT:s="walletconnect";break;default:s="unknown"}return{type:s,name:t,icon:i}}getSDKProperties(){return L._getSdkProperties()}emit(e,t){this.listeners[e].forEach(i=>i(t))}setAppKitAccountUser(e){const{email:t}=e;t&&Object.values(k.CHAIN).forEach(i=>{g.setAccountProp("user",{email:t},i)})}}function B(r){const e=r.split(".");if(e.length!==3)throw new Error("Invalid token");const t=e[1];if(typeof t!="string")throw new Error("Invalid token");const i=t.replace(/-/gu,"+").replace(/_/gu,"/"),s=i.padEnd(i.length+(4-i.length%4)%4,"=");return JSON.parse(atob(s))}const A=z` + .hero { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: var(--wui-spacing-3xs); + + transition-property: margin, height; + transition-duration: var(--wui-duration-md); + transition-timing-function: var(--wui-ease-out-power-1); + margin-top: -100px; + + &[data-state='loading'] { + margin-top: 0px; + } + + position: relative; + &:after { + content: ''; + position: absolute; + bottom: 0; + height: 252px; + width: 360px; + background: radial-gradient( + 96.11% 53.95% at 50% 51.28%, + transparent 0%, + color-mix(in srgb, var(--wui-color-bg-100) 5%, transparent) 49%, + color-mix(in srgb, var(--wui-color-bg-100) 65%, transparent) 99.43% + ); + } + } + + .hero-main-icon { + width: 176px; + transition-property: background-color; + transition-duration: var(--wui-duration-lg); + transition-timing-function: var(--wui-ease-out-power-1); + + &[data-state='loading'] { + width: 56px; + } + } + + .hero-row { + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; + gap: var(--wui-spacing-3xs); + flex-wrap: nowrap; + min-width: fit-content; + + &:nth-child(1) { + transform: translateX(-30px); + } + + &:nth-child(2) { + transform: translateX(30px); + } + + &:nth-child(4) { + transform: translateX(40px); + } + + transition-property: height; + transition-duration: var(--wui-duration-md); + transition-timing-function: var(--wui-ease-out-power-1); + height: 68px; + + &[data-state='loading'] { + height: 0px; + } + } + + .hero-row-icon { + opacity: 0.1; + transition-property: opacity; + transition-duration: var(--wui-duration-md); + transition-timing-function: var(--wui-ease-out-power-1); + + &[data-state='loading'] { + opacity: 0; + } + } + + .email-sufixes { + display: flex; + flex-direction: row; + gap: var(--wui-spacing-3xs); + overflow-x: auto; + max-width: 100%; + margin-top: var(--wui-spacing-s); + margin-bottom: calc(-1 * var(--wui-spacing-m)); + padding-bottom: var(--wui-spacing-m); + margin-left: calc(-1 * var(--wui-spacing-m)); + margin-right: calc(-1 * var(--wui-spacing-m)); + padding-left: var(--wui-spacing-m); + padding-right: var(--wui-spacing-m); + + &::-webkit-scrollbar { + display: none; + } + } + + .recent-emails { + display: flex; + flex-direction: column; + padding: var(--wui-spacing-s) 0; + border-top: 1px solid var(--wui-color-gray-glass-005); + border-bottom: 1px solid var(--wui-color-gray-glass-005); + } + + .recent-emails-heading { + margin-bottom: var(--wui-spacing-s); + } + + .recent-emails-list-item { + --wui-color-gray-glass-002: transparent; + } +`;var _=function(r,e,t,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,i);else for(var o=r.length-1;o>=0;o--)(a=r[o])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n};const H=["@gmail.com","@outlook.com","@yahoo.com","@hotmail.com","@aol.com","@icloud.com","@zoho.com"];let E=class extends N{constructor(){super(...arguments),this.email=""}render(){const e=H.filter(this.filter.bind(this)).map(this.item.bind(this));return e.length===0?null:c``}filter(e){if(!this.email)return!1;const t=this.email.split("@");if(t.length<2)return!0;const i=t.pop();return e.includes(i)&&e!==`@${i}`}item(e){return c`{const i=this.email.split("@");i.length>1&&i.pop();const s=i[0]+e;this.dispatchEvent(new CustomEvent("change",{detail:s,bubbles:!0,composed:!0}))}} + >${e}`}};E.styles=[A];_([O()],E.prototype,"email",void 0);E=_([$("w3m-email-suffixes-widget")],E);var q=function(r,e,t,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,i);else for(var o=r.length-1;o>=0;o--)(a=r[o])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n};let S=class extends N{constructor(){super(...arguments),this.emails=[]}render(){return this.emails.length===0?null:c`
+ Recently used emails + ${this.emails.map(this.item.bind(this))} +
`}item(e){return c`{this.dispatchEvent(new CustomEvent("select",{detail:e,bubbles:!0,composed:!0}))}} + ?chevron=${!0} + icon="mail" + iconVariant="overlay" + class="recent-emails-list-item" + > + ${e} + `}};S.styles=[A];q([O()],S.prototype,"emails",void 0);S=q([$("w3m-recent-emails-widget")],S);var d=function(r,e,t,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,i);else for(var o=r.length-1;o>=0;o--)(a=r[o])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n};let l=class extends N{constructor(){super(...arguments),this.email=f.state.data?.email??g.getAccountData()?.user?.email??"",this.address=g.getAccountData()?.address??"",this.loading=!1,this.appName=w.state.metadata?.name??"AppKit",this.siwx=w.state.siwx,this.isRequired=Array.isArray(w.state.remoteFeatures?.emailCapture)&&w.state.remoteFeatures?.emailCapture.includes("required"),this.recentEmails=this.getRecentEmails()}connectedCallback(){(!this.siwx||!(this.siwx instanceof T))&&v.showError("ReownAuthentication is not initialized."),super.connectedCallback()}firstUpdated(){this.loading=!1,this.recentEmails=this.getRecentEmails(),this.email&&this.onSubmit()}render(){return c` + + ${this.hero()} ${this.paragraph()} ${this.emailInput()} ${this.recentEmailsWidget()} + ${this.footerActions()} + + `}hero(){return c` +
+ ${this.heroRow(["id","mail","wallet","x","solana","qrCode"])} + ${this.heroRow(["mail","farcaster","wallet","discord","mobile","qrCode"])} +
+ ${this.heroIcon("github")} ${this.heroIcon("bank")} + + + ${this.heroIcon("id")} ${this.heroIcon("card")} +
+ ${this.heroRow(["google","id","github","verify","apple","mobile"])} +
+ `}heroRow(e){return c` +
+ ${e.map(this.heroIcon.bind(this))} +
+ `}heroIcon(e){return c` + + + `}paragraph(){return this.loading?c` + We are verifying your account with email + ${this.email} and address + + ${M.getTruncateString({string:this.address,charsEnd:4,charsStart:4,truncate:"middle"})} , please wait a moment. + `:this.isRequired?c` + + ${this.appName} requires your email for authentication. + + `:c` + + + ${this.appName} would like to collect your email. + + + + Don't worry, it's optional—you can skip this step. + + + `}emailInput(){if(this.loading)return null;const e=i=>{i.key==="Enter"&&this.onSubmit()},t=i=>{this.email=i.detail};return c` + + + + + + `}recentEmailsWidget(){if(this.recentEmails.length===0||this.loading)return null;const e=t=>{this.email=t.detail,this.onSubmit()};return c` + + `}footerActions(){return c` + + ${this.isRequired?null:c`Skip this step`} + + + Continue + + + `}async onSubmit(){const e=g.getActiveCaipAddress();if(!e)throw new Error("Account is not connected.");if(!this.isValidEmail(this.email)){v.showError("Please provide a valid email.");return}try{this.loading=!0;const t=await this.siwx.requestEmailOtp({email:this.email,account:e});this.pushRecentEmail(this.email),t.uuid===null?f.replace("SIWXSignMessage"):f.replace("DataCaptureOtpConfirm",{email:this.email})}catch{v.showError("Failed to send email OTP"),this.loading=!1}}onSkip(){f.replace("SIWXSignMessage")}getRecentEmails(){const e=m.getItem(b.RECENT_EMAILS);return(e?e.split(","):[]).filter(this.isValidEmail.bind(this)).slice(0,3)}pushRecentEmail(e){const t=this.getRecentEmails(),i=Array.from(new Set([e,...t])).slice(0,3);m.setItem(b.RECENT_EMAILS,i.join(","))}isValidEmail(e){return/^\S+@\S+\.\S+$/u.test(e)}};l.styles=[A];d([u()],l.prototype,"email",void 0);d([u()],l.prototype,"address",void 0);d([u()],l.prototype,"loading",void 0);d([u()],l.prototype,"appName",void 0);d([u()],l.prototype,"siwx",void 0);d([u()],l.prototype,"isRequired",void 0);d([u()],l.prototype,"recentEmails",void 0);l=d([$("w3m-data-capture-view")],l);var D=function(r,e,t,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,i);else for(var o=r.length-1;o>=0;o--)(a=r[o])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n};let I=class extends R{constructor(){super(...arguments),this.siwx=w.state.siwx,this.onOtpSubmit=async e=>{await this.siwx.confirmEmailOtp({code:e}),f.replace("SIWXSignMessage")},this.onOtpResend=async e=>{const t=g.getAccountData();if(!t?.caipAddress)throw new Error("No account data found");await this.siwx.requestEmailOtp({email:e,account:t.caipAddress})}}connectedCallback(){(!this.siwx||!(this.siwx instanceof T))&&v.showError("ReownAuthentication is not initialized."),super.connectedCallback()}shouldSubmitOnOtpChange(){return this.otp.length===R.OTP_LENGTH}};D([u()],I.prototype,"siwx",void 0);I=D([$("w3m-data-capture-otp-confirm-view")],I);export{I as W3mDataCaptureOtpConfirmView,l as W3mDataCaptureView,E as W3mEmailSuffixesWidget,S as W3mRecentEmailsWidget}; diff --git a/dist/assets/user-BSr3AuAa.js b/dist/assets/user-BSr3AuAa.js new file mode 100644 index 0000000..5000493 --- /dev/null +++ b/dist/assets/user-BSr3AuAa.js @@ -0,0 +1,3 @@ +import{b as C}from"./index-Cr5N_0pd.js";const l=C` + +`;export{l as userSvg}; diff --git a/dist/assets/verify-BjYfOgD5.js b/dist/assets/verify-BjYfOgD5.js new file mode 100644 index 0000000..eaf781e --- /dev/null +++ b/dist/assets/verify-BjYfOgD5.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const c=l` + +`;export{c as verifySvg}; diff --git a/dist/assets/verify-filled-C34Ypr-X.js b/dist/assets/verify-filled-C34Ypr-X.js new file mode 100644 index 0000000..0a5c21a --- /dev/null +++ b/dist/assets/verify-filled-C34Ypr-X.js @@ -0,0 +1,8 @@ +import{b as l}from"./index-Cr5N_0pd.js";const o=l` + +`;export{o as verifyFilledSvg}; diff --git a/dist/assets/w3m-modal-BNMiKa3F.js b/dist/assets/w3m-modal-BNMiKa3F.js new file mode 100644 index 0000000..914964f --- /dev/null +++ b/dist/assets/w3m-modal-BNMiKa3F.js @@ -0,0 +1,467 @@ +import{T as c,ap as p,aI as T,$ as ae,i as v,a3 as B,c as f,a as y,x as l,a5 as u,Z as I,aa as d,a4 as se,aJ as ne,K as h,a6 as L,aH as re,an as U,a0 as V,aj as W,a9 as H,O as z,Y,R as S,av as A,a8 as ce,a7 as le,aK as de,aC as ue,L as pe,Q as he}from"./index-Cr5N_0pd.js";const F={isUnsupportedChainView(){return c.state.view==="UnsupportedChain"||c.state.view==="SwitchNetwork"&&c.state.history.includes("UnsupportedChain")},async safeClose(){if(this.isUnsupportedChainView()){p.shake();return}if(await T.isSIWXCloseDisabled()){p.shake();return}(c.state.view==="DataCapture"||c.state.view==="DataCaptureOtpConfirm")&&ae.disconnect(),p.close()}},we=v` + :host { + display: block; + border-radius: clamp(0px, var(--wui-border-radius-l), 44px); + box-shadow: 0 0 0 1px var(--wui-color-gray-glass-005); + background-color: var(--wui-color-modal-bg); + overflow: hidden; + } + + :host([data-embedded='true']) { + box-shadow: + 0 0 0 1px var(--wui-color-gray-glass-005), + 0px 4px 12px 4px var(--w3m-card-embedded-shadow-color); + } +`;var me=function(n,e,t,i){var a=arguments.length,o=a<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,i);else for(var r=n.length-1;r>=0;r--)(s=n[r])&&(o=(a<3?s(o):a>3?s(e,t,o):s(e,t))||o);return a>3&&o&&Object.defineProperty(e,t,o),o};let M=class extends y{render(){return l``}};M.styles=[B,we];M=me([f("wui-card")],M);const fe=v` + :host { + display: flex; + align-items: center; + justify-content: center; + padding: var(--wui-spacing-s); + border-radius: var(--wui-border-radius-s); + border: 1px solid var(--wui-color-dark-glass-100); + box-sizing: border-box; + background-color: var(--wui-color-bg-325); + box-shadow: 0px 0px 16px 0px rgba(0, 0, 0, 0.25); + } + + wui-flex { + width: 100%; + } + + wui-text { + word-break: break-word; + flex: 1; + } + + .close { + cursor: pointer; + } + + .icon-box { + height: 40px; + width: 40px; + border-radius: var(--wui-border-radius-3xs); + background-color: var(--local-icon-bg-value); + } +`;var $=function(n,e,t,i){var a=arguments.length,o=a<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,i);else for(var r=n.length-1;r>=0;r--)(s=n[r])&&(o=(a<3?s(o):a>3?s(e,t,o):s(e,t))||o);return a>3&&o&&Object.defineProperty(e,t,o),o};let k=class extends y{constructor(){super(...arguments),this.message="",this.backgroundColor="accent-100",this.iconColor="accent-100",this.icon="info"}render(){return this.style.cssText=` + --local-icon-bg-value: var(--wui-color-${this.backgroundColor}); + `,l` + + + + + + ${this.message} + + + + `}onClose(){I.close()}};k.styles=[B,fe];$([u()],k.prototype,"message",void 0);$([u()],k.prototype,"backgroundColor",void 0);$([u()],k.prototype,"iconColor",void 0);$([u()],k.prototype,"icon",void 0);k=$([f("wui-alertbar")],k);const be=v` + :host { + display: block; + position: absolute; + top: var(--wui-spacing-s); + left: var(--wui-spacing-l); + right: var(--wui-spacing-l); + opacity: 0; + pointer-events: none; + } +`;var J=function(n,e,t,i){var a=arguments.length,o=a<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,i);else for(var r=n.length-1;r>=0;r--)(s=n[r])&&(o=(a<3?s(o):a>3?s(e,t,o):s(e,t))||o);return a>3&&o&&Object.defineProperty(e,t,o),o};const ge={info:{backgroundColor:"fg-350",iconColor:"fg-325",icon:"info"},success:{backgroundColor:"success-glass-reown-020",iconColor:"success-125",icon:"checkmark"},warning:{backgroundColor:"warning-glass-reown-020",iconColor:"warning-100",icon:"warningCircle"},error:{backgroundColor:"error-glass-reown-020",iconColor:"error-125",icon:"exclamationTriangle"}};let O=class extends y{constructor(){super(),this.unsubscribe=[],this.open=I.state.open,this.onOpen(!0),this.unsubscribe.push(I.subscribeKey("open",e=>{this.open=e,this.onOpen(!1)}))}disconnectedCallback(){this.unsubscribe.forEach(e=>e())}render(){const{message:e,variant:t}=I.state,i=ge[t];return l` + + `}onOpen(e){this.open?(this.animate([{opacity:0,transform:"scale(0.85)"},{opacity:1,transform:"scale(1)"}],{duration:150,fill:"forwards",easing:"ease"}),this.style.cssText="pointer-events: auto"):e||(this.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(0.85)"}],{duration:150,fill:"forwards",easing:"ease"}),this.style.cssText="pointer-events: none")}};O.styles=be;J([d()],O.prototype,"open",void 0);O=J([f("w3m-alertbar")],O);const ve=v` + button { + display: block; + display: flex; + align-items: center; + padding: var(--wui-spacing-xxs); + gap: var(--wui-spacing-xxs); + transition: all var(--wui-ease-out-power-1) var(--wui-duration-md); + border-radius: var(--wui-border-radius-xxs); + } + + wui-image { + border-radius: 100%; + width: var(--wui-spacing-xl); + height: var(--wui-spacing-xl); + } + + wui-icon-box { + width: var(--wui-spacing-xl); + height: var(--wui-spacing-xl); + } + + button:hover { + background-color: var(--wui-color-gray-glass-002); + } + + button:active { + background-color: var(--wui-color-gray-glass-005); + } +`;var Q=function(n,e,t,i){var a=arguments.length,o=a<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,i);else for(var r=n.length-1;r>=0;r--)(s=n[r])&&(o=(a<3?s(o):a>3?s(e,t,o):s(e,t))||o);return a>3&&o&&Object.defineProperty(e,t,o),o};let P=class extends y{constructor(){super(...arguments),this.imageSrc=""}render(){return l``}imageTemplate(){return this.imageSrc?l``:l``}};P.styles=[B,se,ne,ve];Q([u()],P.prototype,"imageSrc",void 0);P=Q([f("wui-select")],P);const ye=v` + :host { + height: 64px; + } + + wui-text { + text-transform: capitalize; + } + + wui-flex.w3m-header-title { + transform: translateY(0); + opacity: 1; + } + + wui-flex.w3m-header-title[view-direction='prev'] { + animation: + slide-down-out 120ms forwards var(--wui-ease-out-power-2), + slide-down-in 120ms forwards var(--wui-ease-out-power-2); + animation-delay: 0ms, 200ms; + } + + wui-flex.w3m-header-title[view-direction='next'] { + animation: + slide-up-out 120ms forwards var(--wui-ease-out-power-2), + slide-up-in 120ms forwards var(--wui-ease-out-power-2); + animation-delay: 0ms, 200ms; + } + + wui-icon-link[data-hidden='true'] { + opacity: 0 !important; + pointer-events: none; + } + + @keyframes slide-up-out { + from { + transform: translateY(0px); + opacity: 1; + } + to { + transform: translateY(3px); + opacity: 0; + } + } + + @keyframes slide-up-in { + from { + transform: translateY(-3px); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } + } + + @keyframes slide-down-out { + from { + transform: translateY(0px); + opacity: 1; + } + to { + transform: translateY(-3px); + opacity: 0; + } + } + + @keyframes slide-down-in { + from { + transform: translateY(3px); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } + } +`;var b=function(n,e,t,i){var a=arguments.length,o=a<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,i);else for(var r=n.length-1;r>=0;r--)(s=n[r])&&(o=(a<3?s(o):a>3?s(e,t,o):s(e,t))||o);return a>3&&o&&Object.defineProperty(e,t,o),o};const Ce=["SmartSessionList"];function K(){const n=c.state.data?.connector?.name,e=c.state.data?.wallet?.name,t=c.state.data?.network?.name,i=e??n,a=z.getConnectors();return{Connect:`Connect ${a.length===1&&a[0]?.id==="w3m-email"?"Email":""} Wallet`,Create:"Create Wallet",ChooseAccountName:void 0,Account:void 0,AccountSettings:void 0,AllWallets:"All Wallets",ApproveTransaction:"Approve Transaction",BuyInProgress:"Buy",ConnectingExternal:i??"Connect Wallet",ConnectingWalletConnect:i??"WalletConnect",ConnectingWalletConnectBasic:"WalletConnect",ConnectingSiwe:"Sign In",Convert:"Convert",ConvertSelectToken:"Select token",ConvertPreview:"Preview convert",Downloads:i?`Get ${i}`:"Downloads",EmailLogin:"Email Login",EmailVerifyOtp:"Confirm Email",EmailVerifyDevice:"Register Device",GetWallet:"Get a wallet",Networks:"Choose Network",OnRampProviders:"Choose Provider",OnRampActivity:"Activity",OnRampTokenSelect:"Select Token",OnRampFiatSelect:"Select Currency",Pay:"How you pay",ProfileWallets:"Wallets",SwitchNetwork:t??"Switch Network",Transactions:"Activity",UnsupportedChain:"Switch Network",UpgradeEmailWallet:"Upgrade your Wallet",UpdateEmailWallet:"Edit Email",UpdateEmailPrimaryOtp:"Confirm Current Email",UpdateEmailSecondaryOtp:"Confirm New Email",WhatIsABuy:"What is Buy?",RegisterAccountName:"Choose name",RegisterAccountNameSuccess:"",WalletReceive:"Receive",WalletCompatibleNetworks:"Compatible Networks",Swap:"Swap",SwapSelectToken:"Select token",SwapPreview:"Preview swap",WalletSend:"Send",WalletSendPreview:"Review send",WalletSendSelectToken:"Select Token",WhatIsANetwork:"What is a network?",WhatIsAWallet:"What is a wallet?",ConnectWallets:"Connect wallet",ConnectSocials:"All socials",ConnectingSocial:Y.state.socialProvider?Y.state.socialProvider:"Connect Social",ConnectingMultiChain:"Select chain",ConnectingFarcaster:"Farcaster",SwitchActiveChain:"Switch chain",SmartSessionCreated:void 0,SmartSessionList:"Smart Sessions",SIWXSignMessage:"Sign In",PayLoading:"Payment in progress",DataCapture:"Profile",DataCaptureOtpConfirm:"Confirm Email"}}let w=class extends y{constructor(){super(),this.unsubscribe=[],this.heading=K()[c.state.view],this.network=h.state.activeCaipNetwork,this.networkImage=L.getNetworkImage(this.network),this.showBack=!1,this.prevHistoryLength=1,this.view=c.state.view,this.viewDirection="",this.headerText=K()[c.state.view],this.unsubscribe.push(re.subscribeNetworkImages(()=>{this.networkImage=L.getNetworkImage(this.network)}),c.subscribeKey("view",e=>{setTimeout(()=>{this.view=e,this.headerText=K()[e]},U.ANIMATION_DURATIONS.HeaderText),this.onViewChange(),this.onHistoryChange()}),h.subscribeKey("activeCaipNetwork",e=>{this.network=e,this.networkImage=L.getNetworkImage(this.network)}))}disconnectCallback(){this.unsubscribe.forEach(e=>e())}render(){return l` + + ${this.leftHeaderTemplate()} ${this.titleTemplate()} ${this.rightHeaderTemplate()} + + `}onWalletHelp(){V.sendEvent({type:"track",event:"CLICK_WALLET_HELP"}),c.push("WhatIsAWallet")}async onClose(){await F.safeClose()}rightHeaderTemplate(){const e=W?.state?.features?.smartSessions;return c.state.view!=="Account"||!e?this.closeButtonTemplate():l` + c.push("SmartSessionList")} + data-testid="w3m-header-smart-sessions" + > + ${this.closeButtonTemplate()} + `}closeButtonTemplate(){return l` + + `}titleTemplate(){const e=Ce.includes(this.view);return l` + + ${this.headerText} + ${e?l`Beta`:null} + + `}leftHeaderTemplate(){const{view:e}=c.state,t=e==="Connect",i=W.state.enableEmbedded,a=e==="ApproveTransaction",o=e==="ConnectingSiwe",s=e==="Account",r=W.state.enableNetworkSwitch,E=a||o||t&&i;return s&&r?l``:this.showBack&&!E?l``:l``}onNetworks(){this.isAllowedNetworkSwitch()&&(V.sendEvent({type:"track",event:"CLICK_NETWORKS"}),c.push("Networks"))}isAllowedNetworkSwitch(){const e=h.getAllRequestedCaipNetworks(),t=e?e.length>1:!1,i=e?.find(({id:a})=>a===this.network?.id);return t||!i}getPadding(){return this.heading?["l","2l","l","2l"]:["0","2l","0","2l"]}onViewChange(){const{history:e}=c.state;let t=U.VIEW_DIRECTION.Next;e.length1&&!this.showBack&&t?(await t.animate([{opacity:1},{opacity:0}],{duration:200,fill:"forwards",easing:"ease"}).finished,this.showBack=!0,t.animate([{opacity:0},{opacity:1}],{duration:200,fill:"forwards",easing:"ease"})):e.length<=1&&this.showBack&&t&&(await t.animate([{opacity:1},{opacity:0}],{duration:200,fill:"forwards",easing:"ease"}).finished,this.showBack=!1,t.animate([{opacity:0},{opacity:1}],{duration:200,fill:"forwards",easing:"ease"}))}onGoBack(){c.goBack()}};w.styles=ye;b([d()],w.prototype,"heading",void 0);b([d()],w.prototype,"network",void 0);b([d()],w.prototype,"networkImage",void 0);b([d()],w.prototype,"showBack",void 0);b([d()],w.prototype,"prevHistoryLength",void 0);b([d()],w.prototype,"view",void 0);b([d()],w.prototype,"viewDirection",void 0);b([d()],w.prototype,"headerText",void 0);w=b([f("w3m-header")],w);const ke=v` + :host { + display: flex; + column-gap: var(--wui-spacing-s); + align-items: center; + padding: var(--wui-spacing-xs) var(--wui-spacing-m) var(--wui-spacing-xs) var(--wui-spacing-xs); + border-radius: var(--wui-border-radius-s); + border: 1px solid var(--wui-color-gray-glass-005); + box-sizing: border-box; + background-color: var(--wui-color-bg-175); + box-shadow: + 0px 14px 64px -4px rgba(0, 0, 0, 0.15), + 0px 8px 22px -6px rgba(0, 0, 0, 0.15); + + max-width: 300px; + } + + :host wui-loading-spinner { + margin-left: var(--wui-spacing-3xs); + } +`;var x=function(n,e,t,i){var a=arguments.length,o=a<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,i);else for(var r=n.length-1;r>=0;r--)(s=n[r])&&(o=(a<3?s(o):a>3?s(e,t,o):s(e,t))||o);return a>3&&o&&Object.defineProperty(e,t,o),o};let m=class extends y{constructor(){super(...arguments),this.backgroundColor="accent-100",this.iconColor="accent-100",this.icon="checkmark",this.message="",this.loading=!1,this.iconType="default"}render(){return l` + ${this.templateIcon()} + ${this.message} + `}templateIcon(){return this.loading?l``:this.iconType==="default"?l``:l``}};m.styles=[B,ke];x([u()],m.prototype,"backgroundColor",void 0);x([u()],m.prototype,"iconColor",void 0);x([u()],m.prototype,"icon",void 0);x([u()],m.prototype,"message",void 0);x([u()],m.prototype,"loading",void 0);x([u()],m.prototype,"iconType",void 0);m=x([f("wui-snackbar")],m);const xe=v` + :host { + display: block; + position: absolute; + opacity: 0; + pointer-events: none; + top: 11px; + left: 50%; + width: max-content; + } +`;var Z=function(n,e,t,i){var a=arguments.length,o=a<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,i);else for(var r=n.length-1;r>=0;r--)(s=n[r])&&(o=(a<3?s(o):a>3?s(e,t,o):s(e,t))||o);return a>3&&o&&Object.defineProperty(e,t,o),o};const Se={loading:void 0,success:{backgroundColor:"success-100",iconColor:"success-100",icon:"checkmark"},error:{backgroundColor:"error-100",iconColor:"error-100",icon:"close"}};let R=class extends y{constructor(){super(),this.unsubscribe=[],this.timeout=void 0,this.open=S.state.open,this.unsubscribe.push(S.subscribeKey("open",e=>{this.open=e,this.onOpen()}))}disconnectedCallback(){clearTimeout(this.timeout),this.unsubscribe.forEach(e=>e())}render(){const{message:e,variant:t,svg:i}=S.state,a=Se[t],{icon:o,iconColor:s}=i??a??{};return l` + + `}onOpen(){clearTimeout(this.timeout),this.open?(this.animate([{opacity:0,transform:"translateX(-50%) scale(0.85)"},{opacity:1,transform:"translateX(-50%) scale(1)"}],{duration:150,fill:"forwards",easing:"ease"}),this.timeout&&clearTimeout(this.timeout),S.state.autoClose&&(this.timeout=setTimeout(()=>S.hide(),2500))):this.animate([{opacity:1,transform:"translateX(-50%) scale(1)"},{opacity:0,transform:"translateX(-50%) scale(0.85)"}],{duration:150,fill:"forwards",easing:"ease"})}};R.styles=xe;Z([d()],R.prototype,"open",void 0);R=Z([f("w3m-snackbar")],R);const Ne=v` + :host { + z-index: var(--w3m-z-index); + display: block; + backface-visibility: hidden; + will-change: opacity; + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + pointer-events: none; + opacity: 0; + background-color: var(--wui-cover); + transition: opacity 0.2s var(--wui-ease-out-power-2); + will-change: opacity; + } + + :host(.open) { + opacity: 1; + } + + :host(.appkit-modal) { + position: relative; + pointer-events: unset; + background: none; + width: 100%; + opacity: 1; + } + + wui-card { + max-width: var(--w3m-modal-width); + width: 100%; + position: relative; + animation: zoom-in 0.2s var(--wui-ease-out-power-2); + animation-fill-mode: backwards; + outline: none; + transition: + border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1), + background-color var(--wui-duration-lg) var(--wui-ease-out-power-1); + will-change: border-radius, background-color; + } + + :host(.appkit-modal) wui-card { + max-width: 400px; + } + + wui-card[shake='true'] { + animation: + zoom-in 0.2s var(--wui-ease-out-power-2), + w3m-shake 0.5s var(--wui-ease-out-power-2); + } + + wui-flex { + overflow-x: hidden; + overflow-y: auto; + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + } + + @media (max-height: 700px) and (min-width: 431px) { + wui-flex { + align-items: flex-start; + } + + wui-card { + margin: var(--wui-spacing-xxl) 0px; + } + } + + @media (max-width: 430px) { + wui-flex { + align-items: flex-end; + } + + wui-card { + max-width: 100%; + border-bottom-left-radius: var(--local-border-bottom-mobile-radius); + border-bottom-right-radius: var(--local-border-bottom-mobile-radius); + border-bottom: none; + animation: slide-in 0.2s var(--wui-ease-out-power-2); + } + + wui-card[shake='true'] { + animation: + slide-in 0.2s var(--wui-ease-out-power-2), + w3m-shake 0.5s var(--wui-ease-out-power-2); + } + } + + @keyframes zoom-in { + 0% { + transform: scale(0.95) translateY(0); + } + 100% { + transform: scale(1) translateY(0); + } + } + + @keyframes slide-in { + 0% { + transform: scale(1) translateY(50px); + } + 100% { + transform: scale(1) translateY(0); + } + } + + @keyframes w3m-shake { + 0% { + transform: scale(1) rotate(0deg); + } + 20% { + transform: scale(1) rotate(-1deg); + } + 40% { + transform: scale(1) rotate(1.5deg); + } + 60% { + transform: scale(1) rotate(-1.5deg); + } + 80% { + transform: scale(1) rotate(1deg); + } + 100% { + transform: scale(1) rotate(0deg); + } + } + + @keyframes w3m-view-height { + from { + height: var(--prev-height); + } + to { + height: var(--new-height); + } + } +`;var C=function(n,e,t,i){var a=arguments.length,o=a<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,i);else for(var r=n.length-1;r>=0;r--)(s=n[r])&&(o=(a<3?s(o):a>3?s(e,t,o):s(e,t))||o);return a>3&&o&&Object.defineProperty(e,t,o),o};const X="scroll-lock";class g extends y{constructor(){super(),this.unsubscribe=[],this.abortController=void 0,this.hasPrefetched=!1,this.enableEmbedded=W.state.enableEmbedded,this.open=p.state.open,this.caipAddress=h.state.activeCaipAddress,this.caipNetwork=h.state.activeCaipNetwork,this.shake=p.state.shake,this.filterByNamespace=z.state.filterByNamespace,this.initializeTheming(),A.prefetchAnalyticsConfig(),this.unsubscribe.push(p.subscribeKey("open",e=>e?this.onOpen():this.onClose()),p.subscribeKey("shake",e=>this.shake=e),h.subscribeKey("activeCaipNetwork",e=>this.onNewNetwork(e)),h.subscribeKey("activeCaipAddress",e=>this.onNewAddress(e)),W.subscribeKey("enableEmbedded",e=>this.enableEmbedded=e),z.subscribeKey("filterByNamespace",e=>{this.filterByNamespace!==e&&!h.getAccountData(e)?.caipAddress&&(A.fetchRecommendedWallets(),this.filterByNamespace=e)}))}firstUpdated(){if(this.caipAddress){if(this.enableEmbedded){p.close(),this.prefetch();return}this.onNewAddress(this.caipAddress)}this.open&&this.onOpen(),this.enableEmbedded&&this.prefetch()}disconnectedCallback(){this.unsubscribe.forEach(e=>e()),this.onRemoveKeyboardListener()}render(){return this.style.cssText=` + --local-border-bottom-mobile-radius: ${this.enableEmbedded?"clamp(0px, var(--wui-border-radius-l), 44px)":"0px"}; + `,this.enableEmbedded?l`${this.contentTemplate()} + `:this.open?l` + + ${this.contentTemplate()} + + + `:null}contentTemplate(){return l` + + + + + `}async onOverlayClick(e){e.target===e.currentTarget&&await this.handleClose()}async handleClose(){await F.safeClose()}initializeTheming(){const{themeVariables:e,themeMode:t}=ce.state,i=le.getColorTheme(t);de(e,i)}onClose(){this.open=!1,this.classList.remove("open"),this.onScrollUnlock(),S.hide(),this.onRemoveKeyboardListener()}onOpen(){this.open=!0,this.classList.add("open"),this.onScrollLock(),this.onAddKeyboardListener()}onScrollLock(){const e=document.createElement("style");e.dataset.w3m=X,e.textContent=` + body { + touch-action: none; + overflow: hidden; + overscroll-behavior: contain; + } + w3m-modal { + pointer-events: auto; + } + `,document.head.appendChild(e)}onScrollUnlock(){const e=document.head.querySelector(`style[data-w3m="${X}"]`);e&&e.remove()}onAddKeyboardListener(){this.abortController=new AbortController;const e=this.shadowRoot?.querySelector("wui-card");e?.focus(),window.addEventListener("keydown",t=>{if(t.key==="Escape")this.handleClose();else if(t.key==="Tab"){const{tagName:i}=t.target;i&&!i.includes("W3M-")&&!i.includes("WUI-")&&e?.focus()}},this.abortController)}onRemoveKeyboardListener(){this.abortController?.abort(),this.abortController=void 0}async onNewAddress(e){const t=h.state.isSwitchingNamespace,i=c.state.view==="ProfileWallets";e?await this.onConnected({caipAddress:e,isSwitchingNamespace:t,isInProfileView:i}):!t&&!this.enableEmbedded&&!i&&p.close(),await T.initializeIfEnabled(e),this.caipAddress=e,h.setIsSwitchingNamespace(!1)}async onConnected(e){if(e.isInProfileView)return;const{chainNamespace:t,chainId:i,address:a}=ue.parseCaipAddress(e.caipAddress),o=`${t}:${i}`,s=!pe.getPlainAddress(this.caipAddress),r=await T.getSessions({address:a,caipNetworkId:o}),E=T.getSIWX()?r.some(j=>j.data.accountAddress===a):!0,_=e.isSwitchingNamespace&&E&&!this.enableEmbedded,D=this.enableEmbedded&&s;_?c.goBack():D&&p.close()}onNewNetwork(e){const t=this.caipNetwork,i=t?.caipNetworkId?.toString(),a=t?.chainNamespace,o=e?.caipNetworkId?.toString(),s=e?.chainNamespace,r=i!==o,_=r&&!(a!==s),D=t?.name===he.UNSUPPORTED_NETWORK_NAME,j=c.state.view==="ConnectingExternal",ee=c.state.view==="ProfileWallets",te=!h.getAccountData(e?.chainNamespace)?.caipAddress,oe=c.state.view==="UnsupportedChain",ie=p.state.open;let N=!1;this.enableEmbedded&&c.state.view==="SwitchNetwork"&&(N=!0),ie&&!j&&!ee&&(te?r&&(N=!0):(oe||_&&!D)&&(N=!0)),N&&c.state.view!=="SIWXSignMessage"&&c.goBack(),this.caipNetwork=e}prefetch(){this.hasPrefetched||(A.prefetch(),A.fetchWalletsByPage({page:1}),this.hasPrefetched=!0)}}g.styles=Ne;C([u({type:Boolean})],g.prototype,"enableEmbedded",void 0);C([d()],g.prototype,"open",void 0);C([d()],g.prototype,"caipAddress",void 0);C([d()],g.prototype,"caipNetwork",void 0);C([d()],g.prototype,"shake",void 0);C([d()],g.prototype,"filterByNamespace",void 0);let G=class extends g{};G=C([f("w3m-modal")],G);let q=class extends g{};q=C([f("appkit-modal")],q);export{q as AppKitModal,G as W3mModal,g as W3mModalBase}; diff --git a/dist/assets/wallet-B7rYWpGd.js b/dist/assets/wallet-B7rYWpGd.js new file mode 100644 index 0000000..24c1ec8 --- /dev/null +++ b/dist/assets/wallet-B7rYWpGd.js @@ -0,0 +1,8 @@ +import{b as c}from"./index-Cr5N_0pd.js";const v=c` + +`;export{v as walletSvg}; diff --git a/dist/assets/wallet-placeholder-BUQhm8ne.js b/dist/assets/wallet-placeholder-BUQhm8ne.js new file mode 100644 index 0000000..a609ce9 --- /dev/null +++ b/dist/assets/wallet-placeholder-BUQhm8ne.js @@ -0,0 +1,14 @@ +import{b as a}from"./index-Cr5N_0pd.js";const v=a` + + + + +`;export{v as walletPlaceholderSvg}; diff --git a/dist/assets/walletconnect-DhIwJMgu.js b/dist/assets/walletconnect-DhIwJMgu.js new file mode 100644 index 0000000..19c7990 --- /dev/null +++ b/dist/assets/walletconnect-DhIwJMgu.js @@ -0,0 +1,30 @@ +import{b as l}from"./index-Cr5N_0pd.js";const C=l` + + +`,a=l` + + + + + + + + + + + +`,L=l` + + + + + + +`;export{L as walletConnectBrownSvg,a as walletConnectLightBrownSvg,C as walletConnectSvg}; diff --git a/dist/assets/warning-circle-Dwz2WWdH.js b/dist/assets/warning-circle-Dwz2WWdH.js new file mode 100644 index 0000000..ceca168 --- /dev/null +++ b/dist/assets/warning-circle-Dwz2WWdH.js @@ -0,0 +1,12 @@ +import{b as l}from"./index-Cr5N_0pd.js";const e=l` + + +`;export{e as warningCircleSvg}; diff --git a/dist/assets/x-C3LRqiud.js b/dist/assets/x-C3LRqiud.js new file mode 100644 index 0000000..364acda --- /dev/null +++ b/dist/assets/x-C3LRqiud.js @@ -0,0 +1,12 @@ +import{b as l}from"./index-Cr5N_0pd.js";const h=l` + + + + + + + +`;export{h as xSvg}; diff --git a/dist/assets/x-mark-DqeqBMH2.js b/dist/assets/x-mark-DqeqBMH2.js new file mode 100644 index 0000000..b5f4027 --- /dev/null +++ b/dist/assets/x-mark-DqeqBMH2.js @@ -0,0 +1,3 @@ +import{b as l}from"./index-Cr5N_0pd.js";const e=l` + +`;export{e as xMarkSvg}; diff --git a/dist/favicon.ico b/dist/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..32e0122d3273208e97d5024356b57de1ed694a67 GIT binary patch literal 1150 zcmbtTD-wf13{7Vc$O@)|L?RFz0f9tt1Ox)XA$lJK0>M!@L?r@&Nb_i6X!s1!FkyGI zdGGBevqU%f?st;ELzzMJAR<>>LK6AJWgwEh6^kVH66cc+%vJ2DwX5rS9{avO=AIhk zIOeYF2FLu&-SRx=zVCT7%#$QJ!~yJjmC%9B!Is;(!KvnPu5eU6F%a wt&g=~7#xP-&?C#TrX1V08NCgHfKAh!;$M#4H?XENi~aKk2ki4EY!?mKH^xT`4FCWD literal 0 HcmV?d00001 diff --git a/dist/index.html b/dist/index.html new file mode 100644 index 0000000..68a976e --- /dev/null +++ b/dist/index.html @@ -0,0 +1,28 @@ + + + + + + OpChan - Decentralized Forum + + + + + + + + + + + + + +
+ + diff --git a/dist/placeholder.svg b/dist/placeholder.svg new file mode 100644 index 0000000..e763910 --- /dev/null +++ b/dist/placeholder.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/dist/robots.txt b/dist/robots.txt new file mode 100644 index 0000000..6018e70 --- /dev/null +++ b/dist/robots.txt @@ -0,0 +1,14 @@ +User-agent: Googlebot +Allow: / + +User-agent: Bingbot +Allow: / + +User-agent: Twitterbot +Allow: / + +User-agent: facebookexternalhit +Allow: / + +User-agent: * +Allow: / diff --git a/packages/core/dist/database/LocalDatabase.d.ts b/packages/core/dist/database/LocalDatabase.d.ts new file mode 100644 index 0000000..908777d --- /dev/null +++ b/packages/core/dist/database/LocalDatabase.d.ts @@ -0,0 +1,128 @@ +import { CellCache, PostCache, CommentCache, VoteCache, UserIdentityCache, ModerateMessage } from '../types/waku'; +import { User } from '../types/identity'; +import { DelegationInfo } from '../delegation/types'; +import { Bookmark, BookmarkCache } from '../types/forum'; +export interface LocalDatabaseCache { + cells: CellCache; + posts: PostCache; + comments: CommentCache; + votes: VoteCache; + moderations: { + [targetId: string]: ModerateMessage; + }; + userIdentities: UserIdentityCache; + bookmarks: BookmarkCache; +} +/** + * Minimal in-memory LocalDatabase + * Mirrors CacheService message handling to enable incremental migration. + */ +export declare class LocalDatabase { + private processedMessageIds; + private validator; + private db; + private _isSyncing; + private _lastSync; + private pendingIds; + private pendingListeners; + readonly cache: LocalDatabaseCache; + constructor(); + /** + * Open IndexedDB and hydrate in-memory cache. + */ + open(): Promise; + /** + * Apply a message into the LocalDatabase. + * Returns true if the message was newly processed and stored. + */ + applyMessage(message: unknown): Promise; + /** + * Temporary alias to ease migration from CacheService.updateCache + */ + updateCache(message: unknown): Promise; + clear(): void; + private storeMessage; + /** + * Hydrate cache from IndexedDB on warm start + */ + private hydrateFromIndexedDB; + private hydratePendingFromMeta; + private getAllFromStore; + private put; + getSyncState(): { + lastSync: number | null; + isSyncing: boolean; + }; + setSyncing(isSyncing: boolean): void; + updateLastSync(timestamp: number): void; + markPending(id: string): void; + clearPending(id: string): void; + isPending(id: string): boolean; + onPendingChange(listener: () => void): () => void; + /** + * Store user authentication data + */ + storeUser(user: User): Promise; + /** + * Load user authentication data + */ + loadUser(): Promise; + /** + * Clear user authentication data + */ + clearUser(): Promise; + /** + * Store delegation information + */ + storeDelegation(delegation: DelegationInfo): Promise; + /** + * Load delegation information + */ + loadDelegation(): Promise; + /** + * Clear delegation information + */ + clearDelegation(): Promise; + /** + * Store UI state value + */ + storeUIState(key: string, value: unknown): Promise; + /** + * Load UI state value + */ + loadUIState(key: string): Promise; + /** + * Clear UI state value + */ + clearUIState(key: string): Promise; + /** + * Add a bookmark + */ + addBookmark(bookmark: Bookmark): Promise; + /** + * Remove a bookmark + */ + removeBookmark(bookmarkId: string): Promise; + /** + * Get all bookmarks for a user + */ + getUserBookmarks(userId: string): Promise; + /** + * Get bookmarks by type for a user + */ + getUserBookmarksByType(userId: string, type: 'post' | 'comment'): Promise; + /** + * Check if an item is bookmarked by a user + */ + isBookmarked(userId: string, type: 'post' | 'comment', targetId: string): boolean; + /** + * Get bookmark by ID + */ + getBookmark(bookmarkId: string): Bookmark | undefined; + /** + * Get all bookmarks from cache + */ + getAllBookmarks(): Bookmark[]; +} +export declare const localDatabase: LocalDatabase; +//# sourceMappingURL=LocalDatabase.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/database/LocalDatabase.d.ts.map b/packages/core/dist/database/LocalDatabase.d.ts.map new file mode 100644 index 0000000..7ab38e6 --- /dev/null +++ b/packages/core/dist/database/LocalDatabase.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"LocalDatabase.d.ts","sourceRoot":"","sources":["../../src/database/LocalDatabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,SAAS,EACT,SAAS,EACT,YAAY,EACZ,SAAS,EACT,iBAAiB,EACjB,eAAe,EAMhB,MAAM,eAAe,CAAC;AAGvB,OAAO,EAAuB,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEzD,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,SAAS,CAAC;IACjB,KAAK,EAAE,SAAS,CAAC;IACjB,QAAQ,EAAE,YAAY,CAAC;IACvB,KAAK,EAAE,SAAS,CAAC;IACjB,WAAW,EAAE;QAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,eAAe,CAAA;KAAE,CAAC;IACrD,cAAc,EAAE,iBAAiB,CAAC;IAClC,SAAS,EAAE,aAAa,CAAC;CAC1B;AAED;;;GAGG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,mBAAmB,CAA0B;IACrD,OAAO,CAAC,SAAS,CAAmB;IACpC,OAAO,CAAC,EAAE,CAA4B;IACtC,OAAO,CAAC,UAAU,CAAkB;IACpC,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,UAAU,CAA0B;IAC5C,OAAO,CAAC,gBAAgB,CAA8B;IAEtD,SAAgB,KAAK,EAAE,kBAAkB,CAQvC;;IAMF;;OAEG;IACU,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAMlC;;;OAGG;IACU,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IA4B7D;;OAEG;IACU,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IAIrD,KAAK,IAAI,IAAI;IAWpB,OAAO,CAAC,YAAY;IAuFpB;;OAEG;YACW,oBAAoB;YA6CpB,sBAAsB;IAgBpC,OAAO,CAAC,eAAe;IAWvB,OAAO,CAAC,GAAG;IAqBJ,YAAY,IAAI;QAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,SAAS,EAAE,OAAO,CAAA;KAAE;IAI/D,UAAU,CAAC,SAAS,EAAE,OAAO,GAAG,IAAI;IAIpC,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IASvC,WAAW,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAS7B,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAS9B,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO;IAI9B,eAAe,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI;IAOxD;;OAEG;IACU,SAAS,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IASjD;;OAEG;IACU,QAAQ,IAAI,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAiC7C;;OAEG;IACU,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAUvC;;OAEG;IACU,eAAe,CAAC,UAAU,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IASvE;;OAEG;IACU,cAAc,IAAI,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IAkB7D;;OAEG;IACU,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IAU7C;;OAEG;IACU,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IASrE;;OAEG;IACU,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAkBvD;;OAEG;IACU,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUrD;;OAEG;IACU,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAK3D;;OAEG;IACU,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAS9D;;OAEG;IACU,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;IAclE;;OAEG;IACU,sBAAsB,CACjC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GAAG,SAAS,GACvB,OAAO,CAAC,QAAQ,EAAE,CAAC;IAkBtB;;OAEG;IACI,YAAY,CACjB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GAAG,SAAS,EACxB,QAAQ,EAAE,MAAM,GACf,OAAO;IAMV;;OAEG;IACI,WAAW,CAAC,UAAU,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS;IAI5D;;OAEG;IACI,eAAe,IAAI,QAAQ,EAAE;CAGrC;AAED,eAAO,MAAM,aAAa,eAAsB,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/database/LocalDatabase.js b/packages/core/dist/database/LocalDatabase.js new file mode 100644 index 0000000..596f559 --- /dev/null +++ b/packages/core/dist/database/LocalDatabase.js @@ -0,0 +1,453 @@ +import { MessageType, } from '../types/waku'; +import { MessageValidator } from '../utils/MessageValidator'; +import { EVerificationStatus } from '../types/identity'; +import { openLocalDB, STORE } from '../database/schema'; +/** + * Minimal in-memory LocalDatabase + * Mirrors CacheService message handling to enable incremental migration. + */ +export class LocalDatabase { + constructor() { + this.processedMessageIds = new Set(); + this.db = null; + this._isSyncing = false; + this._lastSync = null; + this.pendingIds = new Set(); + this.pendingListeners = new Set(); + this.cache = { + cells: {}, + posts: {}, + comments: {}, + votes: {}, + moderations: {}, + userIdentities: {}, + bookmarks: {}, + }; + this.validator = new MessageValidator(); + } + /** + * Open IndexedDB and hydrate in-memory cache. + */ + async open() { + this.db = await openLocalDB(); + await this.hydrateFromIndexedDB(); + await this.hydratePendingFromMeta(); + } + /** + * Apply a message into the LocalDatabase. + * Returns true if the message was newly processed and stored. + */ + async applyMessage(message) { + if (!(await this.validator.isValidMessage(message))) { + const partialMsg = message; + console.warn('LocalDatabase: Rejecting invalid message', { + messageId: partialMsg?.id, + messageType: partialMsg?.type, + hasSignature: !!partialMsg?.signature, + hasBrowserPubKey: !!partialMsg?.browserPubKey, + }); + return false; + } + const validMessage = message; + const messageKey = `${validMessage.type}:${validMessage.id}:${validMessage.timestamp}`; + if (this.processedMessageIds.has(messageKey)) { + return false; + } + this.processedMessageIds.add(messageKey); + this.storeMessage(validMessage); + return true; + } + /** + * Temporary alias to ease migration from CacheService.updateCache + */ + async updateCache(message) { + return this.applyMessage(message); + } + clear() { + this.processedMessageIds.clear(); + this.cache.cells = {}; + this.cache.posts = {}; + this.cache.comments = {}; + this.cache.votes = {}; + this.cache.moderations = {}; + this.cache.userIdentities = {}; + this.cache.bookmarks = {}; + } + storeMessage(message) { + switch (message.type) { + case MessageType.CELL: + if (!this.cache.cells[message.id] || + this.cache.cells[message.id]?.timestamp !== message.timestamp) { + this.cache.cells[message.id] = message; + this.put(STORE.CELLS, message); + } + break; + case MessageType.POST: + if (!this.cache.posts[message.id] || + this.cache.posts[message.id]?.timestamp !== message.timestamp) { + this.cache.posts[message.id] = message; + this.put(STORE.POSTS, message); + } + break; + case MessageType.COMMENT: + if (!this.cache.comments[message.id] || + this.cache.comments[message.id]?.timestamp !== message.timestamp) { + this.cache.comments[message.id] = message; + this.put(STORE.COMMENTS, message); + } + break; + case MessageType.VOTE: { + const voteKey = `${message.targetId}:${message.author}`; + if (!this.cache.votes[voteKey] || + this.cache.votes[voteKey]?.timestamp !== message.timestamp) { + this.cache.votes[voteKey] = message; + this.put(STORE.VOTES, { key: voteKey, ...message }); + } + break; + } + case MessageType.MODERATE: { + const modMsg = message; + if (!this.cache.moderations[modMsg.targetId] || + this.cache.moderations[modMsg.targetId]?.timestamp !== + modMsg.timestamp) { + this.cache.moderations[modMsg.targetId] = modMsg; + this.put(STORE.MODERATIONS, modMsg); + } + break; + } + case MessageType.USER_PROFILE_UPDATE: { + const profileMsg = message; + const { author, callSign, displayPreference, timestamp } = profileMsg; + const existing = this.cache.userIdentities[author]; + if (!existing || timestamp > existing.lastUpdated) { + const nextRecord = { + ensName: existing?.ensName, + ordinalDetails: existing?.ordinalDetails, + callSign: callSign !== undefined ? callSign : existing?.callSign, + displayPreference, + lastUpdated: timestamp, + verificationStatus: existing?.verificationStatus ?? + EVerificationStatus.WALLET_UNCONNECTED, + }; + this.cache.userIdentities[author] = nextRecord; + // Persist with address keyPath + this.put(STORE.USER_IDENTITIES, { + address: author, + ...nextRecord, + }); + } + break; + } + default: + console.warn('LocalDatabase: Received message with unknown type'); + break; + } + // Update last sync time using local receipt time for accurate UI + this.updateLastSync(Date.now()); + } + /** + * Hydrate cache from IndexedDB on warm start + */ + async hydrateFromIndexedDB() { + if (!this.db) + return; + const [cells, posts, comments, votes, moderations, identities, bookmarks] = await Promise.all([ + this.getAllFromStore(STORE.CELLS), + this.getAllFromStore(STORE.POSTS), + this.getAllFromStore(STORE.COMMENTS), + this.getAllFromStore(STORE.VOTES), + this.getAllFromStore(STORE.MODERATIONS), + this.getAllFromStore(STORE.USER_IDENTITIES), + this.getAllFromStore(STORE.BOOKMARKS), + ]); + this.cache.cells = Object.fromEntries(cells.map((c) => [c.id, c])); + this.cache.posts = Object.fromEntries(posts.map((p) => [p.id, p])); + this.cache.comments = Object.fromEntries(comments.map((cm) => [cm.id, cm])); + this.cache.votes = Object.fromEntries(votes.map((v) => { + const { key, ...rest } = v; + const vote = rest; + return [key, vote]; + })); + this.cache.moderations = Object.fromEntries(moderations.map((m) => [m.targetId, m])); + this.cache.userIdentities = Object.fromEntries(identities.map((u) => { + const { address, ...record } = u; + return [address, record]; + })); + this.cache.bookmarks = Object.fromEntries(bookmarks.map((b) => [b.id, b])); + } + async hydratePendingFromMeta() { + if (!this.db) + return; + const meta = await this.getAllFromStore(STORE.META); + meta + .filter((entry) => typeof entry.key === 'string' && entry.key.startsWith('pending:')) + .forEach((entry) => { + const id = entry.key.substring('pending:'.length); + this.pendingIds.add(id); + }); + } + getAllFromStore(storeName) { + return new Promise((resolve, reject) => { + if (!this.db) + return resolve([]); + const tx = this.db.transaction(storeName, 'readonly'); + const store = tx.objectStore(storeName); + const request = store.getAll(); + request.onerror = () => reject(request.error); + request.onsuccess = () => resolve(request.result); + }); + } + put(storeName, value) { + if (!this.db) + return; + const tx = this.db.transaction(storeName, 'readwrite'); + const store = tx.objectStore(storeName); + store.put(value); + } + getSyncState() { + return { lastSync: this._lastSync, isSyncing: this._isSyncing }; + } + setSyncing(isSyncing) { + this._isSyncing = isSyncing; + } + updateLastSync(timestamp) { + this._lastSync = Math.max(this._lastSync ?? 0, timestamp); + // persist in META store (best-effort) + if (!this.db) + return; + const tx = this.db.transaction(STORE.META, 'readwrite'); + const store = tx.objectStore(STORE.META); + store.put({ key: 'lastSync', value: this._lastSync }); + } + markPending(id) { + this.pendingIds.add(id); + if (!this.db) + return; + const tx = this.db.transaction(STORE.META, 'readwrite'); + const store = tx.objectStore(STORE.META); + store.put({ key: `pending:${id}`, value: true }); + this.pendingListeners.forEach((l) => l()); + } + clearPending(id) { + this.pendingIds.delete(id); + if (!this.db) + return; + const tx = this.db.transaction(STORE.META, 'readwrite'); + const store = tx.objectStore(STORE.META); + store.delete(`pending:${id}`); + this.pendingListeners.forEach((l) => l()); + } + isPending(id) { + return this.pendingIds.has(id); + } + onPendingChange(listener) { + this.pendingListeners.add(listener); + return () => this.pendingListeners.delete(listener); + } + // ===== User Authentication Storage ===== + /** + * Store user authentication data + */ + async storeUser(user) { + const userData = { + key: 'current', + value: user, + timestamp: Date.now(), + }; + this.put(STORE.USER_AUTH, userData); + } + /** + * Load user authentication data + */ + async loadUser() { + if (!this.db) + return null; + return new Promise((resolve, reject) => { + const tx = this.db.transaction(STORE.USER_AUTH, 'readonly'); + const store = tx.objectStore(STORE.USER_AUTH); + const request = store.get('current'); + request.onerror = () => reject(request.error); + request.onsuccess = () => { + const result = request.result; + if (!result) { + resolve(null); + return; + } + const user = result.value; + const lastChecked = user.lastChecked || 0; + const expiryTime = 24 * 60 * 60 * 1000; // 24 hours + if (Date.now() - lastChecked < expiryTime) { + resolve(user); + } + else { + // User data expired, clear it + this.clearUser(); + resolve(null); + } + }; + }); + } + /** + * Clear user authentication data + */ + async clearUser() { + if (!this.db) + return; + const tx = this.db.transaction(STORE.USER_AUTH, 'readwrite'); + const store = tx.objectStore(STORE.USER_AUTH); + store.delete('current'); + } + // ===== Delegation Storage ===== + /** + * Store delegation information + */ + async storeDelegation(delegation) { + const delegationData = { + key: 'current', + value: delegation, + timestamp: Date.now(), + }; + this.put(STORE.DELEGATION, delegationData); + } + /** + * Load delegation information + */ + async loadDelegation() { + if (!this.db) + return null; + return new Promise((resolve, reject) => { + const tx = this.db.transaction(STORE.DELEGATION, 'readonly'); + const store = tx.objectStore(STORE.DELEGATION); + const request = store.get('current'); + request.onerror = () => reject(request.error); + request.onsuccess = () => { + const result = request.result; + resolve(result?.value || null); + }; + }); + } + /** + * Clear delegation information + */ + async clearDelegation() { + if (!this.db) + return; + const tx = this.db.transaction(STORE.DELEGATION, 'readwrite'); + const store = tx.objectStore(STORE.DELEGATION); + store.delete('current'); + } + // ===== UI State Storage ===== + /** + * Store UI state value + */ + async storeUIState(key, value) { + const stateData = { + key, + value, + timestamp: Date.now(), + }; + this.put(STORE.UI_STATE, stateData); + } + /** + * Load UI state value + */ + async loadUIState(key) { + if (!this.db) + return null; + return new Promise((resolve, reject) => { + const tx = this.db.transaction(STORE.UI_STATE, 'readonly'); + const store = tx.objectStore(STORE.UI_STATE); + const request = store.get(key); + request.onerror = () => reject(request.error); + request.onsuccess = () => { + const result = request.result; + resolve(result?.value || null); + }; + }); + } + /** + * Clear UI state value + */ + async clearUIState(key) { + if (!this.db) + return; + const tx = this.db.transaction(STORE.UI_STATE, 'readwrite'); + const store = tx.objectStore(STORE.UI_STATE); + store.delete(key); + } + // ===== Bookmark Storage ===== + /** + * Add a bookmark + */ + async addBookmark(bookmark) { + this.cache.bookmarks[bookmark.id] = bookmark; + this.put(STORE.BOOKMARKS, bookmark); + } + /** + * Remove a bookmark + */ + async removeBookmark(bookmarkId) { + delete this.cache.bookmarks[bookmarkId]; + if (!this.db) + return; + const tx = this.db.transaction(STORE.BOOKMARKS, 'readwrite'); + const store = tx.objectStore(STORE.BOOKMARKS); + store.delete(bookmarkId); + } + /** + * Get all bookmarks for a user + */ + async getUserBookmarks(userId) { + if (!this.db) + return []; + return new Promise((resolve, reject) => { + const tx = this.db.transaction(STORE.BOOKMARKS, 'readonly'); + const store = tx.objectStore(STORE.BOOKMARKS); + const index = store.index('by_userId'); + const request = index.getAll(userId); + request.onerror = () => reject(request.error); + request.onsuccess = () => resolve(request.result); + }); + } + /** + * Get bookmarks by type for a user + */ + async getUserBookmarksByType(userId, type) { + if (!this.db) + return []; + return new Promise((resolve, reject) => { + const tx = this.db.transaction(STORE.BOOKMARKS, 'readonly'); + const store = tx.objectStore(STORE.BOOKMARKS); + const index = store.index('by_userId'); + const request = index.getAll(userId); + request.onerror = () => reject(request.error); + request.onsuccess = () => { + const bookmarks = request.result; + const filtered = bookmarks.filter((b) => b.type === type); + resolve(filtered); + }; + }); + } + /** + * Check if an item is bookmarked by a user + */ + isBookmarked(userId, type, targetId) { + const bookmarkId = `${type}:${targetId}`; + const bookmark = this.cache.bookmarks[bookmarkId]; + return bookmark?.userId === userId; + } + /** + * Get bookmark by ID + */ + getBookmark(bookmarkId) { + return this.cache.bookmarks[bookmarkId]; + } + /** + * Get all bookmarks from cache + */ + getAllBookmarks() { + return Object.values(this.cache.bookmarks); + } +} +export const localDatabase = new LocalDatabase(); +//# sourceMappingURL=LocalDatabase.js.map \ No newline at end of file diff --git a/packages/core/dist/database/LocalDatabase.js.map b/packages/core/dist/database/LocalDatabase.js.map new file mode 100644 index 0000000..bbddad5 --- /dev/null +++ b/packages/core/dist/database/LocalDatabase.js.map @@ -0,0 +1 @@ +{"version":3,"file":"LocalDatabase.js","sourceRoot":"","sources":["../../src/database/LocalDatabase.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,GAYZ,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,mBAAmB,EAAQ,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,WAAW,EAAE,KAAK,EAAa,MAAM,oBAAoB,CAAC;AAanE;;;GAGG;AACH,MAAM,OAAO,aAAa;IAmBxB;QAlBQ,wBAAmB,GAAgB,IAAI,GAAG,EAAE,CAAC;QAE7C,OAAE,GAAuB,IAAI,CAAC;QAC9B,eAAU,GAAY,KAAK,CAAC;QAC5B,cAAS,GAAkB,IAAI,CAAC;QAChC,eAAU,GAAgB,IAAI,GAAG,EAAE,CAAC;QACpC,qBAAgB,GAAoB,IAAI,GAAG,EAAE,CAAC;QAEtC,UAAK,GAAuB;YAC1C,KAAK,EAAE,EAAE;YACT,KAAK,EAAE,EAAE;YACT,QAAQ,EAAE,EAAE;YACZ,KAAK,EAAE,EAAE;YACT,WAAW,EAAE,EAAE;YACf,cAAc,EAAE,EAAE;YAClB,SAAS,EAAE,EAAE;SACd,CAAC;QAGA,IAAI,CAAC,SAAS,GAAG,IAAI,gBAAgB,EAAE,CAAC;IAC1C,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,IAAI;QACf,IAAI,CAAC,EAAE,GAAG,MAAM,WAAW,EAAE,CAAC;QAC9B,MAAM,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAClC,MAAM,IAAI,CAAC,sBAAsB,EAAE,CAAC;IACtC,CAAC;IAED;;;OAGG;IACI,KAAK,CAAC,YAAY,CAAC,OAAgB;QACxC,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;YACpD,MAAM,UAAU,GAAG,OAKlB,CAAC;YACF,OAAO,CAAC,IAAI,CAAC,0CAA0C,EAAE;gBACvD,SAAS,EAAE,UAAU,EAAE,EAAE;gBACzB,WAAW,EAAE,UAAU,EAAE,IAAI;gBAC7B,YAAY,EAAE,CAAC,CAAC,UAAU,EAAE,SAAS;gBACrC,gBAAgB,EAAE,CAAC,CAAC,UAAU,EAAE,aAAa;aAC9C,CAAC,CAAC;YACH,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,YAAY,GAAG,OAAwB,CAAC;QAC9C,MAAM,UAAU,GAAG,GAAG,YAAY,CAAC,IAAI,IAAI,YAAY,CAAC,EAAE,IAAI,YAAY,CAAC,SAAS,EAAE,CAAC;QACvF,IAAI,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7C,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACzC,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,WAAW,CAAC,OAAgB;QACvC,OAAO,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IACpC,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,mBAAmB,CAAC,KAAK,EAAE,CAAC;QACjC,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,EAAE,CAAC;QACzB,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,WAAW,GAAG,EAAE,CAAC;QAC5B,IAAI,CAAC,KAAK,CAAC,cAAc,GAAG,EAAE,CAAC;QAC/B,IAAI,CAAC,KAAK,CAAC,SAAS,GAAG,EAAE,CAAC;IAC5B,CAAC;IAEO,YAAY,CAAC,OAAsB;QACzC,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;YACrB,KAAK,WAAW,CAAC,IAAI;gBACnB,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;oBAC7B,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,SAAS,KAAK,OAAO,CAAC,SAAS,EAC7D,CAAC;oBACD,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC;oBACvC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;gBACjC,CAAC;gBACD,MAAM;YACR,KAAK,WAAW,CAAC,IAAI;gBACnB,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;oBAC7B,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,SAAS,KAAK,OAAO,CAAC,SAAS,EAC7D,CAAC;oBACD,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC;oBACvC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;gBACjC,CAAC;gBACD,MAAM;YACR,KAAK,WAAW,CAAC,OAAO;gBACtB,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;oBAChC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,SAAS,KAAK,OAAO,CAAC,SAAS,EAChE,CAAC;oBACD,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC;oBAC1C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;gBACpC,CAAC;gBACD,MAAM;YACR,KAAK,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;gBACtB,MAAM,OAAO,GAAG,GAAG,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;gBACxD,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC;oBAC1B,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,SAAS,KAAK,OAAO,CAAC,SAAS,EAC1D,CAAC;oBACD,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;oBACpC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;gBACtD,CAAC;gBACD,MAAM;YACR,CAAC;YACD,KAAK,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAC1B,MAAM,MAAM,GAAG,OAA0B,CAAC;gBAC1C,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC;oBACxC,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,SAAS;wBAChD,MAAM,CAAC,SAAS,EAClB,CAAC;oBACD,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC;oBACjD,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;gBACtC,CAAC;gBACD,MAAM;YACR,CAAC;YACD,KAAK,WAAW,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBACrC,MAAM,UAAU,GAAG,OAAmC,CAAC;gBACvD,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,iBAAiB,EAAE,SAAS,EAAE,GAAG,UAAU,CAAC;gBAEtE,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;gBACnD,IAAI,CAAC,QAAQ,IAAI,SAAS,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;oBAClD,MAAM,UAAU,GAAG;wBACjB,OAAO,EAAE,QAAQ,EAAE,OAAO;wBAC1B,cAAc,EAAE,QAAQ,EAAE,cAAc;wBACxC,QAAQ,EAAE,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,EAAE,QAAQ;wBAChE,iBAAiB;wBACjB,WAAW,EAAE,SAAS;wBACtB,kBAAkB,EAChB,QAAQ,EAAE,kBAAkB;4BAC5B,mBAAmB,CAAC,kBAAkB;qBACZ,CAAC;oBAE/B,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC;oBAC/C,+BAA+B;oBAC/B,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,eAAe,EAAE;wBAC9B,OAAO,EAAE,MAAM;wBACf,GAAG,UAAU;qBACd,CAAC,CAAC;gBACL,CAAC;gBACD,MAAM;YACR,CAAC;YACD;gBACE,OAAO,CAAC,IAAI,CAAC,mDAAmD,CAAC,CAAC;gBAClE,MAAM;QACV,CAAC;QAED,iEAAiE;QACjE,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;IAClC,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,oBAAoB;QAChC,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO;QAErB,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,CAAC,GAQrE,MAAM,OAAO,CAAC,GAAG,CAAC;YACpB,IAAI,CAAC,eAAe,CAAc,KAAK,CAAC,KAAK,CAAC;YAC9C,IAAI,CAAC,eAAe,CAAc,KAAK,CAAC,KAAK,CAAC;YAC9C,IAAI,CAAC,eAAe,CAAiB,KAAK,CAAC,QAAQ,CAAC;YACpD,IAAI,CAAC,eAAe,CAAgC,KAAK,CAAC,KAAK,CAAC;YAChE,IAAI,CAAC,eAAe,CAAkB,KAAK,CAAC,WAAW,CAAC;YACxD,IAAI,CAAC,eAAe,CAClB,KAAK,CAAC,eAAe,CACtB;YACD,IAAI,CAAC,eAAe,CAAW,KAAK,CAAC,SAAS,CAAC;SAChD,CAAC,CAAC;QAEH,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACnE,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACnE,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,MAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;QAC5E,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,MAAM,CAAC,WAAW,CACnC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YACd,MAAM,EAAE,GAAG,EAAE,GAAG,IAAI,EAAE,GAAG,CAAC,CAAC;YAC3B,MAAM,IAAI,GAAgB,IAAmB,CAAC;YAC9C,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACrB,CAAC,CAAC,CACH,CAAC;QACF,IAAI,CAAC,KAAK,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,CACzC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CACxC,CAAC;QACF,IAAI,CAAC,KAAK,CAAC,cAAc,GAAG,MAAM,CAAC,WAAW,CAC5C,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YACnB,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,EAAE,GAAG,CAAC,CAAC;YACjC,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC3B,CAAC,CAAC,CACH,CAAC;QACF,IAAI,CAAC,KAAK,CAAC,SAAS,GAAG,MAAM,CAAC,WAAW,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7E,CAAC;IAEO,KAAK,CAAC,sBAAsB;QAClC,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO;QACrB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,eAAe,CACrC,KAAK,CAAC,IAAI,CACX,CAAC;QACF,IAAI;aACD,MAAM,CACL,CAAC,KAAK,EAAE,EAAE,CACR,OAAO,KAAK,CAAC,GAAG,KAAK,QAAQ,IAAI,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC,CACpE;aACA,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;YACjB,MAAM,EAAE,GAAI,KAAK,CAAC,GAAc,CAAC,SAAS,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;YAC9D,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;IACP,CAAC;IAEO,eAAe,CAAI,SAAoB;QAC7C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,IAAI,CAAC,IAAI,CAAC,EAAE;gBAAE,OAAO,OAAO,CAAC,EAAE,CAAC,CAAC;YACjC,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;YACtD,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;YACxC,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC;YAC/B,OAAO,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC9C,OAAO,CAAC,SAAS,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,MAAa,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,GAAG,CACT,SAAoB,EACpB,KAWY;QAEZ,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO;QACrB,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;QACvD,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;QACxC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC;IAEM,YAAY;QACjB,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC;IAClE,CAAC;IAEM,UAAU,CAAC,SAAkB;QAClC,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAAC;IAEM,cAAc,CAAC,SAAiB;QACrC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,EAAE,SAAS,CAAC,CAAC;QAC1D,sCAAsC;QACtC,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO;QACrB,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QACxD,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACzC,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;IACxD,CAAC;IAEM,WAAW,CAAC,EAAU;QAC3B,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO;QACrB,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QACxD,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACzC,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,WAAW,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QACjD,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IAC5C,CAAC;IAEM,YAAY,CAAC,EAAU;QAC5B,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAC3B,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO;QACrB,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QACxD,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACzC,KAAK,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IAC5C,CAAC;IAEM,SAAS,CAAC,EAAU;QACzB,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IACjC,CAAC;IAEM,eAAe,CAAC,QAAoB;QACzC,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACpC,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACtD,CAAC;IAED,0CAA0C;IAE1C;;OAEG;IACI,KAAK,CAAC,SAAS,CAAC,IAAU;QAC/B,MAAM,QAAQ,GAAG;YACf,GAAG,EAAE,SAAS;YACd,KAAK,EAAE,IAAI;YACX,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;SACtB,CAAC;QACF,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IACtC,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,QAAQ;QACnB,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO,IAAI,CAAC;QAE1B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,MAAM,EAAE,GAAG,IAAI,CAAC,EAAG,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;YAC7D,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;YAC9C,MAAM,OAAO,GAAG,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;YAErC,OAAO,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC9C,OAAO,CAAC,SAAS,GAAG,GAAG,EAAE;gBACvB,MAAM,MAAM,GAAG,OAAO,CAAC,MAEV,CAAC;gBACd,IAAI,CAAC,MAAM,EAAE,CAAC;oBACZ,OAAO,CAAC,IAAI,CAAC,CAAC;oBACd,OAAO;gBACT,CAAC;gBAED,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC;gBAC1B,MAAM,WAAW,GAAG,IAAI,CAAC,WAAW,IAAI,CAAC,CAAC;gBAC1C,MAAM,UAAU,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,WAAW;gBAEnD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,WAAW,GAAG,UAAU,EAAE,CAAC;oBAC1C,OAAO,CAAC,IAAI,CAAC,CAAC;gBAChB,CAAC;qBAAM,CAAC;oBACN,8BAA8B;oBAC9B,IAAI,CAAC,SAAS,EAAE,CAAC;oBACjB,OAAO,CAAC,IAAI,CAAC,CAAC;gBAChB,CAAC;YACH,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,SAAS;QACpB,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO;QAErB,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;QAC7D,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QAC9C,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAC1B,CAAC;IAED,iCAAiC;IAEjC;;OAEG;IACI,KAAK,CAAC,eAAe,CAAC,UAA0B;QACrD,MAAM,cAAc,GAAG;YACrB,GAAG,EAAE,SAAS;YACd,KAAK,EAAE,UAAU;YACjB,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;SACtB,CAAC;QACF,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,EAAE,cAAc,CAAC,CAAC;IAC7C,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,cAAc;QACzB,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO,IAAI,CAAC;QAE1B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,MAAM,EAAE,GAAG,IAAI,CAAC,EAAG,CAAC,WAAW,CAAC,KAAK,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;YAC9D,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;YAC/C,MAAM,OAAO,GAAG,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;YAErC,OAAO,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC9C,OAAO,CAAC,SAAS,GAAG,GAAG,EAAE;gBACvB,MAAM,MAAM,GAAG,OAAO,CAAC,MAEV,CAAC;gBACd,OAAO,CAAC,MAAM,EAAE,KAAK,IAAI,IAAI,CAAC,CAAC;YACjC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,eAAe;QAC1B,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO;QAErB,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;QAC9D,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAC/C,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAC1B,CAAC;IAED,+BAA+B;IAE/B;;OAEG;IACI,KAAK,CAAC,YAAY,CAAC,GAAW,EAAE,KAAc;QACnD,MAAM,SAAS,GAAG;YAChB,GAAG;YACH,KAAK;YACL,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;SACtB,CAAC;QACF,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IACtC,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,WAAW,CAAC,GAAW;QAClC,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO,IAAI,CAAC;QAE1B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,MAAM,EAAE,GAAG,IAAI,CAAC,EAAG,CAAC,WAAW,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;YAC5D,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;YAC7C,MAAM,OAAO,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YAE/B,OAAO,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC9C,OAAO,CAAC,SAAS,GAAG,GAAG,EAAE;gBACvB,MAAM,MAAM,GAAG,OAAO,CAAC,MAEV,CAAC;gBACd,OAAO,CAAC,MAAM,EAAE,KAAK,IAAI,IAAI,CAAC,CAAC;YACjC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,YAAY,CAAC,GAAW;QACnC,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO;QAErB,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;QAC5D,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC7C,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC;IAED,+BAA+B;IAE/B;;OAEG;IACI,KAAK,CAAC,WAAW,CAAC,QAAkB;QACzC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC;QAC7C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IACtC,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,cAAc,CAAC,UAAkB;QAC5C,OAAO,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACxC,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO;QAErB,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;QAC7D,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QAC9C,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAC3B,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,gBAAgB,CAAC,MAAc;QAC1C,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO,EAAE,CAAC;QAExB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,MAAM,EAAE,GAAG,IAAI,CAAC,EAAG,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;YAC7D,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;YAC9C,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;YACvC,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAErC,OAAO,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC9C,OAAO,CAAC,SAAS,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,MAAoB,CAAC,CAAC;QAClE,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,sBAAsB,CACjC,MAAc,EACd,IAAwB;QAExB,IAAI,CAAC,IAAI,CAAC,EAAE;YAAE,OAAO,EAAE,CAAC;QAExB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,MAAM,EAAE,GAAG,IAAI,CAAC,EAAG,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;YAC7D,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;YAC9C,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;YACvC,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAErC,OAAO,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC9C,OAAO,CAAC,SAAS,GAAG,GAAG,EAAE;gBACvB,MAAM,SAAS,GAAG,OAAO,CAAC,MAAoB,CAAC;gBAC/C,MAAM,QAAQ,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;gBAC1D,OAAO,CAAC,QAAQ,CAAC,CAAC;YACpB,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACI,YAAY,CACjB,MAAc,EACd,IAAwB,EACxB,QAAgB;QAEhB,MAAM,UAAU,GAAG,GAAG,IAAI,IAAI,QAAQ,EAAE,CAAC;QACzC,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QAClD,OAAO,QAAQ,EAAE,MAAM,KAAK,MAAM,CAAC;IACrC,CAAC;IAED;;OAEG;IACI,WAAW,CAAC,UAAkB;QACnC,OAAO,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;IAC1C,CAAC;IAED;;OAEG;IACI,eAAe;QACpB,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IAC7C,CAAC;CACF;AAED,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/database/schema.d.ts b/packages/core/dist/database/schema.d.ts new file mode 100644 index 0000000..eff3da4 --- /dev/null +++ b/packages/core/dist/database/schema.d.ts @@ -0,0 +1,22 @@ +export declare const DB_NAME = "opchan-local"; +export declare const DB_VERSION = 3; +export declare const STORE: { + readonly CELLS: "cells"; + readonly POSTS: "posts"; + readonly COMMENTS: "comments"; + readonly VOTES: "votes"; + readonly MODERATIONS: "moderations"; + readonly USER_IDENTITIES: "userIdentities"; + readonly USER_AUTH: "userAuth"; + readonly DELEGATION: "delegation"; + readonly UI_STATE: "uiState"; + readonly META: "meta"; + readonly BOOKMARKS: "bookmarks"; +}; +export type StoreName = (typeof STORE)[keyof typeof STORE]; +/** + * Open (and create/upgrade) the IndexedDB database used by LocalDatabase. + * Minimal schema focused on key-based access patterns we already use in memory. + */ +export declare function openLocalDB(): Promise; +//# sourceMappingURL=schema.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/database/schema.d.ts.map b/packages/core/dist/database/schema.d.ts.map new file mode 100644 index 0000000..cfd749d --- /dev/null +++ b/packages/core/dist/database/schema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/database/schema.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,iBAAiB,CAAC;AACtC,eAAO,MAAM,UAAU,IAAI,CAAC;AAE5B,eAAO,MAAM,KAAK;;;;;;;;;;;;CAYR,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,OAAO,KAAK,CAAC,CAAC;AAE3D;;;GAGG;AACH,wBAAgB,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,CA+DlD"} \ No newline at end of file diff --git a/packages/core/dist/database/schema.js b/packages/core/dist/database/schema.js new file mode 100644 index 0000000..88bd361 --- /dev/null +++ b/packages/core/dist/database/schema.js @@ -0,0 +1,81 @@ +export const DB_NAME = 'opchan-local'; +export const DB_VERSION = 3; +export const STORE = { + CELLS: 'cells', + POSTS: 'posts', + COMMENTS: 'comments', + VOTES: 'votes', + MODERATIONS: 'moderations', + USER_IDENTITIES: 'userIdentities', + USER_AUTH: 'userAuth', + DELEGATION: 'delegation', + UI_STATE: 'uiState', + META: 'meta', + BOOKMARKS: 'bookmarks', +}; +/** + * Open (and create/upgrade) the IndexedDB database used by LocalDatabase. + * Minimal schema focused on key-based access patterns we already use in memory. + */ +export function openLocalDB() { + return new Promise((resolve, reject) => { + const request = indexedDB.open(DB_NAME, DB_VERSION); + request.onerror = () => reject(request.error); + request.onsuccess = () => resolve(request.result); + request.onupgradeneeded = () => { + const db = request.result; + // Create stores if they do not exist + if (!db.objectStoreNames.contains(STORE.CELLS)) { + db.createObjectStore(STORE.CELLS, { keyPath: 'id' }); + } + if (!db.objectStoreNames.contains(STORE.POSTS)) { + const store = db.createObjectStore(STORE.POSTS, { keyPath: 'id' }); + // Minimal index to fetch posts by cellId + store.createIndex('by_cellId', 'cellId', { unique: false }); + } + if (!db.objectStoreNames.contains(STORE.COMMENTS)) { + const store = db.createObjectStore(STORE.COMMENTS, { keyPath: 'id' }); + // Minimal index to fetch comments by postId + store.createIndex('by_postId', 'postId', { unique: false }); + } + if (!db.objectStoreNames.contains(STORE.VOTES)) { + // Votes are keyed by composite key `${targetId}:${author}` + db.createObjectStore(STORE.VOTES, { keyPath: 'key' }); + } + if (!db.objectStoreNames.contains(STORE.MODERATIONS)) { + // Moderations keyed by targetId + db.createObjectStore(STORE.MODERATIONS, { keyPath: 'targetId' }); + } + if (!db.objectStoreNames.contains(STORE.USER_IDENTITIES)) { + // User identities keyed by address + db.createObjectStore(STORE.USER_IDENTITIES, { keyPath: 'address' }); + } + if (!db.objectStoreNames.contains(STORE.USER_AUTH)) { + // User authentication data with single key 'current' + db.createObjectStore(STORE.USER_AUTH, { keyPath: 'key' }); + } + if (!db.objectStoreNames.contains(STORE.DELEGATION)) { + // Key delegation information with single key 'current' + db.createObjectStore(STORE.DELEGATION, { keyPath: 'key' }); + } + if (!db.objectStoreNames.contains(STORE.UI_STATE)) { + // UI state like wizard flags, preferences + db.createObjectStore(STORE.UI_STATE, { keyPath: 'key' }); + } + if (!db.objectStoreNames.contains(STORE.META)) { + // Misc metadata like lastSync timestamps + db.createObjectStore(STORE.META, { keyPath: 'key' }); + } + if (!db.objectStoreNames.contains(STORE.BOOKMARKS)) { + const store = db.createObjectStore(STORE.BOOKMARKS, { keyPath: 'id' }); + // Index to fetch bookmarks by user + store.createIndex('by_userId', 'userId', { unique: false }); + // Index to fetch bookmarks by type + store.createIndex('by_type', 'type', { unique: false }); + // Index to fetch bookmarks by targetId + store.createIndex('by_targetId', 'targetId', { unique: false }); + } + }; + }); +} +//# sourceMappingURL=schema.js.map \ No newline at end of file diff --git a/packages/core/dist/database/schema.js.map b/packages/core/dist/database/schema.js.map new file mode 100644 index 0000000..b9ffb20 --- /dev/null +++ b/packages/core/dist/database/schema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/database/schema.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,cAAc,CAAC;AACtC,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,CAAC;AAE5B,MAAM,CAAC,MAAM,KAAK,GAAG;IACnB,KAAK,EAAE,OAAO;IACd,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,UAAU;IACpB,KAAK,EAAE,OAAO;IACd,WAAW,EAAE,aAAa;IAC1B,eAAe,EAAE,gBAAgB;IACjC,SAAS,EAAE,UAAU;IACrB,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,SAAS;IACnB,IAAI,EAAE,MAAM;IACZ,SAAS,EAAE,WAAW;CACd,CAAC;AAIX;;;GAGG;AACH,MAAM,UAAU,WAAW;IACzB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,OAAO,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;QAEpD,OAAO,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAC9C,OAAO,CAAC,SAAS,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAElD,OAAO,CAAC,eAAe,GAAG,GAAG,EAAE;YAC7B,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;YAE1B,qCAAqC;YACrC,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;gBAC/C,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;YACvD,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;gBAC/C,MAAM,KAAK,GAAG,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;gBACnE,yCAAyC;gBACzC,KAAK,CAAC,WAAW,CAAC,WAAW,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;YAC9D,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;gBAClD,MAAM,KAAK,GAAG,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;gBACtE,4CAA4C;gBAC5C,KAAK,CAAC,WAAW,CAAC,WAAW,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;YAC9D,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;gBAC/C,2DAA2D;gBAC3D,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YACxD,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,CAAC;gBACrD,gCAAgC;gBAChC,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,CAAC;YACnE,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,eAAe,CAAC,EAAE,CAAC;gBACzD,mCAAmC;gBACnC,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,eAAe,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,CAAC;YACtE,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC;gBACnD,qDAAqD;gBACrD,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YAC5D,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC;gBACpD,uDAAuD;gBACvD,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,UAAU,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YAC7D,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;gBAClD,0CAA0C;gBAC1C,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YAC3D,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC9C,yCAAyC;gBACzC,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YACvD,CAAC;YACD,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC;gBACnD,MAAM,KAAK,GAAG,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;gBACvE,mCAAmC;gBACnC,KAAK,CAAC,WAAW,CAAC,WAAW,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;gBAC5D,mCAAmC;gBACnC,KAAK,CAAC,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;gBACxD,uCAAuC;gBACvC,KAAK,CAAC,WAAW,CAAC,aAAa,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;YAClE,CAAC;QACH,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/delegation/crypto.d.ts b/packages/core/dist/delegation/crypto.d.ts new file mode 100644 index 0000000..11c6632 --- /dev/null +++ b/packages/core/dist/delegation/crypto.d.ts @@ -0,0 +1,48 @@ +/** + * Delegation-specific cryptographic utilities + * Handles all cryptographic operations: key generation, signing, verification + */ +export declare class DelegationCrypto { + /** + * Create a standardized delegation authorization message + * @param browserPublicKey - The browser public key being authorized + * @param walletAddress - The wallet address doing the authorization + * @param expiryTimestamp - When the delegation expires + * @param nonce - Unique nonce for replay protection + * @returns string - The authorization message to be signed + */ + static createAuthMessage(browserPublicKey: string, walletAddress: string, expiryTimestamp: number, nonce: string): string; + /** + * Verify a wallet signature using WalletManager + * @param authMessage - The message that was signed + * @param walletSignature - The signature to verify + * @param walletAddress - The wallet address that signed + * @param walletType - The type of wallet + * @returns Promise - True if signature is valid + */ + static verifyWalletSignature(authMessage: string, walletSignature: string, walletAddress: string, walletType: 'bitcoin' | 'ethereum'): Promise; + /** + * Generate a new browser-based keypair for signing messages + * @returns Object with public and private keys in hex format + */ + static generateKeypair(): { + publicKey: string; + privateKey: string; + }; + /** + * Sign a raw string message using a private key + * @param message - The message to sign + * @param privateKeyHex - The private key in hex format + * @returns The signature in hex format or null if signing fails + */ + static signRaw(message: string, privateKeyHex: string): string | null; + /** + * Verify a signature made with a public key + * @param message - The original message + * @param signature - The signature to verify in hex format + * @param publicKey - The public key in hex format + * @returns True if signature is valid + */ + static verifyRaw(message: string, signature: string, publicKey: string): boolean; +} +//# sourceMappingURL=crypto.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/delegation/crypto.d.ts.map b/packages/core/dist/delegation/crypto.d.ts.map new file mode 100644 index 0000000..dbf9ada --- /dev/null +++ b/packages/core/dist/delegation/crypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../src/delegation/crypto.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,qBAAa,gBAAgB;IAC3B;;;;;;;OAOG;IACH,MAAM,CAAC,iBAAiB,CACtB,gBAAgB,EAAE,MAAM,EACxB,aAAa,EAAE,MAAM,EACrB,eAAe,EAAE,MAAM,EACvB,KAAK,EAAE,MAAM,GACZ,MAAM;IAIT;;;;;;;OAOG;WACU,qBAAqB,CAChC,WAAW,EAAE,MAAM,EACnB,eAAe,EAAE,MAAM,EACvB,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,SAAS,GAAG,UAAU,GACjC,OAAO,CAAC,OAAO,CAAC;IAcnB;;;OAGG;IACH,MAAM,CAAC,eAAe,IAAI;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE;IAanE;;;;;OAKG;IACH,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IAarE;;;;;;OAMG;IACH,MAAM,CAAC,SAAS,CACd,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB,OAAO;CAYX"} \ No newline at end of file diff --git a/packages/core/dist/delegation/crypto.js b/packages/core/dist/delegation/crypto.js new file mode 100644 index 0000000..26cd239 --- /dev/null +++ b/packages/core/dist/delegation/crypto.js @@ -0,0 +1,89 @@ +import * as ed from '@noble/ed25519'; +import { bytesToHex, hexToBytes } from '../utils'; +import { WalletManager } from '../wallet'; +/** + * Delegation-specific cryptographic utilities + * Handles all cryptographic operations: key generation, signing, verification + */ +export class DelegationCrypto { + /** + * Create a standardized delegation authorization message + * @param browserPublicKey - The browser public key being authorized + * @param walletAddress - The wallet address doing the authorization + * @param expiryTimestamp - When the delegation expires + * @param nonce - Unique nonce for replay protection + * @returns string - The authorization message to be signed + */ + static createAuthMessage(browserPublicKey, walletAddress, expiryTimestamp, nonce) { + return `I, ${walletAddress}, authorize browser key ${browserPublicKey} until ${expiryTimestamp} (nonce: ${nonce})`; + } + /** + * Verify a wallet signature using WalletManager + * @param authMessage - The message that was signed + * @param walletSignature - The signature to verify + * @param walletAddress - The wallet address that signed + * @param walletType - The type of wallet + * @returns Promise - True if signature is valid + */ + static async verifyWalletSignature(authMessage, walletSignature, walletAddress, walletType) { + try { + return await WalletManager.verifySignature(authMessage, walletSignature, walletAddress, walletType); + } + catch (error) { + console.error('Error verifying wallet signature:', error); + return false; + } + } + /** + * Generate a new browser-based keypair for signing messages + * @returns Object with public and private keys in hex format + */ + static generateKeypair() { + const privateKey = ed.utils.randomSecretKey(); + const privateKeyHex = bytesToHex(privateKey); + const publicKey = ed.getPublicKey(privateKey); + const publicKeyHex = bytesToHex(publicKey); + return { + privateKey: privateKeyHex, + publicKey: publicKeyHex, + }; + } + /** + * Sign a raw string message using a private key + * @param message - The message to sign + * @param privateKeyHex - The private key in hex format + * @returns The signature in hex format or null if signing fails + */ + static signRaw(message, privateKeyHex) { + try { + const privateKeyBytes = hexToBytes(privateKeyHex); + const messageBytes = new TextEncoder().encode(message); + const signature = ed.sign(messageBytes, privateKeyBytes); + return bytesToHex(signature); + } + catch (error) { + console.error('Error signing with private key:', error); + return null; + } + } + /** + * Verify a signature made with a public key + * @param message - The original message + * @param signature - The signature to verify in hex format + * @param publicKey - The public key in hex format + * @returns True if signature is valid + */ + static verifyRaw(message, signature, publicKey) { + try { + const messageBytes = new TextEncoder().encode(message); + const signatureBytes = hexToBytes(signature); + const publicKeyBytes = hexToBytes(publicKey); + return ed.verify(signatureBytes, messageBytes, publicKeyBytes); + } + catch (error) { + console.error('Error verifying signature:', error); + return false; + } + } +} +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/packages/core/dist/delegation/crypto.js.map b/packages/core/dist/delegation/crypto.js.map new file mode 100644 index 0000000..68e8fa5 --- /dev/null +++ b/packages/core/dist/delegation/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../src/delegation/crypto.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE1C;;;GAGG;AACH,MAAM,OAAO,gBAAgB;IAC3B;;;;;;;OAOG;IACH,MAAM,CAAC,iBAAiB,CACtB,gBAAwB,EACxB,aAAqB,EACrB,eAAuB,EACvB,KAAa;QAEb,OAAO,MAAM,aAAa,2BAA2B,gBAAgB,UAAU,eAAe,YAAY,KAAK,GAAG,CAAC;IACrH,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,KAAK,CAAC,qBAAqB,CAChC,WAAmB,EACnB,eAAuB,EACvB,aAAqB,EACrB,UAAkC;QAElC,IAAI,CAAC;YACH,OAAO,MAAM,aAAa,CAAC,eAAe,CACxC,WAAW,EACX,eAAe,EACf,aAAa,EACb,UAAU,CACX,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;YAC1D,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,eAAe;QACpB,MAAM,UAAU,GAAG,EAAE,CAAC,KAAK,CAAC,eAAe,EAAE,CAAC;QAC9C,MAAM,aAAa,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;QAE7C,MAAM,SAAS,GAAG,EAAE,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;QAC9C,MAAM,YAAY,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;QAE3C,OAAO;YACL,UAAU,EAAE,aAAa;YACzB,SAAS,EAAE,YAAY;SACxB,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,OAAO,CAAC,OAAe,EAAE,aAAqB;QACnD,IAAI,CAAC;YACH,MAAM,eAAe,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;YAClD,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAEvD,MAAM,SAAS,GAAG,EAAE,CAAC,IAAI,CAAC,YAAY,EAAE,eAAe,CAAC,CAAC;YACzD,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QAC/B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;YACxD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,SAAS,CACd,OAAe,EACf,SAAiB,EACjB,SAAiB;QAEjB,IAAI,CAAC;YACH,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YACvD,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;YAC7C,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;YAE7C,OAAO,EAAE,CAAC,MAAM,CAAC,cAAc,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC;QACjE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,KAAK,CAAC,CAAC;YACnD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/delegation/index.d.ts b/packages/core/dist/delegation/index.d.ts new file mode 100644 index 0000000..3658858 --- /dev/null +++ b/packages/core/dist/delegation/index.d.ts @@ -0,0 +1,48 @@ +import { OpchanMessage } from '../types/forum'; +import { UnsignedMessage } from '../types/waku'; +import { DelegationDuration, DelegationStatus } from './types'; +import { DelegationStorage } from './storage'; +export interface DelegationFullStatus extends DelegationStatus { + publicKey?: string; + address?: string; + walletType?: 'bitcoin' | 'ethereum'; +} +export declare class DelegationManager { + private cachedDelegation; + private cachedAt; + private static readonly CACHE_TTL_MS; + private static readonly DURATION_HOURS; + static getDurationHours(duration: DelegationDuration): number; + /** + * Create a delegation with cryptographic proof + */ + delegate(address: string, walletType: 'bitcoin' | 'ethereum', duration: DelegationDuration | undefined, signFunction: (message: string) => Promise): Promise; + /** + * Sign a message with delegated key + */ + signMessage(message: UnsignedMessage): Promise; + /** + * Verify a signed message + */ + verify(message: OpchanMessage): Promise; + /** + * Get delegation status + */ + getStatus(currentAddress?: string, currentWalletType?: 'bitcoin' | 'ethereum'): Promise; + /** + * Clear stored delegation + */ + clear(): Promise; + /** + * Create delegation proof from stored info + */ + private createProof; + /** + * Verify delegation proof + */ + private verifyProof; +} +export declare const delegationManager: DelegationManager; +export * from './types'; +export { DelegationStorage }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/delegation/index.d.ts.map b/packages/core/dist/delegation/index.d.ts.map new file mode 100644 index 0000000..28a7e0c --- /dev/null +++ b/packages/core/dist/delegation/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/delegation/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EACL,kBAAkB,EAElB,gBAAgB,EAEjB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAG9C,MAAM,WAAW,oBAAqB,SAAQ,gBAAgB;IAC5D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,SAAS,GAAG,UAAU,CAAC;CACrC;AAED,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,gBAAgB,CAA+B;IACvD,OAAO,CAAC,QAAQ,CAAa;IAC7B,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAY;IAChD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAG3B;IAEX,MAAM,CAAC,gBAAgB,CAAC,QAAQ,EAAE,kBAAkB,GAAG,MAAM;IAQ7D;;OAEG;IACG,QAAQ,CACZ,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,SAAS,GAAG,UAAU,EAClC,QAAQ,EAAE,kBAAkB,YAAU,EACtC,YAAY,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GACjD,OAAO,CAAC,OAAO,CAAC;IAwCnB;;OAEG;IACG,WAAW,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;IAoC1E;;OAEG;IACG,MAAM,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC;IAqCtD;;OAEG;IACG,SAAS,CACb,cAAc,CAAC,EAAE,MAAM,EACvB,iBAAiB,CAAC,EAAE,SAAS,GAAG,UAAU,GACzC,OAAO,CAAC,oBAAoB,CAAC;IAkChC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAQ5B;;OAEG;IACH,OAAO,CAAC,WAAW;IAUnB;;OAEG;YACW,WAAW;CAiC1B;AAGD,eAAO,MAAM,iBAAiB,mBAA0B,CAAC;AACzD,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/delegation/index.js b/packages/core/dist/delegation/index.js new file mode 100644 index 0000000..8dd4c4b --- /dev/null +++ b/packages/core/dist/delegation/index.js @@ -0,0 +1,184 @@ +import { DelegationStorage } from './storage'; +import { DelegationCrypto } from './crypto'; +export class DelegationManager { + constructor() { + this.cachedDelegation = null; + this.cachedAt = 0; + } + static getDurationHours(duration) { + return DelegationManager.DURATION_HOURS[duration]; + } + // ============================================================================ + // PUBLIC API + // ============================================================================ + /** + * Create a delegation with cryptographic proof + */ + async delegate(address, walletType, duration = '7days', signFunction) { + try { + // Generate browser keypair + const keypair = DelegationCrypto.generateKeypair(); + // Create expiry and nonce + const expiryTimestamp = Date.now() + + DelegationManager.getDurationHours(duration) * 60 * 60 * 1000; + const nonce = crypto.randomUUID(); + // Create and sign authorization message + const authMessage = DelegationCrypto.createAuthMessage(keypair.publicKey, address, expiryTimestamp, nonce); + const walletSignature = await signFunction(authMessage); + // Store delegation + const delegationInfo = { + authMessage, + walletSignature, + expiryTimestamp, + walletAddress: address, + walletType, + browserPublicKey: keypair.publicKey, + browserPrivateKey: keypair.privateKey, + nonce, + }; + await DelegationStorage.store(delegationInfo); + return true; + } + catch (error) { + console.error('Error creating delegation:', error); + return false; + } + } + /** + * Sign a message with delegated key + */ + async signMessage(message) { + const now = Date.now(); + if (!this.cachedDelegation || + now - this.cachedAt > DelegationManager.CACHE_TTL_MS) { + this.cachedDelegation = await DelegationStorage.retrieve(); + this.cachedAt = now; + } + const delegation = this.cachedDelegation; + if (!delegation || Date.now() >= delegation.expiryTimestamp) { + return null; + } + // Sign message content + const messageToSign = JSON.stringify({ + ...message, + signature: undefined, + browserPubKey: undefined, + delegationProof: undefined, + }); + const signature = DelegationCrypto.signRaw(messageToSign, delegation.browserPrivateKey); + if (!signature) + return null; + return { + ...message, + signature, + browserPubKey: delegation.browserPublicKey, + delegationProof: this.createProof(delegation), + }; + } + /** + * Verify a signed message + */ + async verify(message) { + // Check required fields + if (!message.signature || + !message.browserPubKey || + !message.delegationProof || + !message.author) { + return false; + } + // Verify message signature + const signedContent = JSON.stringify({ + ...message, + signature: undefined, + browserPubKey: undefined, + delegationProof: undefined, + }); + if (!DelegationCrypto.verifyRaw(signedContent, message.signature, message.browserPubKey)) { + return false; + } + // Verify delegation proof + return await this.verifyProof(message.delegationProof, message.browserPubKey, message.author); + } + /** + * Get delegation status + */ + async getStatus(currentAddress, currentWalletType) { + const now = Date.now(); + if (!this.cachedDelegation || + now - this.cachedAt > DelegationManager.CACHE_TTL_MS) { + this.cachedDelegation = await DelegationStorage.retrieve(); + this.cachedAt = now; + } + const delegation = this.cachedDelegation; + if (!delegation) { + return { hasDelegation: false, isValid: false }; + } + const hasExpired = now >= delegation.expiryTimestamp; + const addressMatches = !currentAddress || delegation.walletAddress === currentAddress; + const walletTypeMatches = !currentWalletType || delegation.walletType === currentWalletType; + const isValid = !hasExpired && addressMatches && walletTypeMatches; + return { + hasDelegation: true, + isValid, + timeRemaining: isValid + ? Math.max(0, delegation.expiryTimestamp - now) + : undefined, + publicKey: delegation.browserPublicKey, + address: delegation.walletAddress, + walletType: delegation.walletType, + proof: isValid ? this.createProof(delegation) : undefined, + }; + } + /** + * Clear stored delegation + */ + async clear() { + await DelegationStorage.clear(); + } + // ============================================================================ + // PRIVATE HELPERS + // ============================================================================ + /** + * Create delegation proof from stored info + */ + createProof(delegation) { + return { + authMessage: delegation.authMessage, + walletSignature: delegation.walletSignature, + expiryTimestamp: delegation.expiryTimestamp, + walletAddress: delegation.walletAddress, + walletType: delegation.walletType, + }; + } + /** + * Verify delegation proof + */ + async verifyProof(proof, expectedBrowserKey, expectedWalletAddress) { + // Basic validation + if (!proof?.walletAddress || + !proof?.authMessage || + proof?.expiryTimestamp === undefined || + proof.walletAddress !== expectedWalletAddress || + Date.now() >= proof.expiryTimestamp) { + return false; + } + // Verify auth message format + if (!proof.authMessage.includes(expectedWalletAddress) || + !proof.authMessage.includes(expectedBrowserKey) || + !proof.authMessage.includes(proof.expiryTimestamp.toString())) { + return false; + } + // Verify wallet signature + return await DelegationCrypto.verifyWalletSignature(proof.authMessage, proof.walletSignature, proof.walletAddress, proof.walletType); + } +} +DelegationManager.CACHE_TTL_MS = 5 * 1000; // 5s to avoid hot-looping +DelegationManager.DURATION_HOURS = { + '7days': 24 * 7, + '30days': 24 * 30, +}; +// Export singleton instance +export const delegationManager = new DelegationManager(); +export * from './types'; +export { DelegationStorage }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/core/dist/delegation/index.js.map b/packages/core/dist/delegation/index.js.map new file mode 100644 index 0000000..d73c6f5 --- /dev/null +++ b/packages/core/dist/delegation/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/delegation/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAQ5C,MAAM,OAAO,iBAAiB;IAA9B;QACU,qBAAgB,GAA0B,IAAI,CAAC;QAC/C,aAAQ,GAAW,CAAC,CAAC;IAkP/B,CAAC;IA3OC,MAAM,CAAC,gBAAgB,CAAC,QAA4B;QAClD,OAAO,iBAAiB,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;IACpD,CAAC;IAED,+EAA+E;IAC/E,aAAa;IACb,+EAA+E;IAE/E;;OAEG;IACH,KAAK,CAAC,QAAQ,CACZ,OAAe,EACf,UAAkC,EAClC,WAA+B,OAAO,EACtC,YAAkD;QAElD,IAAI,CAAC;YACH,2BAA2B;YAC3B,MAAM,OAAO,GAAG,gBAAgB,CAAC,eAAe,EAAE,CAAC;YAEnD,0BAA0B;YAC1B,MAAM,eAAe,GACnB,IAAI,CAAC,GAAG,EAAE;gBACV,iBAAiB,CAAC,gBAAgB,CAAC,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;YAChE,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;YAElC,wCAAwC;YACxC,MAAM,WAAW,GAAG,gBAAgB,CAAC,iBAAiB,CACpD,OAAO,CAAC,SAAS,EACjB,OAAO,EACP,eAAe,EACf,KAAK,CACN,CAAC;YACF,MAAM,eAAe,GAAG,MAAM,YAAY,CAAC,WAAW,CAAC,CAAC;YAExD,mBAAmB;YACnB,MAAM,cAAc,GAAmB;gBACrC,WAAW;gBACX,eAAe;gBACf,eAAe;gBACf,aAAa,EAAE,OAAO;gBACtB,UAAU;gBACV,gBAAgB,EAAE,OAAO,CAAC,SAAS;gBACnC,iBAAiB,EAAE,OAAO,CAAC,UAAU;gBACrC,KAAK;aACN,CAAC;YAEF,MAAM,iBAAiB,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;YAC9C,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,KAAK,CAAC,CAAC;YACnD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,WAAW,CAAC,OAAwB;QACxC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IACE,CAAC,IAAI,CAAC,gBAAgB;YACtB,GAAG,GAAG,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC,YAAY,EACpD,CAAC;YACD,IAAI,CAAC,gBAAgB,GAAG,MAAM,iBAAiB,CAAC,QAAQ,EAAE,CAAC;YAC3D,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC;QACtB,CAAC;QACD,MAAM,UAAU,GAAG,IAAI,CAAC,gBAAgB,CAAC;QACzC,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,eAAe,EAAE,CAAC;YAC5D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,uBAAuB;QACvB,MAAM,aAAa,GAAG,IAAI,CAAC,SAAS,CAAC;YACnC,GAAG,OAAO;YACV,SAAS,EAAE,SAAS;YACpB,aAAa,EAAE,SAAS;YACxB,eAAe,EAAE,SAAS;SAC3B,CAAC,CAAC;QAEH,MAAM,SAAS,GAAG,gBAAgB,CAAC,OAAO,CACxC,aAAa,EACb,UAAU,CAAC,iBAAiB,CAC7B,CAAC;QACF,IAAI,CAAC,SAAS;YAAE,OAAO,IAAI,CAAC;QAE5B,OAAO;YACL,GAAG,OAAO;YACV,SAAS;YACT,aAAa,EAAE,UAAU,CAAC,gBAAgB;YAC1C,eAAe,EAAE,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC;SAC7B,CAAC;IACrB,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,MAAM,CAAC,OAAsB;QACjC,wBAAwB;QACxB,IACE,CAAC,OAAO,CAAC,SAAS;YAClB,CAAC,OAAO,CAAC,aAAa;YACtB,CAAC,OAAO,CAAC,eAAe;YACxB,CAAC,OAAO,CAAC,MAAM,EACf,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,2BAA2B;QAC3B,MAAM,aAAa,GAAG,IAAI,CAAC,SAAS,CAAC;YACnC,GAAG,OAAO;YACV,SAAS,EAAE,SAAS;YACpB,aAAa,EAAE,SAAS;YACxB,eAAe,EAAE,SAAS;SAC3B,CAAC,CAAC;QAEH,IACE,CAAC,gBAAgB,CAAC,SAAS,CACzB,aAAa,EACb,OAAO,CAAC,SAAS,EACjB,OAAO,CAAC,aAAa,CACtB,EACD,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,0BAA0B;QAC1B,OAAO,MAAM,IAAI,CAAC,WAAW,CAC3B,OAAO,CAAC,eAAe,EACvB,OAAO,CAAC,aAAa,EACrB,OAAO,CAAC,MAAM,CACf,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,SAAS,CACb,cAAuB,EACvB,iBAA0C;QAE1C,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IACE,CAAC,IAAI,CAAC,gBAAgB;YACtB,GAAG,GAAG,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC,YAAY,EACpD,CAAC;YACD,IAAI,CAAC,gBAAgB,GAAG,MAAM,iBAAiB,CAAC,QAAQ,EAAE,CAAC;YAC3D,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC;QACtB,CAAC;QACD,MAAM,UAAU,GAAG,IAAI,CAAC,gBAAgB,CAAC;QACzC,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QAClD,CAAC;QAED,MAAM,UAAU,GAAG,GAAG,IAAI,UAAU,CAAC,eAAe,CAAC;QACrD,MAAM,cAAc,GAClB,CAAC,cAAc,IAAI,UAAU,CAAC,aAAa,KAAK,cAAc,CAAC;QACjE,MAAM,iBAAiB,GACrB,CAAC,iBAAiB,IAAI,UAAU,CAAC,UAAU,KAAK,iBAAiB,CAAC;QACpE,MAAM,OAAO,GAAG,CAAC,UAAU,IAAI,cAAc,IAAI,iBAAiB,CAAC;QAEnE,OAAO;YACL,aAAa,EAAE,IAAI;YACnB,OAAO;YACP,aAAa,EAAE,OAAO;gBACpB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC,eAAe,GAAG,GAAG,CAAC;gBAC/C,CAAC,CAAC,SAAS;YACb,SAAS,EAAE,UAAU,CAAC,gBAAgB;YACtC,OAAO,EAAE,UAAU,CAAC,aAAa;YACjC,UAAU,EAAE,UAAU,CAAC,UAAU;YACjC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS;SAC1D,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,KAAK;QACT,MAAM,iBAAiB,CAAC,KAAK,EAAE,CAAC;IAClC,CAAC;IAED,+EAA+E;IAC/E,kBAAkB;IAClB,+EAA+E;IAE/E;;OAEG;IACK,WAAW,CAAC,UAA0B;QAC5C,OAAO;YACL,WAAW,EAAE,UAAU,CAAC,WAAW;YACnC,eAAe,EAAE,UAAU,CAAC,eAAe;YAC3C,eAAe,EAAE,UAAU,CAAC,eAAe;YAC3C,aAAa,EAAE,UAAU,CAAC,aAAa;YACvC,UAAU,EAAE,UAAU,CAAC,UAAU;SAClC,CAAC;IACJ,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,WAAW,CACvB,KAAsB,EACtB,kBAA0B,EAC1B,qBAA6B;QAE7B,mBAAmB;QACnB,IACE,CAAC,KAAK,EAAE,aAAa;YACrB,CAAC,KAAK,EAAE,WAAW;YACnB,KAAK,EAAE,eAAe,KAAK,SAAS;YACpC,KAAK,CAAC,aAAa,KAAK,qBAAqB;YAC7C,IAAI,CAAC,GAAG,EAAE,IAAI,KAAK,CAAC,eAAe,EACnC,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,6BAA6B;QAC7B,IACE,CAAC,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,qBAAqB,CAAC;YAClD,CAAC,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,kBAAkB,CAAC;YAC/C,CAAC,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC,eAAe,CAAC,QAAQ,EAAE,CAAC,EAC7D,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,0BAA0B;QAC1B,OAAO,MAAM,gBAAgB,CAAC,qBAAqB,CACjD,KAAK,CAAC,WAAW,EACjB,KAAK,CAAC,eAAe,EACrB,KAAK,CAAC,aAAa,EACnB,KAAK,CAAC,UAAU,CACjB,CAAC;IACJ,CAAC;;AAhPuB,8BAAY,GAAG,CAAC,GAAG,IAAI,AAAX,CAAY,CAAC,0BAA0B;AACnD,gCAAc,GAAG;IACvC,OAAO,EAAE,EAAE,GAAG,CAAC;IACf,QAAQ,EAAE,EAAE,GAAG,EAAE;CACT,AAH4B,CAG3B;AA+Ob,4BAA4B;AAC5B,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAAE,CAAC;AACzD,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/delegation/storage.d.ts b/packages/core/dist/delegation/storage.d.ts new file mode 100644 index 0000000..0ed71ae --- /dev/null +++ b/packages/core/dist/delegation/storage.d.ts @@ -0,0 +1,16 @@ +import { DelegationInfo } from './types'; +export declare class DelegationStorage { + /** + * Store delegation information in IndexedDB + */ + static store(delegation: DelegationInfo): Promise; + /** + * Retrieve delegation information from IndexedDB + */ + static retrieve(): Promise; + /** + * Clear stored delegation information + */ + static clear(): Promise; +} +//# sourceMappingURL=storage.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/delegation/storage.d.ts.map b/packages/core/dist/delegation/storage.d.ts.map new file mode 100644 index 0000000..af638e7 --- /dev/null +++ b/packages/core/dist/delegation/storage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../src/delegation/storage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,qBAAa,iBAAiB;IAC5B;;OAEG;WACU,KAAK,CAAC,UAAU,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAa7D;;OAEG;WACU,QAAQ,IAAI,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IAavD;;OAEG;WACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAOpC"} \ No newline at end of file diff --git a/packages/core/dist/delegation/storage.js b/packages/core/dist/delegation/storage.js new file mode 100644 index 0000000..b131b8c --- /dev/null +++ b/packages/core/dist/delegation/storage.js @@ -0,0 +1,46 @@ +import { localDatabase } from '../database/LocalDatabase'; +export class DelegationStorage { + /** + * Store delegation information in IndexedDB + */ + static async store(delegation) { + // Reduce verbose logging in production; keep minimal signal + if (process.env.NODE_ENV !== 'production') { + console.log('DelegationStorage.store'); + } + try { + await localDatabase.storeDelegation(delegation); + } + catch (e) { + console.error('Failed to store delegation information', e); + } + } + /** + * Retrieve delegation information from IndexedDB + */ + static async retrieve() { + try { + const delegation = await localDatabase.loadDelegation(); + if (process.env.NODE_ENV !== 'production') { + console.log('DelegationStorage.retrieve'); + } + return delegation; + } + catch (e) { + console.error('Failed to retrieve delegation information', e); + return null; + } + } + /** + * Clear stored delegation information + */ + static async clear() { + try { + await localDatabase.clearDelegation(); + } + catch (e) { + console.error('Failed to clear delegation information', e); + } + } +} +//# sourceMappingURL=storage.js.map \ No newline at end of file diff --git a/packages/core/dist/delegation/storage.js.map b/packages/core/dist/delegation/storage.js.map new file mode 100644 index 0000000..aae04a4 --- /dev/null +++ b/packages/core/dist/delegation/storage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/delegation/storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAG1D,MAAM,OAAO,iBAAiB;IAC5B;;OAEG;IACH,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,UAA0B;QAC3C,4DAA4D;QAC5D,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;YAC1C,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;QACzC,CAAC;QAED,IAAI,CAAC;YACH,MAAM,aAAa,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC;QAClD,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,CAAC,KAAK,CAAC,wCAAwC,EAAE,CAAC,CAAC,CAAC;QAC7D,CAAC;IACH,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,KAAK,CAAC,QAAQ;QACnB,IAAI,CAAC;YACH,MAAM,UAAU,GAAG,MAAM,aAAa,CAAC,cAAc,EAAE,CAAC;YACxD,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;gBAC1C,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;YAC5C,CAAC;YACD,OAAO,UAAU,CAAC;QACpB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,CAAC,KAAK,CAAC,2CAA2C,EAAE,CAAC,CAAC,CAAC;YAC9D,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,KAAK,CAAC,KAAK;QAChB,IAAI,CAAC;YACH,MAAM,aAAa,CAAC,eAAe,EAAE,CAAC;QACxC,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,CAAC,KAAK,CAAC,wCAAwC,EAAE,CAAC,CAAC,CAAC;QAC7D,CAAC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/delegation/types.d.ts b/packages/core/dist/delegation/types.d.ts new file mode 100644 index 0000000..24cda0a --- /dev/null +++ b/packages/core/dist/delegation/types.d.ts @@ -0,0 +1,29 @@ +export type DelegationDuration = '7days' | '30days'; +/** + * Cryptographic proof that a wallet authorized a browser key + */ +export interface DelegationProof { + authMessage: string; + walletSignature: string; + expiryTimestamp: number; + walletAddress: string; + walletType: 'bitcoin' | 'ethereum'; +} +/** + * Complete delegation information including private key (stored locally) + */ +export interface DelegationInfo extends DelegationProof { + browserPublicKey: string; + browserPrivateKey: string; + nonce: string; +} +/** + * Status of current delegation + */ +export interface DelegationStatus { + hasDelegation: boolean; + isValid: boolean; + timeRemaining?: number; + proof?: DelegationProof; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/delegation/types.d.ts.map b/packages/core/dist/delegation/types.d.ts.map new file mode 100644 index 0000000..4242559 --- /dev/null +++ b/packages/core/dist/delegation/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/delegation/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,kBAAkB,GAAG,OAAO,GAAG,QAAQ,CAAC;AAEpD;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,SAAS,GAAG,UAAU,CAAC;CACpC;AAED;;GAEG;AACH,MAAM,WAAW,cAAe,SAAQ,eAAe;IACrD,gBAAgB,EAAE,MAAM,CAAC;IACzB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,aAAa,EAAE,OAAO,CAAC;IACvB,OAAO,EAAE,OAAO,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,KAAK,CAAC,EAAE,eAAe,CAAC;CACzB"} \ No newline at end of file diff --git a/packages/core/dist/delegation/types.js b/packages/core/dist/delegation/types.js new file mode 100644 index 0000000..718fd38 --- /dev/null +++ b/packages/core/dist/delegation/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/packages/core/dist/delegation/types.js.map b/packages/core/dist/delegation/types.js.map new file mode 100644 index 0000000..450b40f --- /dev/null +++ b/packages/core/dist/delegation/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/delegation/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/core/dist/forum/ForumActions.d.ts b/packages/core/dist/forum/ForumActions.d.ts new file mode 100644 index 0000000..61fa96b --- /dev/null +++ b/packages/core/dist/forum/ForumActions.d.ts @@ -0,0 +1,65 @@ +import { Cell, Comment, Post } from '../types/forum'; +import { User } from '../types/identity'; +import { DelegationManager } from '../delegation'; +type ActionResult = { + success: boolean; + data?: T; + error?: string; +}; +export declare class ForumActions { + private delegationManager; + constructor(delegationManager?: DelegationManager); + /** + * Unified permission validation system + */ + private validatePermission; + createPost(params: PostCreationParams, updateStateFromCache: () => void): Promise>; + createComment(params: CommentCreationParams, updateStateFromCache: () => void): Promise>; + createCell(params: CellCreationParams, updateStateFromCache: () => void): Promise>; + vote(params: VoteParams, updateStateFromCache: () => void): Promise>; + moderatePost(params: PostModerationParams, updateStateFromCache: () => void): Promise>; + moderateComment(params: CommentModerationParams, updateStateFromCache: () => void): Promise>; + moderateUser(params: UserModerationParams, updateStateFromCache: () => void): Promise>; +} +interface BaseActionParams { + currentUser: User | null; + isAuthenticated: boolean; +} +interface PostCreationParams extends BaseActionParams { + cellId: string; + title: string; + content: string; +} +interface CommentCreationParams extends BaseActionParams { + postId: string; + content: string; +} +interface CellCreationParams extends BaseActionParams { + name: string; + description: string; + icon?: string; +} +interface VoteParams extends BaseActionParams { + targetId: string; + isUpvote: boolean; +} +interface PostModerationParams extends BaseActionParams { + cellId: string; + postId: string; + reason?: string; + cellOwner: string; +} +interface CommentModerationParams extends BaseActionParams { + cellId: string; + commentId: string; + reason?: string; + cellOwner: string; +} +interface UserModerationParams extends BaseActionParams { + cellId: string; + userAddress: string; + reason?: string; + cellOwner: string; +} +export {}; +//# sourceMappingURL=ForumActions.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/forum/ForumActions.d.ts.map b/packages/core/dist/forum/ForumActions.d.ts.map new file mode 100644 index 0000000..a695338 --- /dev/null +++ b/packages/core/dist/forum/ForumActions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ForumActions.d.ts","sourceRoot":"","sources":["../../src/forum/ForumActions.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAuB,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAIlD,KAAK,YAAY,CAAC,CAAC,IAAI;IACrB,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,CAAC,EAAE,CAAC,CAAC;IACT,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,qBAAa,YAAY;IACvB,OAAO,CAAC,iBAAiB,CAAoB;gBAEjC,iBAAiB,CAAC,EAAE,iBAAiB;IAIjD;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAqCpB,UAAU,CACd,MAAM,EAAE,kBAAkB,EAC1B,oBAAoB,EAAE,MAAM,IAAI,GAC/B,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAiExB,aAAa,CACjB,MAAM,EAAE,qBAAqB,EAC7B,oBAAoB,EAAE,MAAM,IAAI,GAC/B,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAqE3B,UAAU,CACd,MAAM,EAAE,kBAAkB,EAC1B,oBAAoB,EAAE,MAAM,IAAI,GAC/B,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAsExB,IAAI,CACR,MAAM,EAAE,UAAU,EAClB,oBAAoB,EAAE,MAAM,IAAI,GAC/B,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAiE3B,YAAY,CAChB,MAAM,EAAE,oBAAoB,EAC5B,oBAAoB,EAAE,MAAM,IAAI,GAC/B,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAgE3B,eAAe,CACnB,MAAM,EAAE,uBAAuB,EAC/B,oBAAoB,EAAE,MAAM,IAAI,GAC/B,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAsE3B,YAAY,CAChB,MAAM,EAAE,oBAAoB,EAC5B,oBAAoB,EAAE,MAAM,IAAI,GAC/B,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;CAqElC;AAGD,UAAU,gBAAgB;IACxB,WAAW,EAAE,IAAI,GAAG,IAAI,CAAC;IACzB,eAAe,EAAE,OAAO,CAAC;CAC1B;AAGD,UAAU,kBAAmB,SAAQ,gBAAgB;IACnD,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,UAAU,qBAAsB,SAAQ,gBAAgB;IACtD,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,UAAU,kBAAmB,SAAQ,gBAAgB;IACnD,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,UAAU,UAAW,SAAQ,gBAAgB;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,UAAU,oBAAqB,SAAQ,gBAAgB;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,UAAU,uBAAwB,SAAQ,gBAAgB;IACxD,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,UAAU,oBAAqB,SAAQ,gBAAgB;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB"} \ No newline at end of file diff --git a/packages/core/dist/forum/ForumActions.js b/packages/core/dist/forum/ForumActions.js new file mode 100644 index 0000000..0333fcd --- /dev/null +++ b/packages/core/dist/forum/ForumActions.js @@ -0,0 +1,416 @@ +import { v4 as uuidv4 } from 'uuid'; +import { MessageType, } from '../types/waku'; +import { EVerificationStatus } from '../types/identity'; +import { transformCell, transformComment, transformPost } from './transformers'; +import { DelegationManager } from '../delegation'; +import { localDatabase } from '../database/LocalDatabase'; +import messageManager from '../waku'; +export class ForumActions { + constructor(delegationManager) { + this.delegationManager = delegationManager || new DelegationManager(); + } + /** + * Unified permission validation system + */ + validatePermission(action, currentUser, _isAuthenticated) { + const verificationStatus = currentUser?.verificationStatus || EVerificationStatus.WALLET_UNCONNECTED; + switch (action) { + case 'createCell': + if (verificationStatus !== EVerificationStatus.ENS_ORDINAL_VERIFIED) { + return { + valid: false, + error: 'Only ENS or Logos ordinal owners can create cells', + }; + } + break; + case 'createPost': + case 'createComment': + case 'vote': + if (verificationStatus === EVerificationStatus.WALLET_UNCONNECTED) { + return { + valid: false, + error: 'Connect your wallet to perform this action', + }; + } + break; + } + return { valid: true }; + } + /* ------------------------------------------------------------------ + POST / COMMENT / CELL CREATION + -------------------------------------------------------------------*/ + async createPost(params, updateStateFromCache) { + const { cellId, title, content, currentUser, isAuthenticated } = params; + const validation = this.validatePermission('createPost', currentUser, isAuthenticated); + if (!validation.valid) { + return { + success: false, + error: validation.error, + }; + } + try { + const postId = uuidv4(); + const unsignedPost = { + type: MessageType.POST, + id: postId, + cellId, + title, + content, + timestamp: Date.now(), + author: currentUser.address, // Safe after validation + }; + const signed = await this.delegationManager.signMessage(unsignedPost); + if (!signed) { + const status = await this.delegationManager.getStatus(currentUser.address, currentUser.walletType); + return { + success: false, + error: status.isValid + ? 'Key delegation required. Please delegate a signing key from your profile menu.' + : 'Key delegation expired. Please re-delegate your key through the profile menu.', + }; + } + await localDatabase.updateCache(signed); + localDatabase.markPending(signed.id); + localDatabase.setSyncing(true); + updateStateFromCache(); + messageManager + .sendMessage(signed) + .catch((err) => console.error('Background send failed:', err)) + .finally(() => localDatabase.setSyncing(false)); + const transformedPost = await transformPost(signed); + if (!transformedPost) { + return { success: false, error: 'Failed to transform post data.' }; + } + return { success: true, data: transformedPost }; + } + catch (error) { + console.error('Error creating post:', error); + return { + success: false, + error: 'Failed to create post. Please try again.', + }; + } + } + async createComment(params, updateStateFromCache) { + const { postId, content, currentUser, isAuthenticated } = params; + // Use unified validation + const validation = this.validatePermission('createComment', currentUser, isAuthenticated); + if (!validation.valid) { + return { + success: false, + error: validation.error, + }; + } + try { + const commentId = uuidv4(); + const unsignedComment = { + type: MessageType.COMMENT, + id: commentId, + postId, + content, + timestamp: Date.now(), + author: currentUser.address, + }; + // Optimistic path: sign locally, write to cache, mark pending, render immediately + const signed = await this.delegationManager.signMessage(unsignedComment); + if (!signed) { + const status = await this.delegationManager.getStatus(currentUser.address, currentUser.walletType); + return { + success: false, + error: status.isValid + ? 'Key delegation required. Please delegate a signing key from your profile menu.' + : 'Key delegation expired. Please re-delegate your key through the profile menu.', + }; + } + // Write immediately to LocalDatabase and reflect in UI + await localDatabase.updateCache(signed); + localDatabase.markPending(signed.id); + localDatabase.setSyncing(true); + updateStateFromCache(); + // Fire-and-forget network send; LocalDatabase will clear pending on ack + messageManager + .sendMessage(signed) + .catch((err) => console.error('Background send failed:', err)) + .finally(() => localDatabase.setSyncing(false)); + const transformed = await transformComment(signed); + if (!transformed) { + return { success: false, error: 'Failed to transform comment data.' }; + } + return { success: true, data: transformed }; + } + catch (error) { + console.error('Error creating comment:', error); + return { + success: false, + error: 'Failed to add comment. Please try again.', + }; + } + } + async createCell(params, updateStateFromCache) { + const { name, description, icon, currentUser, isAuthenticated } = params; + // Use unified validation + const validation = this.validatePermission('createCell', currentUser, isAuthenticated); + if (!validation.valid) { + return { + success: false, + error: validation.error, + }; + } + try { + const cellId = uuidv4(); + const unsignedCell = { + type: MessageType.CELL, + id: cellId, + name, + description, + ...(icon && { icon }), + timestamp: Date.now(), + author: currentUser.address, + }; + const signed = await this.delegationManager.signMessage(unsignedCell); + if (!signed) { + const status = await this.delegationManager.getStatus(currentUser.address, currentUser.walletType); + return { + success: false, + error: status.isValid + ? 'Key delegation required. Please delegate a signing key from your profile menu.' + : 'Key delegation expired. Please re-delegate your key through the profile menu.', + }; + } + await localDatabase.updateCache(signed); + localDatabase.markPending(signed.id); + localDatabase.setSyncing(true); + updateStateFromCache(); + messageManager + .sendMessage(signed) + .catch((err) => console.error('Background send failed:', err)) + .finally(() => localDatabase.setSyncing(false)); + const transformedCell = await transformCell(signed); + if (!transformedCell) { + return { success: false, error: 'Failed to transform cell data.' }; + } + return { success: true, data: transformedCell }; + } + catch (error) { + console.error('Error creating cell:', error); + return { + success: false, + error: 'Failed to create cell. Please try again.', + }; + } + } + /* ------------------------------------------------------------------ + VOTING + -------------------------------------------------------------------*/ + async vote(params, updateStateFromCache) { + const { targetId, isUpvote, currentUser, isAuthenticated } = params; + // Use unified validation + const validation = this.validatePermission('vote', currentUser, isAuthenticated); + if (!validation.valid) { + return { + success: false, + error: validation.error, + }; + } + try { + const voteId = uuidv4(); + const unsignedVote = { + type: MessageType.VOTE, + id: voteId, + targetId, + value: isUpvote ? 1 : -1, + timestamp: Date.now(), + author: currentUser.address, + }; + const signed = await this.delegationManager.signMessage(unsignedVote); + if (!signed) { + const status = await this.delegationManager.getStatus(currentUser.address, currentUser.walletType); + return { + success: false, + error: status.isValid + ? 'Key delegation required. Please delegate a signing key from your profile menu.' + : 'Key delegation expired. Please re-delegate your key through the profile menu.', + }; + } + await localDatabase.updateCache(signed); + localDatabase.markPending(signed.id); + localDatabase.setSyncing(true); + updateStateFromCache(); + messageManager + .sendMessage(signed) + .catch((err) => console.error('Background send failed:', err)) + .finally(() => localDatabase.setSyncing(false)); + return { success: true, data: true }; + } + catch (error) { + console.error('Error voting:', error); + return { + success: false, + error: 'Failed to register your vote. Please try again.', + }; + } + } + /* ------------------------------------------------------------------ + MODERATION + -------------------------------------------------------------------*/ + async moderatePost(params, updateStateFromCache) { + const { cellId, postId, reason, currentUser, isAuthenticated, cellOwner } = params; + if (!isAuthenticated || !currentUser) { + return { + success: false, + error: 'Authentication required. You need to verify Ordinal ownership to moderate posts.', + }; + } + if (currentUser.address !== cellOwner) { + return { + success: false, + error: 'Not authorized. Only the cell admin can moderate posts.', + }; + } + try { + const unsignedMod = { + type: MessageType.MODERATE, + id: uuidv4(), + cellId, + targetType: 'post', + targetId: postId, + reason, + timestamp: Date.now(), + author: currentUser.address, + }; + const signed = await this.delegationManager.signMessage(unsignedMod); + if (!signed) { + const status = await this.delegationManager.getStatus(currentUser.address, currentUser.walletType); + return { + success: false, + error: status.isValid + ? 'Key delegation required. Please delegate a signing key from your profile menu.' + : 'Key delegation expired. Please re-delegate your key through the profile menu.', + }; + } + await localDatabase.updateCache(signed); + localDatabase.markPending(signed.id); + localDatabase.setSyncing(true); + updateStateFromCache(); + messageManager + .sendMessage(signed) + .catch((err) => console.error('Background send failed:', err)) + .finally(() => localDatabase.setSyncing(false)); + return { success: true, data: true }; + } + catch (error) { + console.error('Error moderating post:', error); + return { + success: false, + error: 'Failed to moderate post. Please try again.', + }; + } + } + async moderateComment(params, updateStateFromCache) { + const { cellId, commentId, reason, currentUser, isAuthenticated, cellOwner, } = params; + if (!isAuthenticated || !currentUser) { + return { + success: false, + error: 'Authentication required. You need to verify Ordinal ownership to moderate comments.', + }; + } + if (currentUser.address !== cellOwner) { + return { + success: false, + error: 'Not authorized. Only the cell admin can moderate comments.', + }; + } + try { + const unsignedMod = { + type: MessageType.MODERATE, + id: uuidv4(), + cellId, + targetType: 'comment', + targetId: commentId, + reason, + timestamp: Date.now(), + author: currentUser.address, + }; + const signed = await this.delegationManager.signMessage(unsignedMod); + if (!signed) { + const status = await this.delegationManager.getStatus(currentUser.address, currentUser.walletType); + return { + success: false, + error: status.isValid + ? 'Key delegation required. Please delegate a signing key from your profile menu.' + : 'Key delegation expired. Please re-delegate your key through the profile menu.', + }; + } + await localDatabase.updateCache(signed); + localDatabase.markPending(signed.id); + localDatabase.setSyncing(true); + updateStateFromCache(); + messageManager + .sendMessage(signed) + .catch((err) => console.error('Background send failed:', err)) + .finally(() => localDatabase.setSyncing(false)); + return { success: true, data: true }; + } + catch (error) { + console.error('Error moderating comment:', error); + return { + success: false, + error: 'Failed to moderate comment. Please try again.', + }; + } + } + async moderateUser(params, updateStateFromCache) { + const { cellId, userAddress, reason, currentUser, isAuthenticated, cellOwner, } = params; + if (!isAuthenticated || !currentUser) { + return { + success: false, + error: 'Authentication required. You need to verify Ordinal ownership to moderate users.', + }; + } + if (currentUser.address !== cellOwner) { + return { + success: false, + error: 'Not authorized. Only the cell admin can moderate users.', + }; + } + try { + const unsignedMod = { + type: MessageType.MODERATE, + id: uuidv4(), + cellId, + targetType: 'user', + targetId: userAddress, + reason, + author: currentUser.address, + timestamp: Date.now(), + }; + const signed = await this.delegationManager.signMessage(unsignedMod); + if (!signed) { + const status = await this.delegationManager.getStatus(currentUser.address, currentUser.walletType); + return { + success: false, + error: status.isValid + ? 'Key delegation required. Please delegate a signing key from your profile menu.' + : 'Key delegation expired. Please re-delegate your key through the profile menu.', + }; + } + await localDatabase.updateCache(signed); + localDatabase.markPending(signed.id); + localDatabase.setSyncing(true); + updateStateFromCache(); + messageManager + .sendMessage(signed) + .catch((err) => console.error('Background send failed:', err)) + .finally(() => localDatabase.setSyncing(false)); + return { success: true, data: true }; + } + catch (error) { + console.error('Error moderating user:', error); + return { + success: false, + error: 'Failed to moderate user. Please try again.', + }; + } + } +} +//# sourceMappingURL=ForumActions.js.map \ No newline at end of file diff --git a/packages/core/dist/forum/ForumActions.js.map b/packages/core/dist/forum/ForumActions.js.map new file mode 100644 index 0000000..9e3cf8f --- /dev/null +++ b/packages/core/dist/forum/ForumActions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ForumActions.js","sourceRoot":"","sources":["../../src/forum/ForumActions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EACL,WAAW,GASZ,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,mBAAmB,EAAQ,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAChF,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,cAAc,MAAM,SAAS,CAAC;AAQrC,MAAM,OAAO,YAAY;IAGvB,YAAY,iBAAqC;QAC/C,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,IAAI,IAAI,iBAAiB,EAAE,CAAC;IACxE,CAAC;IAED;;OAEG;IACK,kBAAkB,CACxB,MAA8D,EAC9D,WAAwB,EACxB,gBAAyB;QAEzB,MAAM,kBAAkB,GACtB,WAAW,EAAE,kBAAkB,IAAI,mBAAmB,CAAC,kBAAkB,CAAC;QAE5E,QAAQ,MAAM,EAAE,CAAC;YACf,KAAK,YAAY;gBACf,IAAI,kBAAkB,KAAK,mBAAmB,CAAC,oBAAoB,EAAE,CAAC;oBACpE,OAAO;wBACL,KAAK,EAAE,KAAK;wBACZ,KAAK,EAAE,mDAAmD;qBAC3D,CAAC;gBACJ,CAAC;gBACD,MAAM;YAER,KAAK,YAAY,CAAC;YAClB,KAAK,eAAe,CAAC;YACrB,KAAK,MAAM;gBACT,IAAI,kBAAkB,KAAK,mBAAmB,CAAC,kBAAkB,EAAE,CAAC;oBAClE,OAAO;wBACL,KAAK,EAAE,KAAK;wBACZ,KAAK,EAAE,4CAA4C;qBACpD,CAAC;gBACJ,CAAC;gBACD,MAAM;QACV,CAAC;QAED,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACzB,CAAC;IAED;;yEAEqE;IAErE,KAAK,CAAC,UAAU,CACd,MAA0B,EAC1B,oBAAgC;QAEhC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,GAAG,MAAM,CAAC;QAExE,MAAM,UAAU,GAAG,IAAI,CAAC,kBAAkB,CACxC,YAAY,EACZ,WAAW,EACX,eAAe,CAChB,CAAC;QACF,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;YACtB,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,UAAU,CAAC,KAAM;aACzB,CAAC;QACJ,CAAC;QAED,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC;YACxB,MAAM,YAAY,GAAwB;gBACxC,IAAI,EAAE,WAAW,CAAC,IAAI;gBACtB,EAAE,EAAE,MAAM;gBACV,MAAM;gBACN,KAAK;gBACL,OAAO;gBACP,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;gBACrB,MAAM,EAAE,WAAY,CAAC,OAAO,EAAE,wBAAwB;aACvD,CAAC;YAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,YAAY,CAAC,CAAC;YACtE,IAAI,CAAC,MAAM,EAAE,CAAC;gBACZ,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,SAAS,CACnD,WAAY,CAAC,OAAO,EACpB,WAAY,CAAC,UAAU,CACxB,CAAC;gBACF,OAAO;oBACL,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,MAAM,CAAC,OAAO;wBACnB,CAAC,CAAC,gFAAgF;wBAClF,CAAC,CAAC,+EAA+E;iBACpF,CAAC;YACJ,CAAC;YAED,MAAM,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YACxC,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACrC,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAC/B,oBAAoB,EAAE,CAAC;YAEvB,cAAc;iBACX,WAAW,CAAC,MAAM,CAAC;iBACnB,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;iBAC7D,OAAO,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;YAElD,MAAM,eAAe,GAAG,MAAM,aAAa,CAAC,MAAqB,CAAC,CAAC;YACnE,IAAI,CAAC,eAAe,EAAE,CAAC;gBACrB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,gCAAgC,EAAE,CAAC;YACrE,CAAC;YACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,eAAe,EAAE,CAAC;QAClD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;YAC7C,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,0CAA0C;aAClD,CAAC;QACJ,CAAC;IACH,CAAC;IAED,KAAK,CAAC,aAAa,CACjB,MAA6B,EAC7B,oBAAgC;QAEhC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,GAAG,MAAM,CAAC;QAEjE,yBAAyB;QACzB,MAAM,UAAU,GAAG,IAAI,CAAC,kBAAkB,CACxC,eAAe,EACf,WAAW,EACX,eAAe,CAChB,CAAC;QACF,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;YACtB,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,UAAU,CAAC,KAAM;aACzB,CAAC;QACJ,CAAC;QAED,IAAI,CAAC;YACH,MAAM,SAAS,GAAG,MAAM,EAAE,CAAC;YAC3B,MAAM,eAAe,GAA2B;gBAC9C,IAAI,EAAE,WAAW,CAAC,OAAO;gBACzB,EAAE,EAAE,SAAS;gBACb,MAAM;gBACN,OAAO;gBACP,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;gBACrB,MAAM,EAAE,WAAY,CAAC,OAAO;aAC7B,CAAC;YAEF,kFAAkF;YAClF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,eAAe,CAAC,CAAC;YACzE,IAAI,CAAC,MAAM,EAAE,CAAC;gBACZ,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,SAAS,CACnD,WAAY,CAAC,OAAO,EACpB,WAAY,CAAC,UAAU,CACxB,CAAC;gBACF,OAAO;oBACL,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,MAAM,CAAC,OAAO;wBACnB,CAAC,CAAC,gFAAgF;wBAClF,CAAC,CAAC,+EAA+E;iBACpF,CAAC;YACJ,CAAC;YAED,uDAAuD;YACvD,MAAM,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YACxC,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACrC,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAC/B,oBAAoB,EAAE,CAAC;YAEvB,wEAAwE;YACxE,cAAc;iBACX,WAAW,CAAC,MAAM,CAAC;iBACnB,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;iBAC7D,OAAO,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;YAElD,MAAM,WAAW,GAAG,MAAM,gBAAgB,CAAC,MAAwB,CAAC,CAAC;YACrE,IAAI,CAAC,WAAW,EAAE,CAAC;gBACjB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,mCAAmC,EAAE,CAAC;YACxE,CAAC;YAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;QAC9C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;YAChD,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,0CAA0C;aAClD,CAAC;QACJ,CAAC;IACH,CAAC;IAED,KAAK,CAAC,UAAU,CACd,MAA0B,EAC1B,oBAAgC;QAEhC,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,eAAe,EAAE,GAAG,MAAM,CAAC;QAEzE,yBAAyB;QACzB,MAAM,UAAU,GAAG,IAAI,CAAC,kBAAkB,CACxC,YAAY,EACZ,WAAW,EACX,eAAe,CAChB,CAAC;QACF,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;YACtB,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,UAAU,CAAC,KAAM;aACzB,CAAC;QACJ,CAAC;QAED,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC;YACxB,MAAM,YAAY,GAAwB;gBACxC,IAAI,EAAE,WAAW,CAAC,IAAI;gBACtB,EAAE,EAAE,MAAM;gBACV,IAAI;gBACJ,WAAW;gBACX,GAAG,CAAC,IAAI,IAAI,EAAE,IAAI,EAAE,CAAC;gBACrB,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;gBACrB,MAAM,EAAE,WAAY,CAAC,OAAO;aAC7B,CAAC;YAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,YAAY,CAAC,CAAC;YACtE,IAAI,CAAC,MAAM,EAAE,CAAC;gBACZ,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,SAAS,CACnD,WAAY,CAAC,OAAO,EACpB,WAAY,CAAC,UAAU,CACxB,CAAC;gBACF,OAAO;oBACL,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,MAAM,CAAC,OAAO;wBACnB,CAAC,CAAC,gFAAgF;wBAClF,CAAC,CAAC,+EAA+E;iBACpF,CAAC;YACJ,CAAC;YAED,MAAM,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YACxC,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACrC,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAC/B,oBAAoB,EAAE,CAAC;YAEvB,cAAc;iBACX,WAAW,CAAC,MAAM,CAAC;iBACnB,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;iBAC7D,OAAO,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;YAElD,MAAM,eAAe,GAAG,MAAM,aAAa,CAAC,MAAqB,CAAC,CAAC;YACnE,IAAI,CAAC,eAAe,EAAE,CAAC;gBACrB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,gCAAgC,EAAE,CAAC;YACrE,CAAC;YACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,eAAe,EAAE,CAAC;QAClD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;YAC7C,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,0CAA0C;aAClD,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;yEAEqE;IAErE,KAAK,CAAC,IAAI,CACR,MAAkB,EAClB,oBAAgC;QAEhC,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,eAAe,EAAE,GAAG,MAAM,CAAC;QAEpE,yBAAyB;QACzB,MAAM,UAAU,GAAG,IAAI,CAAC,kBAAkB,CACxC,MAAM,EACN,WAAW,EACX,eAAe,CAChB,CAAC;QACF,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;YACtB,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,UAAU,CAAC,KAAM;aACzB,CAAC;QACJ,CAAC;QAED,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC;YACxB,MAAM,YAAY,GAAwB;gBACxC,IAAI,EAAE,WAAW,CAAC,IAAI;gBACtB,EAAE,EAAE,MAAM;gBACV,QAAQ;gBACR,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;gBACxB,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;gBACrB,MAAM,EAAE,WAAY,CAAC,OAAO;aAC7B,CAAC;YAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,YAAY,CAAC,CAAC;YACtE,IAAI,CAAC,MAAM,EAAE,CAAC;gBACZ,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,SAAS,CACnD,WAAY,CAAC,OAAO,EACpB,WAAY,CAAC,UAAU,CACxB,CAAC;gBACF,OAAO;oBACL,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,MAAM,CAAC,OAAO;wBACnB,CAAC,CAAC,gFAAgF;wBAClF,CAAC,CAAC,+EAA+E;iBACpF,CAAC;YACJ,CAAC;YAED,MAAM,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YACxC,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACrC,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAC/B,oBAAoB,EAAE,CAAC;YAEvB,cAAc;iBACX,WAAW,CAAC,MAAM,CAAC;iBACnB,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;iBAC7D,OAAO,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;YAElD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACvC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;YACtC,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,iDAAiD;aACzD,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;yEAEqE;IAErE,KAAK,CAAC,YAAY,CAChB,MAA4B,EAC5B,oBAAgC;QAEhC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,eAAe,EAAE,SAAS,EAAE,GACvE,MAAM,CAAC;QAET,IAAI,CAAC,eAAe,IAAI,CAAC,WAAW,EAAE,CAAC;YACrC,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EACH,kFAAkF;aACrF,CAAC;QACJ,CAAC;QACD,IAAI,WAAW,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;YACtC,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,yDAAyD;aACjE,CAAC;QACJ,CAAC;QAED,IAAI,CAAC;YACH,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,WAAW,CAAC,QAAQ;gBAC1B,EAAE,EAAE,MAAM,EAAE;gBACZ,MAAM;gBACN,UAAU,EAAE,MAAM;gBAClB,QAAQ,EAAE,MAAM;gBAChB,MAAM;gBACN,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;gBACrB,MAAM,EAAE,WAAY,CAAC,OAAO;aAC7B,CAAC;YAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;YACrE,IAAI,CAAC,MAAM,EAAE,CAAC;gBACZ,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,SAAS,CACnD,WAAY,CAAC,OAAO,EACpB,WAAY,CAAC,UAAU,CACxB,CAAC;gBACF,OAAO;oBACL,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,MAAM,CAAC,OAAO;wBACnB,CAAC,CAAC,gFAAgF;wBAClF,CAAC,CAAC,+EAA+E;iBACpF,CAAC;YACJ,CAAC;YAED,MAAM,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YACxC,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACrC,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAC/B,oBAAoB,EAAE,CAAC;YAEvB,cAAc;iBACX,WAAW,CAAC,MAAM,CAAC;iBACnB,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;iBAC7D,OAAO,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;YAElD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACvC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,KAAK,CAAC,CAAC;YAC/C,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,4CAA4C;aACpD,CAAC;QACJ,CAAC;IACH,CAAC;IAED,KAAK,CAAC,eAAe,CACnB,MAA+B,EAC/B,oBAAgC;QAEhC,MAAM,EACJ,MAAM,EACN,SAAS,EACT,MAAM,EACN,WAAW,EACX,eAAe,EACf,SAAS,GACV,GAAG,MAAM,CAAC;QAEX,IAAI,CAAC,eAAe,IAAI,CAAC,WAAW,EAAE,CAAC;YACrC,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EACH,qFAAqF;aACxF,CAAC;QACJ,CAAC;QACD,IAAI,WAAW,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;YACtC,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,4DAA4D;aACpE,CAAC;QACJ,CAAC;QAED,IAAI,CAAC;YACH,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,WAAW,CAAC,QAAQ;gBAC1B,EAAE,EAAE,MAAM,EAAE;gBACZ,MAAM;gBACN,UAAU,EAAE,SAAS;gBACrB,QAAQ,EAAE,SAAS;gBACnB,MAAM;gBACN,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;gBACrB,MAAM,EAAE,WAAY,CAAC,OAAO;aAC7B,CAAC;YAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;YACrE,IAAI,CAAC,MAAM,EAAE,CAAC;gBACZ,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,SAAS,CACnD,WAAY,CAAC,OAAO,EACpB,WAAY,CAAC,UAAU,CACxB,CAAC;gBACF,OAAO;oBACL,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,MAAM,CAAC,OAAO;wBACnB,CAAC,CAAC,gFAAgF;wBAClF,CAAC,CAAC,+EAA+E;iBACpF,CAAC;YACJ,CAAC;YAED,MAAM,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YACxC,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACrC,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAC/B,oBAAoB,EAAE,CAAC;YAEvB,cAAc;iBACX,WAAW,CAAC,MAAM,CAAC;iBACnB,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;iBAC7D,OAAO,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;YAElD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACvC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;YAClD,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,+CAA+C;aACvD,CAAC;QACJ,CAAC;IACH,CAAC;IAED,KAAK,CAAC,YAAY,CAChB,MAA4B,EAC5B,oBAAgC;QAEhC,MAAM,EACJ,MAAM,EACN,WAAW,EACX,MAAM,EACN,WAAW,EACX,eAAe,EACf,SAAS,GACV,GAAG,MAAM,CAAC;QAEX,IAAI,CAAC,eAAe,IAAI,CAAC,WAAW,EAAE,CAAC;YACrC,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EACH,kFAAkF;aACrF,CAAC;QACJ,CAAC;QACD,IAAI,WAAW,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;YACtC,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,yDAAyD;aACjE,CAAC;QACJ,CAAC;QAED,IAAI,CAAC;YACH,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,WAAW,CAAC,QAAQ;gBAC1B,EAAE,EAAE,MAAM,EAAE;gBACZ,MAAM;gBACN,UAAU,EAAE,MAAM;gBAClB,QAAQ,EAAE,WAAW;gBACrB,MAAM;gBACN,MAAM,EAAE,WAAY,CAAC,OAAO;gBAC5B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;aACtB,CAAC;YAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;YACrE,IAAI,CAAC,MAAM,EAAE,CAAC;gBACZ,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,SAAS,CACnD,WAAY,CAAC,OAAO,EACpB,WAAY,CAAC,UAAU,CACxB,CAAC;gBACF,OAAO;oBACL,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,MAAM,CAAC,OAAO;wBACnB,CAAC,CAAC,gFAAgF;wBAClF,CAAC,CAAC,+EAA+E;iBACpF,CAAC;YACJ,CAAC;YAED,MAAM,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YACxC,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACrC,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAC/B,oBAAoB,EAAE,CAAC;YAEvB,cAAc;iBACX,WAAW,CAAC,MAAM,CAAC;iBACnB,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;iBAC7D,OAAO,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;YAElD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACvC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,KAAK,CAAC,CAAC;YAC/C,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,4CAA4C;aACpD,CAAC;QACJ,CAAC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/forum/RelevanceCalculator.d.ts b/packages/core/dist/forum/RelevanceCalculator.d.ts new file mode 100644 index 0000000..c5e1dd6 --- /dev/null +++ b/packages/core/dist/forum/RelevanceCalculator.d.ts @@ -0,0 +1,71 @@ +import { Post, Comment, Cell, RelevanceScoreDetails, UserVerificationStatus } from '../types/forum'; +import { User } from '../types/identity'; +import { VoteMessage } from '../types/waku'; +export declare class RelevanceCalculator { + private static readonly BASE_SCORES; + private static readonly ENGAGEMENT_SCORES; + private static readonly VERIFICATION_BONUS; + private static readonly BASIC_VERIFICATION_BONUS; + private static readonly VERIFIED_UPVOTE_BONUS; + private static readonly VERIFIED_COMMENTER_BONUS; + private static readonly DECAY_RATE; + private static readonly MODERATION_PENALTY; + /** + * Calculate relevance score for a post + */ + calculatePostScore(post: Post, votes: VoteMessage[], comments: Comment[], userVerificationStatus: UserVerificationStatus): { + score: number; + details: RelevanceScoreDetails; + }; + /** + * Calculate relevance score for a comment + */ + calculateCommentScore(comment: Comment, votes: VoteMessage[], userVerificationStatus: UserVerificationStatus): { + score: number; + details: RelevanceScoreDetails; + }; + /** + * Calculate relevance score for a cell + */ + calculateCellScore(cell: Cell, posts: Post[]): { + score: number; + details: RelevanceScoreDetails; + }; + /** + * Check if a user is verified (has ENS or ordinal ownership, or basic verification) + */ + isUserVerified(user: User): boolean; + /** + * Build user verification status map from users array + */ + buildUserVerificationStatus(users: User[]): UserVerificationStatus; + /** + * Apply base score to the current score + */ + private applyBaseScore; + /** + * Apply engagement score based on upvotes and comments + */ + private applyEngagementScore; + /** + * Apply verification bonus for verified authors + */ + private applyAuthorVerificationBonus; + /** + * Apply verified upvote bonus + */ + private applyVerifiedUpvoteBonus; + /** + * Apply verified commenter bonus + */ + private applyVerifiedCommenterBonus; + /** + * Apply time decay to a score + */ + private applyTimeDecay; + /** + * Apply moderation penalty + */ + private applyModerationPenalty; +} +//# sourceMappingURL=RelevanceCalculator.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/forum/RelevanceCalculator.d.ts.map b/packages/core/dist/forum/RelevanceCalculator.d.ts.map new file mode 100644 index 0000000..ee51bd2 --- /dev/null +++ b/packages/core/dist/forum/RelevanceCalculator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RelevanceCalculator.d.ts","sourceRoot":"","sources":["../../src/forum/RelevanceCalculator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EACJ,OAAO,EACP,IAAI,EACJ,qBAAqB,EACrB,sBAAsB,EACvB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAuB,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAIjC;IAEF,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAGvC;IAEF,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,kBAAkB,CAAQ;IAClD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,wBAAwB,CAAO;IACvD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,qBAAqB,CAAO;IACpD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,wBAAwB,CAAQ;IAExD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAO;IACzC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,kBAAkB,CAAO;IAEjD;;OAEG;IACH,kBAAkB,CAChB,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,WAAW,EAAE,EACpB,QAAQ,EAAE,OAAO,EAAE,EACnB,sBAAsB,EAAE,sBAAsB,GAC7C;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,qBAAqB,CAAA;KAAE;IA2DpD;;OAEG;IACH,qBAAqB,CACnB,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,WAAW,EAAE,EACpB,sBAAsB,EAAE,sBAAsB,GAC7C;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,qBAAqB,CAAA;KAAE;IAwDpD;;OAEG;IACH,kBAAkB,CAChB,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,IAAI,EAAE,GACZ;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,qBAAqB,CAAA;KAAE;IAsDpD;;OAEG;IACH,cAAc,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO;IAQnC;;OAEG;IACH,2BAA2B,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,sBAAsB;IAgBlE;;OAEG;IACH,OAAO,CAAC,cAAc;IAItB;;OAEG;IACH,OAAO,CAAC,oBAAoB;IAW5B;;OAEG;IACH,OAAO,CAAC,4BAA4B;IA8BpC;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAchC;;OAEG;IACH,OAAO,CAAC,2BAA2B;IAkBnC;;OAEG;IACH,OAAO,CAAC,cAAc;IAetB;;OAEG;IACH,OAAO,CAAC,sBAAsB;CAc/B"} \ No newline at end of file diff --git a/packages/core/dist/forum/RelevanceCalculator.js b/packages/core/dist/forum/RelevanceCalculator.js new file mode 100644 index 0000000..2ebc6bf --- /dev/null +++ b/packages/core/dist/forum/RelevanceCalculator.js @@ -0,0 +1,250 @@ +import { EVerificationStatus } from '../types/identity'; +export class RelevanceCalculator { + /** + * Calculate relevance score for a post + */ + calculatePostScore(post, votes, comments, userVerificationStatus) { + let score = this.applyBaseScore('POST'); + const baseScore = score; + const upvotes = votes.filter((vote) => vote.value === 1); + const engagementScore = this.applyEngagementScore(upvotes, comments); + score += engagementScore; + const { bonus: authorVerificationBonus, isVerified } = this.applyAuthorVerificationBonus(score, post.authorAddress, userVerificationStatus); + score += authorVerificationBonus; + const { bonus: verifiedUpvoteBonus, verifiedUpvotes } = this.applyVerifiedUpvoteBonus(upvotes, userVerificationStatus); + score += verifiedUpvoteBonus; + const { bonus: verifiedCommenterBonus, verifiedCommenters } = this.applyVerifiedCommenterBonus(comments, userVerificationStatus); + score += verifiedCommenterBonus; + const { decayedScore, multiplier: timeDecayMultiplier, daysOld, } = this.applyTimeDecay(score, post.timestamp); + score = decayedScore; + const { penalizedScore, penalty: moderationPenalty } = this.applyModerationPenalty(score, post.moderated || false); + score = penalizedScore; + const finalScore = Math.max(0, score); // Ensure non-negative score + return { + score: finalScore, + details: { + baseScore, + engagementScore, + authorVerificationBonus, + verifiedUpvoteBonus, + verifiedCommenterBonus, + timeDecayMultiplier, + moderationPenalty, + finalScore, + isVerified, + upvotes: upvotes.length, + comments: comments.length, + verifiedUpvotes, + verifiedCommenters, + daysOld, + isModerated: post.moderated || false, + }, + }; + } + /** + * Calculate relevance score for a comment + */ + calculateCommentScore(comment, votes, userVerificationStatus) { + // Apply base score + let score = this.applyBaseScore('COMMENT'); + const baseScore = score; + const upvotes = votes.filter((vote) => vote.value === 1); + const engagementScore = this.applyEngagementScore(upvotes, []); + score += engagementScore; + const { bonus: authorVerificationBonus, isVerified } = this.applyAuthorVerificationBonus(score, comment.authorAddress, userVerificationStatus); + score += authorVerificationBonus; + const { bonus: verifiedUpvoteBonus, verifiedUpvotes } = this.applyVerifiedUpvoteBonus(upvotes, userVerificationStatus); + score += verifiedUpvoteBonus; + const { decayedScore, multiplier: timeDecayMultiplier, daysOld, } = this.applyTimeDecay(score, comment.timestamp); + score = decayedScore; + const { penalizedScore, penalty: moderationPenalty } = this.applyModerationPenalty(score, comment.moderated || false); + score = penalizedScore; + const finalScore = Math.max(0, score); // Ensure non-negative score + return { + score: finalScore, + details: { + baseScore, + engagementScore, + authorVerificationBonus, + verifiedUpvoteBonus, + verifiedCommenterBonus: 0, // Comments don't have commenters + timeDecayMultiplier, + moderationPenalty, + finalScore, + isVerified, + upvotes: upvotes.length, + comments: 0, // Comments don't have comments + verifiedUpvotes, + verifiedCommenters: 0, + daysOld, + isModerated: comment.moderated || false, + }, + }; + } + /** + * Calculate relevance score for a cell + */ + calculateCellScore(cell, posts) { + // Apply base score + let score = this.applyBaseScore('CELL'); + const baseScore = score; + // Calculate cell-specific engagement + const cellPosts = posts.filter((post) => post.cellId === cell.id); + const totalUpvotes = cellPosts.reduce((sum, post) => { + return sum + (post.upvotes?.length || 0); + }, 0); + const activityScore = cellPosts.length * RelevanceCalculator.ENGAGEMENT_SCORES.COMMENT; + const engagementBonus = totalUpvotes * 0.1; // Small bonus for cell activity + const engagementScore = activityScore + engagementBonus; + score += engagementScore; + const mostRecentPost = cellPosts.reduce((latest, post) => { + return post.timestamp > latest.timestamp ? post : latest; + }, { timestamp: Date.now() }); + const { decayedScore, multiplier: timeDecayMultiplier, daysOld, } = this.applyTimeDecay(score, mostRecentPost.timestamp); + score = decayedScore; + const finalScore = Math.max(0, score); // Ensure non-negative score + return { + score: finalScore, + details: { + baseScore, + engagementScore, + authorVerificationBonus: 0, // Cells don't have authors in the same way + verifiedUpvoteBonus: 0, + verifiedCommenterBonus: 0, + timeDecayMultiplier, + moderationPenalty: 1, // Cells aren't moderated + finalScore, + isVerified: false, // Cells don't have verification status + upvotes: totalUpvotes, + comments: cellPosts.length, + verifiedUpvotes: 0, + verifiedCommenters: 0, + daysOld, + isModerated: false, + }, + }; + } + /** + * Check if a user is verified (has ENS or ordinal ownership, or basic verification) + */ + isUserVerified(user) { + return !!(user.ensDetails || + user.ordinalDetails || + user.verificationStatus === EVerificationStatus.WALLET_CONNECTED); + } + /** + * Build user verification status map from users array + */ + buildUserVerificationStatus(users) { + const status = {}; + users.forEach((user) => { + status[user.address] = { + isVerified: this.isUserVerified(user), + hasENS: !!user.ensDetails, + hasOrdinal: !!user.ordinalDetails, + ensName: user.ensDetails?.ensName, + verificationStatus: user.verificationStatus, + }; + }); + return status; + } + /** + * Apply base score to the current score + */ + applyBaseScore(type) { + return RelevanceCalculator.BASE_SCORES[type]; + } + /** + * Apply engagement score based on upvotes and comments + */ + applyEngagementScore(upvotes, comments = []) { + const upvoteScore = upvotes.length * RelevanceCalculator.ENGAGEMENT_SCORES.UPVOTE; + const commentScore = comments.length * RelevanceCalculator.ENGAGEMENT_SCORES.COMMENT; + return upvoteScore + commentScore; + } + /** + * Apply verification bonus for verified authors + */ + applyAuthorVerificationBonus(score, authorAddress, userVerificationStatus) { + const authorStatus = userVerificationStatus[authorAddress]; + const isVerified = authorStatus?.isVerified || false; + if (!isVerified) { + return { bonus: 0, isVerified: false }; + } + // Apply different bonuses based on verification level + let bonus = 0; + if (authorStatus?.verificationStatus === + EVerificationStatus.ENS_ORDINAL_VERIFIED) { + // Full bonus for ENS/Ordinal owners + bonus = score * (RelevanceCalculator.VERIFICATION_BONUS - 1); + } + else if (authorStatus?.verificationStatus === EVerificationStatus.WALLET_CONNECTED) { + // Lower bonus for basic verified users + bonus = score * (RelevanceCalculator.BASIC_VERIFICATION_BONUS - 1); + } + return { bonus, isVerified: true }; + } + /** + * Apply verified upvote bonus + */ + applyVerifiedUpvoteBonus(upvotes, userVerificationStatus) { + const verifiedUpvotes = upvotes.filter((vote) => { + const voterStatus = userVerificationStatus[vote.author]; + return voterStatus?.isVerified; + }); + const bonus = verifiedUpvotes.length * RelevanceCalculator.VERIFIED_UPVOTE_BONUS; + return { bonus, verifiedUpvotes: verifiedUpvotes.length }; + } + /** + * Apply verified commenter bonus + */ + applyVerifiedCommenterBonus(comments, userVerificationStatus) { + const verifiedCommenters = new Set(); + comments.forEach((comment) => { + const commenterStatus = userVerificationStatus[comment.authorAddress]; + if (commenterStatus?.isVerified) { + verifiedCommenters.add(comment.authorAddress); + } + }); + const bonus = verifiedCommenters.size * RelevanceCalculator.VERIFIED_COMMENTER_BONUS; + return { bonus, verifiedCommenters: verifiedCommenters.size }; + } + /** + * Apply time decay to a score + */ + applyTimeDecay(score, timestamp) { + const daysOld = (Date.now() - timestamp) / (1000 * 60 * 60 * 24); + const multiplier = Math.exp(-RelevanceCalculator.DECAY_RATE * daysOld); + const decayedScore = score * multiplier; + return { decayedScore, multiplier, daysOld }; + } + /** + * Apply moderation penalty + */ + applyModerationPenalty(score, isModerated) { + if (isModerated) { + const penalizedScore = score * RelevanceCalculator.MODERATION_PENALTY; + return { + penalizedScore, + penalty: RelevanceCalculator.MODERATION_PENALTY, + }; + } + return { penalizedScore: score, penalty: 1 }; + } +} +RelevanceCalculator.BASE_SCORES = { + POST: 10, + COMMENT: 5, + CELL: 15, +}; +RelevanceCalculator.ENGAGEMENT_SCORES = { + UPVOTE: 1, + COMMENT: 0.5, +}; +RelevanceCalculator.VERIFICATION_BONUS = 1.25; // 25% increase for ENS/Ordinal owners +RelevanceCalculator.BASIC_VERIFICATION_BONUS = 1.1; // 10% increase for basic verified users +RelevanceCalculator.VERIFIED_UPVOTE_BONUS = 0.1; +RelevanceCalculator.VERIFIED_COMMENTER_BONUS = 0.05; +RelevanceCalculator.DECAY_RATE = 0.1; // λ = 0.1 +RelevanceCalculator.MODERATION_PENALTY = 0.5; // 50% reduction +//# sourceMappingURL=RelevanceCalculator.js.map \ No newline at end of file diff --git a/packages/core/dist/forum/RelevanceCalculator.js.map b/packages/core/dist/forum/RelevanceCalculator.js.map new file mode 100644 index 0000000..fc837c6 --- /dev/null +++ b/packages/core/dist/forum/RelevanceCalculator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RelevanceCalculator.js","sourceRoot":"","sources":["../../src/forum/RelevanceCalculator.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,mBAAmB,EAAQ,MAAM,mBAAmB,CAAC;AAG9D,MAAM,OAAO,mBAAmB;IAoB9B;;OAEG;IACH,kBAAkB,CAChB,IAAU,EACV,KAAoB,EACpB,QAAmB,EACnB,sBAA8C;QAE9C,IAAI,KAAK,GAAG,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;QACxC,MAAM,SAAS,GAAG,KAAK,CAAC;QAExB,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC;QACzD,MAAM,eAAe,GAAG,IAAI,CAAC,oBAAoB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrE,KAAK,IAAI,eAAe,CAAC;QAEzB,MAAM,EAAE,KAAK,EAAE,uBAAuB,EAAE,UAAU,EAAE,GAClD,IAAI,CAAC,4BAA4B,CAC/B,KAAK,EACL,IAAI,CAAC,aAAa,EAClB,sBAAsB,CACvB,CAAC;QACJ,KAAK,IAAI,uBAAuB,CAAC;QAEjC,MAAM,EAAE,KAAK,EAAE,mBAAmB,EAAE,eAAe,EAAE,GACnD,IAAI,CAAC,wBAAwB,CAAC,OAAO,EAAE,sBAAsB,CAAC,CAAC;QACjE,KAAK,IAAI,mBAAmB,CAAC;QAE7B,MAAM,EAAE,KAAK,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,GACzD,IAAI,CAAC,2BAA2B,CAAC,QAAQ,EAAE,sBAAsB,CAAC,CAAC;QACrE,KAAK,IAAI,sBAAsB,CAAC;QAEhC,MAAM,EACJ,YAAY,EACZ,UAAU,EAAE,mBAAmB,EAC/B,OAAO,GACR,GAAG,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;QAC/C,KAAK,GAAG,YAAY,CAAC;QAErB,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,iBAAiB,EAAE,GAClD,IAAI,CAAC,sBAAsB,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,IAAI,KAAK,CAAC,CAAC;QAC9D,KAAK,GAAG,cAAc,CAAC;QAEvB,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,4BAA4B;QAEnE,OAAO;YACL,KAAK,EAAE,UAAU;YACjB,OAAO,EAAE;gBACP,SAAS;gBACT,eAAe;gBACf,uBAAuB;gBACvB,mBAAmB;gBACnB,sBAAsB;gBACtB,mBAAmB;gBACnB,iBAAiB;gBACjB,UAAU;gBACV,UAAU;gBACV,OAAO,EAAE,OAAO,CAAC,MAAM;gBACvB,QAAQ,EAAE,QAAQ,CAAC,MAAM;gBACzB,eAAe;gBACf,kBAAkB;gBAClB,OAAO;gBACP,WAAW,EAAE,IAAI,CAAC,SAAS,IAAI,KAAK;aACrC;SACF,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,qBAAqB,CACnB,OAAgB,EAChB,KAAoB,EACpB,sBAA8C;QAE9C,mBAAmB;QACnB,IAAI,KAAK,GAAG,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;QAC3C,MAAM,SAAS,GAAG,KAAK,CAAC;QAExB,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC;QACzD,MAAM,eAAe,GAAG,IAAI,CAAC,oBAAoB,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QAC/D,KAAK,IAAI,eAAe,CAAC;QAEzB,MAAM,EAAE,KAAK,EAAE,uBAAuB,EAAE,UAAU,EAAE,GAClD,IAAI,CAAC,4BAA4B,CAC/B,KAAK,EACL,OAAO,CAAC,aAAa,EACrB,sBAAsB,CACvB,CAAC;QACJ,KAAK,IAAI,uBAAuB,CAAC;QAEjC,MAAM,EAAE,KAAK,EAAE,mBAAmB,EAAE,eAAe,EAAE,GACnD,IAAI,CAAC,wBAAwB,CAAC,OAAO,EAAE,sBAAsB,CAAC,CAAC;QACjE,KAAK,IAAI,mBAAmB,CAAC;QAE7B,MAAM,EACJ,YAAY,EACZ,UAAU,EAAE,mBAAmB,EAC/B,OAAO,GACR,GAAG,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;QAClD,KAAK,GAAG,YAAY,CAAC;QAErB,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,iBAAiB,EAAE,GAClD,IAAI,CAAC,sBAAsB,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,IAAI,KAAK,CAAC,CAAC;QACjE,KAAK,GAAG,cAAc,CAAC;QAEvB,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,4BAA4B;QAEnE,OAAO;YACL,KAAK,EAAE,UAAU;YACjB,OAAO,EAAE;gBACP,SAAS;gBACT,eAAe;gBACf,uBAAuB;gBACvB,mBAAmB;gBACnB,sBAAsB,EAAE,CAAC,EAAE,iCAAiC;gBAC5D,mBAAmB;gBACnB,iBAAiB;gBACjB,UAAU;gBACV,UAAU;gBACV,OAAO,EAAE,OAAO,CAAC,MAAM;gBACvB,QAAQ,EAAE,CAAC,EAAE,+BAA+B;gBAC5C,eAAe;gBACf,kBAAkB,EAAE,CAAC;gBACrB,OAAO;gBACP,WAAW,EAAE,OAAO,CAAC,SAAS,IAAI,KAAK;aACxC;SACF,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,kBAAkB,CAChB,IAAU,EACV,KAAa;QAEb,mBAAmB;QACnB,IAAI,KAAK,GAAG,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;QACxC,MAAM,SAAS,GAAG,KAAK,CAAC;QAExB,qCAAqC;QACrC,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,EAAE,CAAC,CAAC;QAClE,MAAM,YAAY,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;YAClD,OAAO,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,IAAI,CAAC,CAAC,CAAC;QAC3C,CAAC,EAAE,CAAC,CAAC,CAAC;QAEN,MAAM,aAAa,GACjB,SAAS,CAAC,MAAM,GAAG,mBAAmB,CAAC,iBAAiB,CAAC,OAAO,CAAC;QACnE,MAAM,eAAe,GAAG,YAAY,GAAG,GAAG,CAAC,CAAC,gCAAgC;QAC5E,MAAM,eAAe,GAAG,aAAa,GAAG,eAAe,CAAC;QACxD,KAAK,IAAI,eAAe,CAAC;QAEzB,MAAM,cAAc,GAAG,SAAS,CAAC,MAAM,CACrC,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE;YACf,OAAO,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;QAC3D,CAAC,EACD,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAC1B,CAAC;QACF,MAAM,EACJ,YAAY,EACZ,UAAU,EAAE,mBAAmB,EAC/B,OAAO,GACR,GAAG,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,cAAc,CAAC,SAAS,CAAC,CAAC;QACzD,KAAK,GAAG,YAAY,CAAC;QAErB,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,4BAA4B;QAEnE,OAAO;YACL,KAAK,EAAE,UAAU;YACjB,OAAO,EAAE;gBACP,SAAS;gBACT,eAAe;gBACf,uBAAuB,EAAE,CAAC,EAAE,2CAA2C;gBACvE,mBAAmB,EAAE,CAAC;gBACtB,sBAAsB,EAAE,CAAC;gBACzB,mBAAmB;gBACnB,iBAAiB,EAAE,CAAC,EAAE,yBAAyB;gBAC/C,UAAU;gBACV,UAAU,EAAE,KAAK,EAAE,uCAAuC;gBAC1D,OAAO,EAAE,YAAY;gBACrB,QAAQ,EAAE,SAAS,CAAC,MAAM;gBAC1B,eAAe,EAAE,CAAC;gBAClB,kBAAkB,EAAE,CAAC;gBACrB,OAAO;gBACP,WAAW,EAAE,KAAK;aACnB;SACF,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,cAAc,CAAC,IAAU;QACvB,OAAO,CAAC,CAAC,CACP,IAAI,CAAC,UAAU;YACf,IAAI,CAAC,cAAc;YACnB,IAAI,CAAC,kBAAkB,KAAK,mBAAmB,CAAC,gBAAgB,CACjE,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,2BAA2B,CAAC,KAAa;QACvC,MAAM,MAAM,GAA2B,EAAE,CAAC;QAE1C,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;YACrB,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG;gBACrB,UAAU,EAAE,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC;gBACrC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,UAAU;gBACzB,UAAU,EAAE,CAAC,CAAC,IAAI,CAAC,cAAc;gBACjC,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE,OAAO;gBACjC,kBAAkB,EAAE,IAAI,CAAC,kBAAkB;aAC5C,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;OAEG;IACK,cAAc,CAAC,IAAiC;QACtD,OAAO,mBAAmB,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;IAC/C,CAAC;IAED;;OAEG;IACK,oBAAoB,CAC1B,OAAsB,EACtB,WAAsB,EAAE;QAExB,MAAM,WAAW,GACf,OAAO,CAAC,MAAM,GAAG,mBAAmB,CAAC,iBAAiB,CAAC,MAAM,CAAC;QAChE,MAAM,YAAY,GAChB,QAAQ,CAAC,MAAM,GAAG,mBAAmB,CAAC,iBAAiB,CAAC,OAAO,CAAC;QAClE,OAAO,WAAW,GAAG,YAAY,CAAC;IACpC,CAAC;IAED;;OAEG;IACK,4BAA4B,CAClC,KAAa,EACb,aAAqB,EACrB,sBAA8C;QAE9C,MAAM,YAAY,GAAG,sBAAsB,CAAC,aAAa,CAAC,CAAC;QAC3D,MAAM,UAAU,GAAG,YAAY,EAAE,UAAU,IAAI,KAAK,CAAC;QAErD,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,EAAE,KAAK,EAAE,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;QACzC,CAAC;QAED,sDAAsD;QACtD,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IACE,YAAY,EAAE,kBAAkB;YAChC,mBAAmB,CAAC,oBAAoB,EACxC,CAAC;YACD,oCAAoC;YACpC,KAAK,GAAG,KAAK,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,GAAG,CAAC,CAAC,CAAC;QAC/D,CAAC;aAAM,IACL,YAAY,EAAE,kBAAkB,KAAK,mBAAmB,CAAC,gBAAgB,EACzE,CAAC;YACD,uCAAuC;YACvC,KAAK,GAAG,KAAK,GAAG,CAAC,mBAAmB,CAAC,wBAAwB,GAAG,CAAC,CAAC,CAAC;QACrE,CAAC;QAED,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;IACrC,CAAC;IAED;;OAEG;IACK,wBAAwB,CAC9B,OAAsB,EACtB,sBAA8C;QAE9C,MAAM,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE;YAC9C,MAAM,WAAW,GAAG,sBAAsB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACxD,OAAO,WAAW,EAAE,UAAU,CAAC;QACjC,CAAC,CAAC,CAAC;QAEH,MAAM,KAAK,GACT,eAAe,CAAC,MAAM,GAAG,mBAAmB,CAAC,qBAAqB,CAAC;QACrE,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,eAAe,CAAC,MAAM,EAAE,CAAC;IAC5D,CAAC;IAED;;OAEG;IACK,2BAA2B,CACjC,QAAmB,EACnB,sBAA8C;QAE9C,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAU,CAAC;QAE7C,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC3B,MAAM,eAAe,GAAG,sBAAsB,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YACtE,IAAI,eAAe,EAAE,UAAU,EAAE,CAAC;gBAChC,kBAAkB,CAAC,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YAChD,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,MAAM,KAAK,GACT,kBAAkB,CAAC,IAAI,GAAG,mBAAmB,CAAC,wBAAwB,CAAC;QACzE,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,CAAC,IAAI,EAAE,CAAC;IAChE,CAAC;IAED;;OAEG;IACK,cAAc,CACpB,KAAa,EACb,SAAiB;QAMjB,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC;QACjE,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,mBAAmB,CAAC,UAAU,GAAG,OAAO,CAAC,CAAC;QACvE,MAAM,YAAY,GAAG,KAAK,GAAG,UAAU,CAAC;QAExC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC;IAC/C,CAAC;IAED;;OAEG;IACK,sBAAsB,CAC5B,KAAa,EACb,WAAoB;QAEpB,IAAI,WAAW,EAAE,CAAC;YAChB,MAAM,cAAc,GAAG,KAAK,GAAG,mBAAmB,CAAC,kBAAkB,CAAC;YACtE,OAAO;gBACL,cAAc;gBACd,OAAO,EAAE,mBAAmB,CAAC,kBAAkB;aAChD,CAAC;QACJ,CAAC;QAED,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IAC/C,CAAC;;AA7WuB,+BAAW,GAAG;IACpC,IAAI,EAAE,EAAE;IACR,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,EAAE;CACT,CAAC;AAEsB,qCAAiB,GAAG;IAC1C,MAAM,EAAE,CAAC;IACT,OAAO,EAAE,GAAG;CACb,CAAC;AAEsB,sCAAkB,GAAG,IAAI,CAAC,CAAC,sCAAsC;AACjE,4CAAwB,GAAG,GAAG,CAAC,CAAC,wCAAwC;AACxE,yCAAqB,GAAG,GAAG,CAAC;AAC5B,4CAAwB,GAAG,IAAI,CAAC;AAEhC,8BAAU,GAAG,GAAG,CAAC,CAAC,UAAU;AAC5B,sCAAkB,GAAG,GAAG,CAAC,CAAC,gBAAgB"} \ No newline at end of file diff --git a/packages/core/dist/forum/transformers.d.ts b/packages/core/dist/forum/transformers.d.ts new file mode 100644 index 0000000..6386b35 --- /dev/null +++ b/packages/core/dist/forum/transformers.d.ts @@ -0,0 +1,14 @@ +import { Cell, Post, Comment } from '../types/forum'; +import { CellMessage, CommentMessage, PostMessage, VoteMessage } from '../types/waku'; +import { UserVerificationStatus } from '../types/forum'; +export declare const transformCell: (cellMessage: CellMessage, _verifyMessage?: unknown, userVerificationStatus?: UserVerificationStatus, posts?: Post[]) => Promise; +export declare const transformPost: (postMessage: PostMessage, _verifyMessage?: unknown, userVerificationStatus?: UserVerificationStatus) => Promise; +export declare const transformComment: (commentMessage: CommentMessage, _verifyMessage?: unknown, userVerificationStatus?: UserVerificationStatus) => Promise; +export declare const transformVote: (voteMessage: VoteMessage, _verifyMessage?: unknown) => Promise; +export declare const getDataFromCache: (_verifyMessage?: unknown, // Deprecated parameter, kept for compatibility +userVerificationStatus?: UserVerificationStatus) => Promise<{ + cells: Cell[]; + posts: Post[]; + comments: Comment[]; +}>; +//# sourceMappingURL=transformers.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/forum/transformers.d.ts.map b/packages/core/dist/forum/transformers.d.ts.map new file mode 100644 index 0000000..1adb178 --- /dev/null +++ b/packages/core/dist/forum/transformers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.d.ts","sourceRoot":"","sources":["../../src/forum/transformers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EACL,WAAW,EACX,cAAc,EACd,WAAW,EACX,WAAW,EACZ,MAAM,eAAe,CAAC;AAGvB,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAIxD,eAAO,MAAM,aAAa,GACxB,aAAa,WAAW,EACxB,iBAAiB,OAAO,EACxB,yBAAyB,sBAAsB,EAC/C,QAAQ,IAAI,EAAE,KACb,OAAO,CAAC,IAAI,GAAG,IAAI,CAyCrB,CAAC;AAEF,eAAO,MAAM,aAAa,GACxB,aAAa,WAAW,EACxB,iBAAiB,OAAO,EACxB,yBAAyB,sBAAsB,KAC9C,OAAO,CAAC,IAAI,GAAG,IAAI,CA8GrB,CAAC;AAEF,eAAO,MAAM,gBAAgB,GAC3B,gBAAgB,cAAc,EAC9B,iBAAiB,OAAO,EACxB,yBAAyB,sBAAsB,KAC9C,OAAO,CAAC,OAAO,GAAG,IAAI,CAgFxB,CAAC;AAEF,eAAO,MAAM,aAAa,GACxB,aAAa,WAAW,EACxB,iBAAiB,OAAO,KACvB,OAAO,CAAC,WAAW,GAAG,IAAI,CAI5B,CAAC;AAEF,eAAO,MAAM,gBAAgB,GAC3B,iBAAiB,OAAO,EAAE,+CAA+C;AACzE,yBAAyB,sBAAsB,KAC9C,OAAO,CAAC;IAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IAAC,KAAK,EAAE,IAAI,EAAE,CAAC;IAAC,QAAQ,EAAE,OAAO,EAAE,CAAA;CAAE,CAyB/D,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/forum/transformers.js b/packages/core/dist/forum/transformers.js new file mode 100644 index 0000000..e5d5029 --- /dev/null +++ b/packages/core/dist/forum/transformers.js @@ -0,0 +1,186 @@ +import messageManager from '../waku'; +import { RelevanceCalculator } from './RelevanceCalculator'; +// Validation is enforced at ingestion time by LocalDatabase. Transformers assume +// cache contains only valid, verified messages. +export const transformCell = async (cellMessage, _verifyMessage, userVerificationStatus, posts) => { + // Message validity already enforced upstream + const transformedCell = { + id: cellMessage.id, + type: cellMessage.type, + author: cellMessage.author, + name: cellMessage.name, + description: cellMessage.description, + icon: cellMessage.icon || '', + timestamp: cellMessage.timestamp, + signature: cellMessage.signature, + browserPubKey: cellMessage.browserPubKey, + delegationProof: cellMessage.delegationProof, + }; + // Calculate relevance score if user verification status and posts are provided + if (userVerificationStatus && posts) { + const relevanceCalculator = new RelevanceCalculator(); + const relevanceResult = relevanceCalculator.calculateCellScore(transformedCell, posts); + // Calculate active member count + const cellPosts = posts.filter((post) => post.cellId === cellMessage.id); + const activeMembers = new Set(); + cellPosts.forEach((post) => { + activeMembers.add(post.authorAddress); + }); + return { + ...transformedCell, + relevanceScore: relevanceResult.score, + activeMemberCount: activeMembers.size, + relevanceDetails: relevanceResult.details, + }; + } + return transformedCell; +}; +export const transformPost = async (postMessage, _verifyMessage, userVerificationStatus) => { + // Message validity already enforced upstream + const votes = Object.values(messageManager.messageCache.votes).filter((vote) => vote.targetId === postMessage.id); + // Votes in cache are already validated; just map + const filteredVotes = votes; + const upvotes = filteredVotes.filter((vote) => vote !== null && vote.value === 1); + const downvotes = filteredVotes.filter((vote) => vote !== null && vote.value === -1); + const modMsg = messageManager.messageCache.moderations[postMessage.id]; + const isPostModerated = !!modMsg && modMsg.targetType === 'post'; + const userModMsg = Object.values(messageManager.messageCache.moderations).find((m) => m.targetType === 'user' && + m.cellId === postMessage.cellId && + m.targetId === postMessage.author); + const isUserModerated = !!userModMsg; + const transformedPost = { + id: postMessage.id, + type: postMessage.type, + author: postMessage.author, + cellId: postMessage.cellId, + authorAddress: postMessage.author, + title: postMessage.title, + content: postMessage.content, + timestamp: postMessage.timestamp, + signature: postMessage.signature, + browserPubKey: postMessage.browserPubKey, + delegationProof: postMessage.delegationProof, + upvotes, + downvotes, + moderated: isPostModerated || isUserModerated, + moderatedBy: isPostModerated + ? modMsg.author + : isUserModerated + ? userModMsg.author + : undefined, + moderationReason: isPostModerated + ? modMsg.reason + : isUserModerated + ? userModMsg.reason + : undefined, + moderationTimestamp: isPostModerated + ? modMsg.timestamp + : isUserModerated + ? userModMsg.timestamp + : undefined, + // mark pending for optimistic UI if not yet acknowledged + // not persisted as a field; UI can check via LocalDatabase + }; + // Calculate relevance score if user verification status is provided + if (userVerificationStatus) { + const relevanceCalculator = new RelevanceCalculator(); + // Get comments for this post + const comments = await Promise.all(Object.values(messageManager.messageCache.comments).map((comment) => transformComment(comment, undefined, userVerificationStatus))).then((comments) => comments.filter((comment) => comment !== null)); + const postComments = comments.filter((comment) => comment.postId === postMessage.id); + const relevanceResult = relevanceCalculator.calculatePostScore(transformedPost, filteredVotes, postComments, userVerificationStatus); + const relevanceScore = relevanceResult.score; + // Calculate verified upvotes and commenters + const verifiedUpvotes = upvotes.filter((vote) => { + const voterStatus = userVerificationStatus[vote.author]; + return voterStatus?.isVerified; + }).length; + const verifiedCommenters = new Set(); + postComments.forEach((comment) => { + const commenterStatus = userVerificationStatus[comment.authorAddress]; + if (commenterStatus?.isVerified) { + verifiedCommenters.add(comment.authorAddress); + } + }); + return { + ...transformedPost, + relevanceScore, + verifiedUpvotes, + verifiedCommenters: Array.from(verifiedCommenters), + relevanceDetails: relevanceResult.details, + }; + } + return transformedPost; +}; +export const transformComment = async (commentMessage, _verifyMessage, userVerificationStatus) => { + // Message validity already enforced upstream + const votes = Object.values(messageManager.messageCache.votes).filter((vote) => vote.targetId === commentMessage.id); + // Votes in cache are already validated + const filteredVotes = votes; + const upvotes = filteredVotes.filter((vote) => vote !== null && vote.value === 1); + const downvotes = filteredVotes.filter((vote) => vote !== null && vote.value === -1); + const modMsg = messageManager.messageCache.moderations[commentMessage.id]; + const isCommentModerated = !!modMsg && modMsg.targetType === 'comment'; + // Find the post to get the correct cell ID + const parentPost = Object.values(messageManager.messageCache.posts).find((post) => post.id === commentMessage.postId); + const userModMsg = Object.values(messageManager.messageCache.moderations).find((m) => m.targetType === 'user' && + m.cellId === parentPost?.cellId && + m.targetId === commentMessage.author); + const isUserModerated = !!userModMsg; + const transformedComment = { + id: commentMessage.id, + type: commentMessage.type, + author: commentMessage.author, + postId: commentMessage.postId, + authorAddress: commentMessage.author, + content: commentMessage.content, + timestamp: commentMessage.timestamp, + signature: commentMessage.signature, + browserPubKey: commentMessage.browserPubKey, + delegationProof: commentMessage.delegationProof, + upvotes, + downvotes, + moderated: isCommentModerated || isUserModerated, + moderatedBy: isCommentModerated + ? modMsg.author + : isUserModerated + ? userModMsg.author + : undefined, + moderationReason: isCommentModerated + ? modMsg.reason + : isUserModerated + ? userModMsg.reason + : undefined, + moderationTimestamp: isCommentModerated + ? modMsg.timestamp + : isUserModerated + ? userModMsg.timestamp + : undefined, + // mark pending for optimistic UI via LocalDatabase lookup + }; + // Calculate relevance score if user verification status is provided + if (userVerificationStatus) { + const relevanceCalculator = new RelevanceCalculator(); + const relevanceResult = relevanceCalculator.calculateCommentScore(transformedComment, filteredVotes.filter((vote) => vote !== null), userVerificationStatus); + return { + ...transformedComment, + relevanceScore: relevanceResult.score, + relevanceDetails: relevanceResult.details, + }; + } + return transformedComment; +}; +export const transformVote = async (voteMessage, _verifyMessage) => { + // Message validity already enforced upstream + return voteMessage; +}; +export const getDataFromCache = async (_verifyMessage, // Deprecated parameter, kept for compatibility +userVerificationStatus) => { + // First transform posts and comments to get relevance scores + // All validation is now handled internally by the transform functions + const posts = await Promise.all(Object.values(messageManager.messageCache.posts).map((post) => transformPost(post, undefined, userVerificationStatus))).then((posts) => posts.filter((post) => post !== null)); + const comments = await Promise.all(Object.values(messageManager.messageCache.comments).map((c) => transformComment(c, undefined, userVerificationStatus))).then((comments) => comments.filter((comment) => comment !== null)); + // Then transform cells with posts for relevance calculation + const cells = await Promise.all(Object.values(messageManager.messageCache.cells).map((cell) => transformCell(cell, undefined, userVerificationStatus, posts))).then((cells) => cells.filter((cell) => cell !== null)); + return { cells, posts, comments }; +}; +//# sourceMappingURL=transformers.js.map \ No newline at end of file diff --git a/packages/core/dist/forum/transformers.js.map b/packages/core/dist/forum/transformers.js.map new file mode 100644 index 0000000..c3896df --- /dev/null +++ b/packages/core/dist/forum/transformers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.js","sourceRoot":"","sources":["../../src/forum/transformers.ts"],"names":[],"mappings":"AAOA,OAAO,cAAc,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,iFAAiF;AACjF,gDAAgD;AAEhD,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,EAChC,WAAwB,EACxB,cAAwB,EACxB,sBAA+C,EAC/C,KAAc,EACQ,EAAE;IACxB,6CAA6C;IAE7C,MAAM,eAAe,GAAS;QAC5B,EAAE,EAAE,WAAW,CAAC,EAAE;QAClB,IAAI,EAAE,WAAW,CAAC,IAAI;QACtB,MAAM,EAAE,WAAW,CAAC,MAAM;QAC1B,IAAI,EAAE,WAAW,CAAC,IAAI;QACtB,WAAW,EAAE,WAAW,CAAC,WAAW;QACpC,IAAI,EAAE,WAAW,CAAC,IAAI,IAAI,EAAE;QAC5B,SAAS,EAAE,WAAW,CAAC,SAAS;QAChC,SAAS,EAAE,WAAW,CAAC,SAAS;QAChC,aAAa,EAAE,WAAW,CAAC,aAAa;QACxC,eAAe,EAAE,WAAW,CAAC,eAAe;KAC7C,CAAC;IAEF,+EAA+E;IAC/E,IAAI,sBAAsB,IAAI,KAAK,EAAE,CAAC;QACpC,MAAM,mBAAmB,GAAG,IAAI,mBAAmB,EAAE,CAAC;QAEtD,MAAM,eAAe,GAAG,mBAAmB,CAAC,kBAAkB,CAC5D,eAAe,EACf,KAAK,CACN,CAAC;QAEF,gCAAgC;QAChC,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,KAAK,WAAW,CAAC,EAAE,CAAC,CAAC;QACzE,MAAM,aAAa,GAAG,IAAI,GAAG,EAAU,CAAC;QACxC,SAAS,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;YACzB,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QACxC,CAAC,CAAC,CAAC;QAEH,OAAO;YACL,GAAG,eAAe;YAClB,cAAc,EAAE,eAAe,CAAC,KAAK;YACrC,iBAAiB,EAAE,aAAa,CAAC,IAAI;YACrC,gBAAgB,EAAE,eAAe,CAAC,OAAO;SAC1C,CAAC;IACJ,CAAC;IAED,OAAO,eAAe,CAAC;AACzB,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,EAChC,WAAwB,EACxB,cAAwB,EACxB,sBAA+C,EACzB,EAAE;IACxB,6CAA6C;IAE7C,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,MAAM,CACnE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,KAAK,WAAW,CAAC,EAAE,CAC3C,CAAC;IACF,iDAAiD;IACjD,MAAM,aAAa,GAAG,KAAK,CAAC;IAC5B,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAClC,CAAC,IAAI,EAAuB,EAAE,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,CAAC,CACjE,CAAC;IACF,MAAM,SAAS,GAAG,aAAa,CAAC,MAAM,CACpC,CAAC,IAAI,EAAuB,EAAE,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,CAAC,CAAC,CAClE,CAAC;IAEF,MAAM,MAAM,GAAG,cAAc,CAAC,YAAY,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IACvE,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,UAAU,KAAK,MAAM,CAAC;IACjE,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAC9B,cAAc,CAAC,YAAY,CAAC,WAAW,CACxC,CAAC,IAAI,CACJ,CAAC,CAAC,EAAE,EAAE,CACJ,CAAC,CAAC,UAAU,KAAK,MAAM;QACvB,CAAC,CAAC,MAAM,KAAK,WAAW,CAAC,MAAM;QAC/B,CAAC,CAAC,QAAQ,KAAK,WAAW,CAAC,MAAM,CACpC,CAAC;IACF,MAAM,eAAe,GAAG,CAAC,CAAC,UAAU,CAAC;IAErC,MAAM,eAAe,GAAS;QAC5B,EAAE,EAAE,WAAW,CAAC,EAAE;QAClB,IAAI,EAAE,WAAW,CAAC,IAAI;QACtB,MAAM,EAAE,WAAW,CAAC,MAAM;QAC1B,MAAM,EAAE,WAAW,CAAC,MAAM;QAC1B,aAAa,EAAE,WAAW,CAAC,MAAM;QACjC,KAAK,EAAE,WAAW,CAAC,KAAK;QACxB,OAAO,EAAE,WAAW,CAAC,OAAO;QAC5B,SAAS,EAAE,WAAW,CAAC,SAAS;QAChC,SAAS,EAAE,WAAW,CAAC,SAAS;QAChC,aAAa,EAAE,WAAW,CAAC,aAAa;QACxC,eAAe,EAAE,WAAW,CAAC,eAAe;QAC5C,OAAO;QACP,SAAS;QACT,SAAS,EAAE,eAAe,IAAI,eAAe;QAC7C,WAAW,EAAE,eAAe;YAC1B,CAAC,CAAC,MAAM,CAAC,MAAM;YACf,CAAC,CAAC,eAAe;gBACf,CAAC,CAAC,UAAW,CAAC,MAAM;gBACpB,CAAC,CAAC,SAAS;QACf,gBAAgB,EAAE,eAAe;YAC/B,CAAC,CAAC,MAAM,CAAC,MAAM;YACf,CAAC,CAAC,eAAe;gBACf,CAAC,CAAC,UAAW,CAAC,MAAM;gBACpB,CAAC,CAAC,SAAS;QACf,mBAAmB,EAAE,eAAe;YAClC,CAAC,CAAC,MAAM,CAAC,SAAS;YAClB,CAAC,CAAC,eAAe;gBACf,CAAC,CAAC,UAAW,CAAC,SAAS;gBACvB,CAAC,CAAC,SAAS;QACf,yDAAyD;QACzD,2DAA2D;KAC5D,CAAC;IAEF,oEAAoE;IACpE,IAAI,sBAAsB,EAAE,CAAC;QAC3B,MAAM,mBAAmB,GAAG,IAAI,mBAAmB,EAAE,CAAC;QAEtD,6BAA6B;QAC7B,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,GAAG,CAChC,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAClE,gBAAgB,CAAC,OAAO,EAAE,SAAS,EAAE,sBAAsB,CAAC,CAC7D,CACF,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAClB,QAAQ,CAAC,MAAM,CAAC,CAAC,OAAO,EAAsB,EAAE,CAAC,OAAO,KAAK,IAAI,CAAC,CACnE,CAAC;QACF,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAClC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,KAAK,WAAW,CAAC,EAAE,CAC/C,CAAC;QAEF,MAAM,eAAe,GAAG,mBAAmB,CAAC,kBAAkB,CAC5D,eAAe,EACf,aAAa,EACb,YAAY,EACZ,sBAAsB,CACvB,CAAC;QAEF,MAAM,cAAc,GAAG,eAAe,CAAC,KAAK,CAAC;QAE7C,4CAA4C;QAC5C,MAAM,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE;YAC9C,MAAM,WAAW,GAAG,sBAAsB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACxD,OAAO,WAAW,EAAE,UAAU,CAAC;QACjC,CAAC,CAAC,CAAC,MAAM,CAAC;QAEV,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAU,CAAC;QAC7C,YAAY,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC/B,MAAM,eAAe,GAAG,sBAAsB,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YACtE,IAAI,eAAe,EAAE,UAAU,EAAE,CAAC;gBAChC,kBAAkB,CAAC,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YAChD,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,OAAO;YACL,GAAG,eAAe;YAClB,cAAc;YACd,eAAe;YACf,kBAAkB,EAAE,KAAK,CAAC,IAAI,CAAC,kBAAkB,CAAC;YAClD,gBAAgB,EAAE,eAAe,CAAC,OAAO;SAC1C,CAAC;IACJ,CAAC;IAED,OAAO,eAAe,CAAC;AACzB,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,EACnC,cAA8B,EAC9B,cAAwB,EACxB,sBAA+C,EACtB,EAAE;IAC3B,6CAA6C;IAC7C,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,MAAM,CACnE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,KAAK,cAAc,CAAC,EAAE,CAC9C,CAAC;IACF,uCAAuC;IACvC,MAAM,aAAa,GAAG,KAAK,CAAC;IAC5B,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAClC,CAAC,IAAI,EAAuB,EAAE,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,CAAC,CACjE,CAAC;IACF,MAAM,SAAS,GAAG,aAAa,CAAC,MAAM,CACpC,CAAC,IAAI,EAAuB,EAAE,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,CAAC,CAAC,CAClE,CAAC;IAEF,MAAM,MAAM,GAAG,cAAc,CAAC,YAAY,CAAC,WAAW,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC;IAC1E,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,UAAU,KAAK,SAAS,CAAC;IACvE,2CAA2C;IAC3C,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,IAAI,CACtE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,cAAc,CAAC,MAAM,CAC5C,CAAC;IACF,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAC9B,cAAc,CAAC,YAAY,CAAC,WAAW,CACxC,CAAC,IAAI,CACJ,CAAC,CAAC,EAAE,EAAE,CACJ,CAAC,CAAC,UAAU,KAAK,MAAM;QACvB,CAAC,CAAC,MAAM,KAAK,UAAU,EAAE,MAAM;QAC/B,CAAC,CAAC,QAAQ,KAAK,cAAc,CAAC,MAAM,CACvC,CAAC;IACF,MAAM,eAAe,GAAG,CAAC,CAAC,UAAU,CAAC;IAErC,MAAM,kBAAkB,GAAY;QAClC,EAAE,EAAE,cAAc,CAAC,EAAE;QACrB,IAAI,EAAE,cAAc,CAAC,IAAI;QACzB,MAAM,EAAE,cAAc,CAAC,MAAM;QAC7B,MAAM,EAAE,cAAc,CAAC,MAAM;QAC7B,aAAa,EAAE,cAAc,CAAC,MAAM;QACpC,OAAO,EAAE,cAAc,CAAC,OAAO;QAC/B,SAAS,EAAE,cAAc,CAAC,SAAS;QACnC,SAAS,EAAE,cAAc,CAAC,SAAS;QACnC,aAAa,EAAE,cAAc,CAAC,aAAa;QAC3C,eAAe,EAAE,cAAc,CAAC,eAAe;QAC/C,OAAO;QACP,SAAS;QACT,SAAS,EAAE,kBAAkB,IAAI,eAAe;QAChD,WAAW,EAAE,kBAAkB;YAC7B,CAAC,CAAC,MAAM,CAAC,MAAM;YACf,CAAC,CAAC,eAAe;gBACf,CAAC,CAAC,UAAW,CAAC,MAAM;gBACpB,CAAC,CAAC,SAAS;QACf,gBAAgB,EAAE,kBAAkB;YAClC,CAAC,CAAC,MAAM,CAAC,MAAM;YACf,CAAC,CAAC,eAAe;gBACf,CAAC,CAAC,UAAW,CAAC,MAAM;gBACpB,CAAC,CAAC,SAAS;QACf,mBAAmB,EAAE,kBAAkB;YACrC,CAAC,CAAC,MAAM,CAAC,SAAS;YAClB,CAAC,CAAC,eAAe;gBACf,CAAC,CAAC,UAAW,CAAC,SAAS;gBACvB,CAAC,CAAC,SAAS;QACf,0DAA0D;KAC3D,CAAC;IAEF,oEAAoE;IACpE,IAAI,sBAAsB,EAAE,CAAC;QAC3B,MAAM,mBAAmB,GAAG,IAAI,mBAAmB,EAAE,CAAC;QAEtD,MAAM,eAAe,GAAG,mBAAmB,CAAC,qBAAqB,CAC/D,kBAAkB,EAClB,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,EAAuB,EAAE,CAAC,IAAI,KAAK,IAAI,CAAC,EAClE,sBAAsB,CACvB,CAAC;QAEF,OAAO;YACL,GAAG,kBAAkB;YACrB,cAAc,EAAE,eAAe,CAAC,KAAK;YACrC,gBAAgB,EAAE,eAAe,CAAC,OAAO;SAC1C,CAAC;IACJ,CAAC;IAED,OAAO,kBAAkB,CAAC;AAC5B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,EAChC,WAAwB,EACxB,cAAwB,EACK,EAAE;IAC/B,6CAA6C;IAE7C,OAAO,WAAW,CAAC;AACrB,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,EACnC,cAAwB,EAAE,+CAA+C;AACzE,sBAA+C,EACiB,EAAE;IAClE,6DAA6D;IAC7D,sEAAsE;IACtE,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,GAAG,CAC7B,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAC5D,aAAa,CAAC,IAAI,EAAE,SAAS,EAAE,sBAAsB,CAAC,CACvD,CACF,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAgB,EAAE,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC;IAEvE,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,GAAG,CAChC,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAC5D,gBAAgB,CAAC,CAAC,EAAE,SAAS,EAAE,sBAAsB,CAAC,CACvD,CACF,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAClB,QAAQ,CAAC,MAAM,CAAC,CAAC,OAAO,EAAsB,EAAE,CAAC,OAAO,KAAK,IAAI,CAAC,CACnE,CAAC;IAEF,4DAA4D;IAC5D,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,GAAG,CAC7B,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAC5D,aAAa,CAAC,IAAI,EAAE,SAAS,EAAE,sBAAsB,EAAE,KAAK,CAAC,CAC9D,CACF,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAgB,EAAE,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC;IAEvE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC;AACpC,CAAC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/index.d.ts b/packages/core/dist/index.d.ts new file mode 100644 index 0000000..2415aa8 --- /dev/null +++ b/packages/core/dist/index.d.ts @@ -0,0 +1,15 @@ +export { localDatabase } from './database/LocalDatabase'; +export * from './database/schema'; +export * from './delegation'; +export { ForumActions } from './forum/ForumActions'; +export { RelevanceCalculator } from './forum/RelevanceCalculator'; +export * from './forum/transformers'; +export { BookmarkService } from './services/BookmarkService'; +export { MessageService } from './services/MessageService'; +export { UserIdentityService } from './services/UserIdentityService'; +export * from './services/Ordinal'; +export * from './types'; +export * from './utils'; +export * from './waku'; +export * from './wallet'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/index.d.ts.map b/packages/core/dist/index.d.ts.map new file mode 100644 index 0000000..3fb1b0c --- /dev/null +++ b/packages/core/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,cAAc,mBAAmB,CAAC;AAGlC,cAAc,cAAc,CAAC;AAG7B,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,cAAc,sBAAsB,CAAC;AAGrC,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,cAAc,oBAAoB,CAAC;AAGnC,cAAc,SAAS,CAAC;AAGxB,cAAc,SAAS,CAAC;AAGxB,cAAc,QAAQ,CAAC;AAGvB,cAAc,UAAU,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/index.js b/packages/core/dist/index.js new file mode 100644 index 0000000..2cd3ba7 --- /dev/null +++ b/packages/core/dist/index.js @@ -0,0 +1,23 @@ +// Database exports +export { localDatabase } from './database/LocalDatabase'; +export * from './database/schema'; +// Delegation exports +export * from './delegation'; +// Forum exports +export { ForumActions } from './forum/ForumActions'; +export { RelevanceCalculator } from './forum/RelevanceCalculator'; +export * from './forum/transformers'; +// Services exports +export { BookmarkService } from './services/BookmarkService'; +export { MessageService } from './services/MessageService'; +export { UserIdentityService } from './services/UserIdentityService'; +export * from './services/Ordinal'; +// Types exports +export * from './types'; +// Utils exports +export * from './utils'; +// Waku exports +export * from './waku'; +// Wallet exports +export * from './wallet'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/core/dist/index.js.map b/packages/core/dist/index.js.map new file mode 100644 index 0000000..0988d37 --- /dev/null +++ b/packages/core/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,mBAAmB;AACnB,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,cAAc,mBAAmB,CAAC;AAElC,qBAAqB;AACrB,cAAc,cAAc,CAAC;AAE7B,gBAAgB;AAChB,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,cAAc,sBAAsB,CAAC;AAErC,mBAAmB;AACnB,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,cAAc,oBAAoB,CAAC;AAEnC,gBAAgB;AAChB,cAAc,SAAS,CAAC;AAExB,gBAAgB;AAChB,cAAc,SAAS,CAAC;AAExB,eAAe;AACf,cAAc,QAAQ,CAAC;AAEvB,iBAAiB;AACjB,cAAc,UAAU,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/services/BookmarkService.d.ts b/packages/core/dist/services/BookmarkService.d.ts new file mode 100644 index 0000000..92e5dbd --- /dev/null +++ b/packages/core/dist/services/BookmarkService.d.ts @@ -0,0 +1,57 @@ +import { Bookmark, BookmarkType, Post, Comment } from '../types/forum'; +/** + * Service for managing bookmarks + * Handles all bookmark-related operations including CRUD operations + * and metadata extraction for display purposes + */ +export declare class BookmarkService { + /** + * Create a bookmark for a post + */ + static bookmarkPost(post: Post, userId: string, cellId?: string): Promise; + /** + * Create a bookmark for a comment + */ + static bookmarkComment(comment: Comment, userId: string, postId?: string): Promise; + /** + * Remove a bookmark + */ + static removeBookmark(type: BookmarkType, targetId: string): Promise; + /** + * Toggle bookmark status for a post + */ + static togglePostBookmark(post: Post, userId: string, cellId?: string): Promise; + /** + * Toggle bookmark status for a comment + */ + static toggleCommentBookmark(comment: Comment, userId: string, postId?: string): Promise; + /** + * Check if a post is bookmarked by a user + */ + static isPostBookmarked(userId: string, postId: string): boolean; + /** + * Check if a comment is bookmarked by a user + */ + static isCommentBookmarked(userId: string, commentId: string): boolean; + /** + * Get all bookmarks for a user + */ + static getUserBookmarks(userId: string): Promise; + /** + * Get bookmarks by type for a user + */ + static getUserBookmarksByType(userId: string, type: BookmarkType): Promise; + /** + * Get bookmark by ID + */ + static getBookmark(bookmarkId: string): Bookmark | undefined; + /** + * Get all bookmarks (for debugging/admin purposes) + */ + static getAllBookmarks(): Bookmark[]; + /** + * Clear all bookmarks for a user (useful for account cleanup) + */ + static clearUserBookmarks(userId: string): Promise; +} +//# sourceMappingURL=BookmarkService.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/services/BookmarkService.d.ts.map b/packages/core/dist/services/BookmarkService.d.ts.map new file mode 100644 index 0000000..b63c42b --- /dev/null +++ b/packages/core/dist/services/BookmarkService.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"BookmarkService.d.ts","sourceRoot":"","sources":["../../src/services/BookmarkService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAGvE;;;;GAIG;AACH,qBAAa,eAAe;IAC1B;;OAEG;WACiB,YAAY,CAC9B,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,QAAQ,CAAC;IAiBpB;;OAEG;WACiB,eAAe,CACjC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,QAAQ,CAAC;IAsBpB;;OAEG;WACiB,cAAc,CAChC,IAAI,EAAE,YAAY,EAClB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,IAAI,CAAC;IAKhB;;OAEG;WACiB,kBAAkB,CACpC,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,OAAO,CAAC;IAYnB;;OAEG;WACiB,qBAAqB,CACvC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,OAAO,CAAC;IAgBnB;;OAEG;WACW,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO;IAIvE;;OAEG;WACW,mBAAmB,CAC/B,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,GAChB,OAAO;IAIV;;OAEG;WACiB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;IAIzE;;OAEG;WACiB,sBAAsB,CACxC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,YAAY,GACjB,OAAO,CAAC,QAAQ,EAAE,CAAC;IAItB;;OAEG;WACW,WAAW,CAAC,UAAU,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS;IAInE;;OAEG;WACW,eAAe,IAAI,QAAQ,EAAE;IAI3C;;OAEG;WACiB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAMtE"} \ No newline at end of file diff --git a/packages/core/dist/services/BookmarkService.js b/packages/core/dist/services/BookmarkService.js new file mode 100644 index 0000000..2d4bb4b --- /dev/null +++ b/packages/core/dist/services/BookmarkService.js @@ -0,0 +1,127 @@ +import { BookmarkType } from '../types/forum'; +import { localDatabase } from '../database/LocalDatabase'; +/** + * Service for managing bookmarks + * Handles all bookmark-related operations including CRUD operations + * and metadata extraction for display purposes + */ +export class BookmarkService { + /** + * Create a bookmark for a post + */ + static async bookmarkPost(post, userId, cellId) { + const bookmark = { + id: `post:${post.id}`, + type: BookmarkType.POST, + targetId: post.id, + userId, + createdAt: Date.now(), + title: post.title, + author: post.author, + cellId: cellId || post.cellId, + postId: post.id, + }; + await localDatabase.addBookmark(bookmark); + return bookmark; + } + /** + * Create a bookmark for a comment + */ + static async bookmarkComment(comment, userId, postId) { + // Create a preview of the comment content for display + const preview = comment.content.length > 100 + ? `${comment.content.substring(0, 100)}...` + : comment.content; + const bookmark = { + id: `comment:${comment.id}`, + type: BookmarkType.COMMENT, + targetId: comment.id, + userId, + createdAt: Date.now(), + title: preview, + author: comment.author, + postId: postId || comment.postId, + }; + await localDatabase.addBookmark(bookmark); + return bookmark; + } + /** + * Remove a bookmark + */ + static async removeBookmark(type, targetId) { + const bookmarkId = `${type}:${targetId}`; + await localDatabase.removeBookmark(bookmarkId); + } + /** + * Toggle bookmark status for a post + */ + static async togglePostBookmark(post, userId, cellId) { + const isBookmarked = localDatabase.isBookmarked(userId, 'post', post.id); + if (isBookmarked) { + await this.removeBookmark(BookmarkType.POST, post.id); + return false; + } + else { + await this.bookmarkPost(post, userId, cellId); + return true; + } + } + /** + * Toggle bookmark status for a comment + */ + static async toggleCommentBookmark(comment, userId, postId) { + const isBookmarked = localDatabase.isBookmarked(userId, 'comment', comment.id); + if (isBookmarked) { + await this.removeBookmark(BookmarkType.COMMENT, comment.id); + return false; + } + else { + await this.bookmarkComment(comment, userId, postId); + return true; + } + } + /** + * Check if a post is bookmarked by a user + */ + static isPostBookmarked(userId, postId) { + return localDatabase.isBookmarked(userId, 'post', postId); + } + /** + * Check if a comment is bookmarked by a user + */ + static isCommentBookmarked(userId, commentId) { + return localDatabase.isBookmarked(userId, 'comment', commentId); + } + /** + * Get all bookmarks for a user + */ + static async getUserBookmarks(userId) { + return localDatabase.getUserBookmarks(userId); + } + /** + * Get bookmarks by type for a user + */ + static async getUserBookmarksByType(userId, type) { + return localDatabase.getUserBookmarksByType(userId, type); + } + /** + * Get bookmark by ID + */ + static getBookmark(bookmarkId) { + return localDatabase.getBookmark(bookmarkId); + } + /** + * Get all bookmarks (for debugging/admin purposes) + */ + static getAllBookmarks() { + return localDatabase.getAllBookmarks(); + } + /** + * Clear all bookmarks for a user (useful for account cleanup) + */ + static async clearUserBookmarks(userId) { + const bookmarks = await this.getUserBookmarks(userId); + await Promise.all(bookmarks.map((bookmark) => localDatabase.removeBookmark(bookmark.id))); + } +} +//# sourceMappingURL=BookmarkService.js.map \ No newline at end of file diff --git a/packages/core/dist/services/BookmarkService.js.map b/packages/core/dist/services/BookmarkService.js.map new file mode 100644 index 0000000..9131711 --- /dev/null +++ b/packages/core/dist/services/BookmarkService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"BookmarkService.js","sourceRoot":"","sources":["../../src/services/BookmarkService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,YAAY,EAAiB,MAAM,gBAAgB,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAE1D;;;;GAIG;AACH,MAAM,OAAO,eAAe;IAC1B;;OAEG;IACI,MAAM,CAAC,KAAK,CAAC,YAAY,CAC9B,IAAU,EACV,MAAc,EACd,MAAe;QAEf,MAAM,QAAQ,GAAa;YACzB,EAAE,EAAE,QAAQ,IAAI,CAAC,EAAE,EAAE;YACrB,IAAI,EAAE,YAAY,CAAC,IAAI;YACvB,QAAQ,EAAE,IAAI,CAAC,EAAE;YACjB,MAAM;YACN,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;YACrB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,MAAM,EAAE,MAAM,IAAI,IAAI,CAAC,MAAM;YAC7B,MAAM,EAAE,IAAI,CAAC,EAAE;SAChB,CAAC;QAEF,MAAM,aAAa,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC1C,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,KAAK,CAAC,eAAe,CACjC,OAAgB,EAChB,MAAc,EACd,MAAe;QAEf,sDAAsD;QACtD,MAAM,OAAO,GACX,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,GAAG;YAC1B,CAAC,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,KAAK;YAC3C,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC;QAEtB,MAAM,QAAQ,GAAa;YACzB,EAAE,EAAE,WAAW,OAAO,CAAC,EAAE,EAAE;YAC3B,IAAI,EAAE,YAAY,CAAC,OAAO;YAC1B,QAAQ,EAAE,OAAO,CAAC,EAAE;YACpB,MAAM;YACN,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;YACrB,KAAK,EAAE,OAAO;YACd,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,MAAM,EAAE,MAAM,IAAI,OAAO,CAAC,MAAM;SACjC,CAAC;QAEF,MAAM,aAAa,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC1C,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,KAAK,CAAC,cAAc,CAChC,IAAkB,EAClB,QAAgB;QAEhB,MAAM,UAAU,GAAG,GAAG,IAAI,IAAI,QAAQ,EAAE,CAAC;QACzC,MAAM,aAAa,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;IACjD,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,KAAK,CAAC,kBAAkB,CACpC,IAAU,EACV,MAAc,EACd,MAAe;QAEf,MAAM,YAAY,GAAG,aAAa,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC;QAEzE,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,IAAI,CAAC,cAAc,CAAC,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC;YACtD,OAAO,KAAK,CAAC;QACf,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;YAC9C,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,KAAK,CAAC,qBAAqB,CACvC,OAAgB,EAChB,MAAc,EACd,MAAe;QAEf,MAAM,YAAY,GAAG,aAAa,CAAC,YAAY,CAC7C,MAAM,EACN,SAAS,EACT,OAAO,CAAC,EAAE,CACX,CAAC;QAEF,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,IAAI,CAAC,cAAc,CAAC,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;YAC5D,OAAO,KAAK,CAAC;QACf,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,CAAC,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;YACpD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,gBAAgB,CAAC,MAAc,EAAE,MAAc;QAC3D,OAAO,aAAa,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5D,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,mBAAmB,CAC/B,MAAc,EACd,SAAiB;QAEjB,OAAO,aAAa,CAAC,YAAY,CAAC,MAAM,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;IAClE,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC,MAAc;QACjD,OAAO,aAAa,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;IAChD,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,KAAK,CAAC,sBAAsB,CACxC,MAAc,EACd,IAAkB;QAElB,OAAO,aAAa,CAAC,sBAAsB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC5D,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,WAAW,CAAC,UAAkB;QAC1C,OAAO,aAAa,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;IAC/C,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,eAAe;QAC3B,OAAO,aAAa,CAAC,eAAe,EAAE,CAAC;IACzC,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,KAAK,CAAC,kBAAkB,CAAC,MAAc;QACnD,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;QACtD,MAAM,OAAO,CAAC,GAAG,CACf,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,aAAa,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CACvE,CAAC;IACJ,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/services/MessageService.d.ts b/packages/core/dist/services/MessageService.d.ts new file mode 100644 index 0000000..aa1988a --- /dev/null +++ b/packages/core/dist/services/MessageService.d.ts @@ -0,0 +1,30 @@ +import { OpchanMessage } from '../types/forum'; +import { UnsignedMessage } from '../types/waku'; +import { DelegationManager } from '../delegation'; +export interface MessageResult { + success: boolean; + message?: OpchanMessage; + error?: string; +} +export interface MessageServiceInterface { + sendMessage(message: UnsignedMessage): Promise; + verifyMessage(message: OpchanMessage): Promise; + signAndBroadcastMessage(message: UnsignedMessage): Promise; +} +export declare class MessageService implements MessageServiceInterface { + private delegationManager; + constructor(delegationManager: DelegationManager); + /** + * Sign and send a message to the Waku network + */ + sendMessage(message: UnsignedMessage): Promise; + /** + * Sign and broadcast a message (simplified version for profile updates) + */ + signAndBroadcastMessage(message: UnsignedMessage): Promise; + /** + * Verify a message signature + */ + verifyMessage(message: OpchanMessage): Promise; +} +//# sourceMappingURL=MessageService.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/services/MessageService.d.ts.map b/packages/core/dist/services/MessageService.d.ts.map new file mode 100644 index 0000000..23c2db0 --- /dev/null +++ b/packages/core/dist/services/MessageService.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"MessageService.d.ts","sourceRoot":"","sources":["../../src/services/MessageService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAGlD,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,aAAa,CAAC;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,uBAAuB;IACtC,WAAW,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IAC9D,aAAa,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACxD,uBAAuB,CACrB,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC;CAClC;AAED,qBAAa,cAAe,YAAW,uBAAuB;IAC5D,OAAO,CAAC,iBAAiB,CAAoB;gBAEjC,iBAAiB,EAAE,iBAAiB;IAIhD;;OAEG;IACG,WAAW,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,aAAa,CAAC;IAqDnE;;OAEG;IACG,uBAAuB,CAC3B,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;IAgBhC;;OAEG;IACG,aAAa,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC;CAG9D"} \ No newline at end of file diff --git a/packages/core/dist/services/MessageService.js b/packages/core/dist/services/MessageService.js new file mode 100644 index 0000000..a30e1c4 --- /dev/null +++ b/packages/core/dist/services/MessageService.js @@ -0,0 +1,78 @@ +import messageManager from '../waku'; +export class MessageService { + constructor(delegationManager) { + this.delegationManager = delegationManager; + } + /** + * Sign and send a message to the Waku network + */ + async sendMessage(message) { + try { + const signedMessage = await this.delegationManager.signMessage(message); + if (!signedMessage) { + // Check if delegation exists but is expired + const delegationStatus = await this.delegationManager.getStatus(); + const isDelegationExpired = !delegationStatus.isValid; + return { + success: false, + error: isDelegationExpired + ? 'Key delegation expired. Please re-delegate your key through the profile menu.' + : 'Key delegation required. Please delegate a signing key from your profile menu to post without wallet approval for each action.', + }; + } + await messageManager.sendMessage(signedMessage); + return { + success: true, + message: signedMessage, + }; + } + catch (error) { + console.error('Error signing and sending message:', error); + let errorMessage = 'Failed to sign and send message. Please try again.'; + if (error instanceof Error) { + if (error.message.includes('timeout') || + error.message.includes('network')) { + errorMessage = + 'Network issue detected. Please check your connection and try again.'; + } + else if (error.message.includes('rejected') || + error.message.includes('denied')) { + errorMessage = + 'Wallet signature request was rejected. Please approve signing to continue.'; + } + else { + errorMessage = error.message; + } + } + return { + success: false, + error: errorMessage, + }; + } + } + /** + * Sign and broadcast a message (simplified version for profile updates) + */ + async signAndBroadcastMessage(message) { + try { + const signedMessage = await this.delegationManager.signMessage(message); + if (!signedMessage) { + console.error('Failed to sign message'); + return null; + } + await messageManager.sendMessage(signedMessage); + return signedMessage; + } + catch (error) { + console.error('Error signing and broadcasting message:', error); + return null; + } + } + /** + * Verify a message signature + */ + async verifyMessage(message) { + return await this.delegationManager.verify(message); + } +} +//# sourceMappingURL=MessageService.js.map \ No newline at end of file diff --git a/packages/core/dist/services/MessageService.js.map b/packages/core/dist/services/MessageService.js.map new file mode 100644 index 0000000..4b2dab7 --- /dev/null +++ b/packages/core/dist/services/MessageService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MessageService.js","sourceRoot":"","sources":["../../src/services/MessageService.ts"],"names":[],"mappings":"AAGA,OAAO,cAAc,MAAM,SAAS,CAAC;AAgBrC,MAAM,OAAO,cAAc;IAGzB,YAAY,iBAAoC;QAC9C,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;IAC7C,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,WAAW,CAAC,OAAwB;QACxC,IAAI,CAAC;YACH,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YAExE,IAAI,CAAC,aAAa,EAAE,CAAC;gBACnB,4CAA4C;gBAC5C,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,SAAS,EAAE,CAAC;gBAClE,MAAM,mBAAmB,GAAG,CAAC,gBAAgB,CAAC,OAAO,CAAC;gBAEtD,OAAO;oBACL,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,mBAAmB;wBACxB,CAAC,CAAC,+EAA+E;wBACjF,CAAC,CAAC,gIAAgI;iBACrI,CAAC;YACJ,CAAC;YAED,MAAM,cAAc,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;YAEhD,OAAO;gBACL,OAAO,EAAE,IAAI;gBACb,OAAO,EAAE,aAAa;aACvB,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;YAE3D,IAAI,YAAY,GAAG,oDAAoD,CAAC;YAExE,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;gBAC3B,IACE,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC;oBACjC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EACjC,CAAC;oBACD,YAAY;wBACV,qEAAqE,CAAC;gBAC1E,CAAC;qBAAM,IACL,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC;oBAClC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAChC,CAAC;oBACD,YAAY;wBACV,4EAA4E,CAAC;gBACjF,CAAC;qBAAM,CAAC;oBACN,YAAY,GAAG,KAAK,CAAC,OAAO,CAAC;gBAC/B,CAAC;YACH,CAAC;YAED,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,YAAY;aACpB,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,uBAAuB,CAC3B,OAAwB;QAExB,IAAI,CAAC;YACH,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YACxE,IAAI,CAAC,aAAa,EAAE,CAAC;gBACnB,OAAO,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC;gBACxC,OAAO,IAAI,CAAC;YACd,CAAC;YAED,MAAM,cAAc,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;YAChD,OAAO,aAAa,CAAC;QACvB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,yCAAyC,EAAE,KAAK,CAAC,CAAC;YAChE,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa,CAAC,OAAsB;QACxC,OAAO,MAAM,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACtD,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/services/Ordinal/index.d.ts b/packages/core/dist/services/Ordinal/index.d.ts new file mode 100644 index 0000000..a067bff --- /dev/null +++ b/packages/core/dist/services/Ordinal/index.d.ts @@ -0,0 +1,10 @@ +import { OrdinalApiResponse } from './types'; +export declare class OrdinalAPI { + /** + * Fetches Ordinal operator details for a given Bitcoin address. + * @param address - The Bitcoin address to query. + * @returns A promise that resolves with the API response. + */ + getOperatorDetails(address: string): Promise; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/services/Ordinal/index.d.ts.map b/packages/core/dist/services/Ordinal/index.d.ts.map new file mode 100644 index 0000000..4e3c1f2 --- /dev/null +++ b/packages/core/dist/services/Ordinal/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/services/Ordinal/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAI7C,qBAAa,UAAU;IACrB;;;;OAIG;IACG,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC;CA2CvE"} \ No newline at end of file diff --git a/packages/core/dist/services/Ordinal/index.js b/packages/core/dist/services/Ordinal/index.js new file mode 100644 index 0000000..530212e --- /dev/null +++ b/packages/core/dist/services/Ordinal/index.js @@ -0,0 +1,39 @@ +const BASE_URL = 'https://dashboard.logos.co/api/operators/wallet'; +export class OrdinalAPI { + /** + * Fetches Ordinal operator details for a given Bitcoin address. + * @param address - The Bitcoin address to query. + * @returns A promise that resolves with the API response. + */ + async getOperatorDetails(address) { + if (process.env.VITE_OPCHAN_MOCK_ORDINAL_CHECK === 'true') { + console.log(`[DEV] Bypassing ordinal verification for address: ${address}`); + return { + has_operators: true, + error_message: '', + data: [], + }; + } + const url = `${BASE_URL}/${address}/detail/`; + try { + const response = await fetch(url, { + method: 'GET', + headers: { Accept: 'application/json' }, + }); + if (!response.ok) { + const errorBody = await response.text().catch(() => ''); + throw new Error(`HTTP error! status: ${response.status}, message: ${errorBody || response.statusText}`); + } + const data = await response.json(); + if (data.error_message) { + console.warn(`API returned an error message for address ${address}: ${data.error_message}`); + } + return data; + } + catch (error) { + console.error(`Failed to fetch ordinal details for address ${address}:`, error); + throw error; + } + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/core/dist/services/Ordinal/index.js.map b/packages/core/dist/services/Ordinal/index.js.map new file mode 100644 index 0000000..4c08127 --- /dev/null +++ b/packages/core/dist/services/Ordinal/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/services/Ordinal/index.ts"],"names":[],"mappings":"AAEA,MAAM,QAAQ,GAAG,iDAAiD,CAAC;AAEnE,MAAM,OAAO,UAAU;IACrB;;;;OAIG;IACH,KAAK,CAAC,kBAAkB,CAAC,OAAe;QACtC,IAAI,OAAO,CAAC,GAAG,CAAC,8BAA8B,KAAK,MAAM,EAAE,CAAC;YAC1D,OAAO,CAAC,GAAG,CACT,qDAAqD,OAAO,EAAE,CAC/D,CAAC;YACF,OAAO;gBACL,aAAa,EAAE,IAAI;gBACnB,aAAa,EAAE,EAAE;gBACjB,IAAI,EAAE,EAAE;aACT,CAAC;QACJ,CAAC;QAED,MAAM,GAAG,GAAG,GAAG,QAAQ,IAAI,OAAO,UAAU,CAAC;QAE7C,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;gBAChC,MAAM,EAAE,KAAK;gBACb,OAAO,EAAE,EAAE,MAAM,EAAE,kBAAkB,EAAE;aACxC,CAAC,CAAC;YAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;gBACjB,MAAM,SAAS,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;gBACxD,MAAM,IAAI,KAAK,CACb,uBAAuB,QAAQ,CAAC,MAAM,cAAc,SAAS,IAAI,QAAQ,CAAC,UAAU,EAAE,CACvF,CAAC;YACJ,CAAC;YAED,MAAM,IAAI,GAAuB,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;YAEvD,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;gBACvB,OAAO,CAAC,IAAI,CACV,6CAA6C,OAAO,KAAK,IAAI,CAAC,aAAa,EAAE,CAC9E,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CACX,+CAA+C,OAAO,GAAG,EACzD,KAAK,CACN,CAAC;YACF,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/services/Ordinal/types.d.ts b/packages/core/dist/services/Ordinal/types.d.ts new file mode 100644 index 0000000..58bfbc2 --- /dev/null +++ b/packages/core/dist/services/Ordinal/types.d.ts @@ -0,0 +1,25 @@ +export interface OrdinalDetail { + name: string; + archetype_name: string; + comp: string; + background: string; + skin: string; + helmet: string; + jacket: string; + image_200_url: string; + image_200_jpeg_url: string; + image_400_url: string; + image_400_jpeg_url: string; + image_1024_url: string; + image_1024_jpeg_url: string; + image_2048_url: string; + image_2048_jpeg_url: string; + image_pixalated_url: string; + mp4_url: string; +} +export interface OrdinalApiResponse { + has_operators: boolean; + error_message: string; + data: OrdinalDetail[]; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/services/Ordinal/types.d.ts.map b/packages/core/dist/services/Ordinal/types.d.ts.map new file mode 100644 index 0000000..8c49f0b --- /dev/null +++ b/packages/core/dist/services/Ordinal/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/services/Ordinal/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,aAAa,EAAE,MAAM,CAAC;IACtB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,cAAc,EAAE,MAAM,CAAC;IACvB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,cAAc,EAAE,MAAM,CAAC;IACvB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,OAAO,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,IAAI,EAAE,aAAa,EAAE,CAAC;CACvB"} \ No newline at end of file diff --git a/packages/core/dist/services/Ordinal/types.js b/packages/core/dist/services/Ordinal/types.js new file mode 100644 index 0000000..718fd38 --- /dev/null +++ b/packages/core/dist/services/Ordinal/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/packages/core/dist/services/Ordinal/types.js.map b/packages/core/dist/services/Ordinal/types.js.map new file mode 100644 index 0000000..1c15fc6 --- /dev/null +++ b/packages/core/dist/services/Ordinal/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/services/Ordinal/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/core/dist/services/UserIdentityService.d.ts b/packages/core/dist/services/UserIdentityService.d.ts new file mode 100644 index 0000000..c478d79 --- /dev/null +++ b/packages/core/dist/services/UserIdentityService.d.ts @@ -0,0 +1,74 @@ +import { EVerificationStatus, EDisplayPreference } from '../types/identity'; +import { UserProfileUpdateMessage } from '../types/waku'; +import { MessageService } from './MessageService'; +export interface UserIdentity { + address: string; + ensName?: string; + ordinalDetails?: { + ordinalId: string; + ordinalDetails: string; + }; + callSign?: string; + displayPreference: EDisplayPreference; + lastUpdated: number; + verificationStatus: EVerificationStatus; +} +export declare class UserIdentityService { + private messageService; + private userIdentityCache; + private refreshListeners; + constructor(messageService: MessageService); + /** + * Get user identity from cache or resolve from sources + */ + getUserIdentity(address: string): Promise; + /** + * Get all cached user identities + */ + getAllUserIdentities(): UserIdentity[]; + /** + * Update user profile via Waku message + */ + updateUserProfile(address: string, callSign: string | undefined, displayPreference: EDisplayPreference): Promise; + /** + * Resolve user identity from various sources + */ + private resolveUserIdentity; + /** + * Resolve ENS name from Ethereum address + */ + private resolveENSName; + /** + * Resolve Ordinal details from Bitcoin address + */ + private resolveOrdinalDetails; + /** + * Update user identity from Waku message + */ + updateUserIdentityFromMessage(message: UserProfileUpdateMessage): void; + /** + * Map verification status string to enum + */ + private mapVerificationStatus; + /** + * Refresh user identity (force re-resolution) + */ + refreshUserIdentity(address: string): Promise; + /** + * Clear user identity cache + */ + clearUserIdentityCache(): void; + /** + * Add a refresh listener for when user identity data changes + */ + addRefreshListener(listener: (address: string) => void): () => void; + /** + * Notify all listeners that user identity data has changed + */ + private notifyRefreshListeners; + /** + * Get display name for user based on their preferences + */ + getDisplayName(address: string): string; +} +//# sourceMappingURL=UserIdentityService.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/services/UserIdentityService.d.ts.map b/packages/core/dist/services/UserIdentityService.d.ts.map new file mode 100644 index 0000000..9d267a2 --- /dev/null +++ b/packages/core/dist/services/UserIdentityService.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"UserIdentityService.d.ts","sourceRoot":"","sources":["../../src/services/UserIdentityService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAEL,wBAAwB,EAGzB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAIlD,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE;QACf,SAAS,EAAE,MAAM,CAAC;QAClB,cAAc,EAAE,MAAM,CAAC;KACxB,CAAC;IACF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iBAAiB,EAAE,kBAAkB,CAAC;IACtC,WAAW,EAAE,MAAM,CAAC;IACpB,kBAAkB,EAAE,mBAAmB,CAAC;CACzC;AAED,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,iBAAiB,CAAyB;IAClD,OAAO,CAAC,gBAAgB,CAA6C;gBAEzD,cAAc,EAAE,cAAc;IAI1C;;OAEG;IACG,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAyHpE;;OAEG;IACH,oBAAoB,IAAI,YAAY,EAAE;IAYtC;;OAEG;IACG,iBAAiB,CACrB,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,iBAAiB,EAAE,kBAAkB,GACpC,OAAO,CAAC,OAAO,CAAC;IAmFnB;;OAEG;YACW,mBAAmB;IAmCjC;;OAEG;YACW,cAAc;IAqB5B;;OAEG;YACW,qBAAqB;IAanC;;OAEG;IACH,6BAA6B,CAAC,OAAO,EAAE,wBAAwB,GAAG,IAAI;IA6BtE;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAa7B;;OAEG;IACG,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKzD;;OAEG;IACH,sBAAsB,IAAI,IAAI;IAI9B;;OAEG;IACH,kBAAkB,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAAG,MAAM,IAAI;IAKnE;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAI9B;;OAEG;IACH,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM;CAmBxC"} \ No newline at end of file diff --git a/packages/core/dist/services/UserIdentityService.js b/packages/core/dist/services/UserIdentityService.js new file mode 100644 index 0000000..e7245e9 --- /dev/null +++ b/packages/core/dist/services/UserIdentityService.js @@ -0,0 +1,354 @@ +import { EVerificationStatus, EDisplayPreference } from '../types/identity'; +import { MessageType, } from '../types/waku'; +import messageManager from '../waku'; +import { localDatabase } from '../database/LocalDatabase'; +export class UserIdentityService { + constructor(messageService) { + this.userIdentityCache = {}; + this.refreshListeners = new Set(); + this.messageService = messageService; + } + /** + * Get user identity from cache or resolve from sources + */ + async getUserIdentity(address) { + // Check internal cache first + if (this.userIdentityCache[address]) { + const cached = this.userIdentityCache[address]; + if (process.env.NODE_ENV === 'development') { + console.debug('UserIdentityService: cache hit (internal)'); + } + // Enrich with ENS name if missing and ETH address + if (!cached.ensName && address.startsWith('0x')) { + const ensName = await this.resolveENSName(address); + if (ensName) { + cached.ensName = ensName; + } + } + return { + address, + ensName: cached.ensName, + ordinalDetails: cached.ordinalDetails, + callSign: cached.callSign, + displayPreference: cached.displayPreference, + lastUpdated: cached.lastUpdated, + verificationStatus: this.mapVerificationStatus(cached.verificationStatus), + }; + } + // Check LocalDatabase first for persisted identities (warm start) + const persisted = localDatabase.cache.userIdentities[address]; + if (persisted) { + this.userIdentityCache[address] = { + ensName: persisted.ensName, + ordinalDetails: persisted.ordinalDetails, + callSign: persisted.callSign, + displayPreference: persisted.displayPreference, + lastUpdated: persisted.lastUpdated, + verificationStatus: persisted.verificationStatus, + }; + const result = { + address, + ensName: persisted.ensName, + ordinalDetails: persisted.ordinalDetails, + callSign: persisted.callSign, + displayPreference: persisted.displayPreference, + lastUpdated: persisted.lastUpdated, + verificationStatus: this.mapVerificationStatus(persisted.verificationStatus), + }; + // Enrich with ENS name if missing and ETH address + if (!result.ensName && address.startsWith('0x')) { + const ensName = await this.resolveENSName(address); + if (ensName) { + result.ensName = ensName; + this.userIdentityCache[address].ensName = ensName; + } + } + return result; + } + // Fallback: Check Waku message cache + const cacheServiceData = messageManager.messageCache.userIdentities[address]; + if (cacheServiceData) { + if (process.env.NODE_ENV === 'development') { + console.debug('UserIdentityService: cache hit (message cache)'); + } + // Store in internal cache for future use + this.userIdentityCache[address] = { + ensName: cacheServiceData.ensName, + ordinalDetails: cacheServiceData.ordinalDetails, + callSign: cacheServiceData.callSign, + displayPreference: cacheServiceData.displayPreference, + lastUpdated: cacheServiceData.lastUpdated, + verificationStatus: cacheServiceData.verificationStatus, + }; + const result = { + address, + ensName: cacheServiceData.ensName, + ordinalDetails: cacheServiceData.ordinalDetails, + callSign: cacheServiceData.callSign, + displayPreference: cacheServiceData.displayPreference, + lastUpdated: cacheServiceData.lastUpdated, + verificationStatus: this.mapVerificationStatus(cacheServiceData.verificationStatus), + }; + // Enrich with ENS name if missing and ETH address + if (!result.ensName && address.startsWith('0x')) { + const ensName = await this.resolveENSName(address); + if (ensName) { + result.ensName = ensName; + this.userIdentityCache[address].ensName = ensName; + } + } + return result; + } + if (process.env.NODE_ENV === 'development') { + console.debug('UserIdentityService: cache miss, resolving'); + } + // Try to resolve identity from various sources + const identity = await this.resolveUserIdentity(address); + if (identity) { + this.userIdentityCache[address] = { + ensName: identity.ensName, + ordinalDetails: identity.ordinalDetails, + callSign: identity.callSign, + displayPreference: identity.displayPreference, + lastUpdated: identity.lastUpdated, + verificationStatus: identity.verificationStatus, + }; + } + return identity; + } + /** + * Get all cached user identities + */ + getAllUserIdentities() { + return Object.entries(this.userIdentityCache).map(([address, cached]) => ({ + address, + ensName: cached.ensName, + ordinalDetails: cached.ordinalDetails, + callSign: cached.callSign, + displayPreference: cached.displayPreference, + lastUpdated: cached.lastUpdated, + verificationStatus: this.mapVerificationStatus(cached.verificationStatus), + })); + } + /** + * Update user profile via Waku message + */ + async updateUserProfile(address, callSign, displayPreference) { + try { + if (process.env.NODE_ENV === 'development') { + console.debug('UserIdentityService: updating profile', { address }); + } + const timestamp = Date.now(); + const unsignedMessage = { + id: crypto.randomUUID(), + type: MessageType.USER_PROFILE_UPDATE, + timestamp, + author: address, + displayPreference, + }; + // Only include callSign if provided and non-empty + if (callSign && callSign.trim()) { + unsignedMessage.callSign = callSign.trim(); + } + if (process.env.NODE_ENV === 'development') { + console.debug('UserIdentityService: created unsigned message'); + } + const signedMessage = await this.messageService.signAndBroadcastMessage(unsignedMessage); + if (process.env.NODE_ENV === 'development') { + console.debug('UserIdentityService: message broadcast result', !!signedMessage); + } + // If broadcast was successful, immediately update local cache + if (signedMessage) { + this.updateUserIdentityFromMessage(signedMessage); + // Also update the local database cache immediately + if (this.userIdentityCache[address]) { + const updatedIdentity = { + ...this.userIdentityCache[address], + callSign: callSign && callSign.trim() + ? callSign.trim() + : this.userIdentityCache[address].callSign, + displayPreference, + lastUpdated: timestamp, + }; + localDatabase.cache.userIdentities[address] = updatedIdentity; + // Persist to IndexedDB using the storeMessage method + const profileMessage = { + id: unsignedMessage.id, + type: MessageType.USER_PROFILE_UPDATE, + timestamp, + author: address, + displayPreference, + signature: signedMessage.signature, + browserPubKey: signedMessage.browserPubKey, + delegationProof: signedMessage.delegationProof, + }; + if (callSign && callSign.trim()) { + profileMessage.callSign = callSign.trim(); + } + // Apply the message to update the database + await localDatabase.applyMessage(profileMessage); + // Notify listeners that the user identity has been updated + this.notifyRefreshListeners(address); + } + } + return !!signedMessage; + } + catch (error) { + console.error('Failed to update user profile:', error); + return false; + } + } + /** + * Resolve user identity from various sources + */ + async resolveUserIdentity(address) { + try { + const [ensName, ordinalDetails] = await Promise.all([ + this.resolveENSName(address), + this.resolveOrdinalDetails(address), + ]); + // Default to wallet address display preference + const defaultDisplayPreference = EDisplayPreference.WALLET_ADDRESS; + // Default verification status based on what we can resolve + let verificationStatus = EVerificationStatus.WALLET_UNCONNECTED; + if (ensName || ordinalDetails) { + verificationStatus = EVerificationStatus.ENS_ORDINAL_VERIFIED; + } + return { + address, + ensName: ensName || undefined, + ordinalDetails: ordinalDetails || undefined, + callSign: undefined, // Will be populated from Waku messages + displayPreference: defaultDisplayPreference, + lastUpdated: Date.now(), + verificationStatus, + }; + } + catch (error) { + console.error('Failed to resolve user identity:', error); + return null; + } + } + /** + * Resolve ENS name from Ethereum address + */ + async resolveENSName(address) { + if (!address.startsWith('0x')) { + return null; // Not an Ethereum address + } + try { + // Import the ENS resolver from wagmi + const { getEnsName } = await import('@wagmi/core'); + const { config } = await import('../wallet/config'); + const ensName = await getEnsName(config, { + address: address, + }); + return ensName || null; + } + catch (error) { + console.error('Failed to resolve ENS name:', error); + return null; + } + } + /** + * Resolve Ordinal details from Bitcoin address + */ + async resolveOrdinalDetails(address) { + try { + //TODO: add Ordinal API call + console.log('resolveOrdinalDetails', address); + return null; + } + catch (error) { + console.error('Failed to resolve Ordinal details:', error); + return null; + } + } + /** + * Update user identity from Waku message + */ + updateUserIdentityFromMessage(message) { + const { author, callSign, displayPreference, timestamp } = message; + if (!this.userIdentityCache[author]) { + // Create new identity entry if it doesn't exist + this.userIdentityCache[author] = { + ensName: undefined, + ordinalDetails: undefined, + callSign: undefined, + displayPreference, + lastUpdated: timestamp, + verificationStatus: EVerificationStatus.WALLET_UNCONNECTED, + }; + } + // Update only if this message is newer + if (timestamp > this.userIdentityCache[author].lastUpdated) { + this.userIdentityCache[author] = { + ...this.userIdentityCache[author], + callSign, + displayPreference, + lastUpdated: timestamp, + }; + // Notify listeners that the user identity has been updated + this.notifyRefreshListeners(author); + } + } + /** + * Map verification status string to enum + */ + mapVerificationStatus(status) { + switch (status) { + case 'verified-basic': + return EVerificationStatus.WALLET_CONNECTED; + case 'verified-owner': + return EVerificationStatus.ENS_ORDINAL_VERIFIED; + case 'verifying': + return EVerificationStatus.WALLET_CONNECTED; // Temporary state during verification + default: + return EVerificationStatus.WALLET_UNCONNECTED; + } + } + /** + * Refresh user identity (force re-resolution) + */ + async refreshUserIdentity(address) { + delete this.userIdentityCache[address]; + await this.getUserIdentity(address); + } + /** + * Clear user identity cache + */ + clearUserIdentityCache() { + this.userIdentityCache = {}; + } + /** + * Add a refresh listener for when user identity data changes + */ + addRefreshListener(listener) { + this.refreshListeners.add(listener); + return () => this.refreshListeners.delete(listener); + } + /** + * Notify all listeners that user identity data has changed + */ + notifyRefreshListeners(address) { + this.refreshListeners.forEach((listener) => listener(address)); + } + /** + * Get display name for user based on their preferences + */ + getDisplayName(address) { + const identity = this.userIdentityCache[address]; + if (!identity) { + return `${address.slice(0, 6)}...${address.slice(-4)}`; + } + if (identity.displayPreference === EDisplayPreference.CALL_SIGN && + identity.callSign) { + return identity.callSign; + } + if (identity.ensName) { + return identity.ensName; + } + return `${address.slice(0, 6)}...${address.slice(-4)}`; + } +} +//# sourceMappingURL=UserIdentityService.js.map \ No newline at end of file diff --git a/packages/core/dist/services/UserIdentityService.js.map b/packages/core/dist/services/UserIdentityService.js.map new file mode 100644 index 0000000..3ab579d --- /dev/null +++ b/packages/core/dist/services/UserIdentityService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"UserIdentityService.js","sourceRoot":"","sources":["../../src/services/UserIdentityService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAGL,WAAW,GAEZ,MAAM,eAAe,CAAC;AAEvB,OAAO,cAAc,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAe1D,MAAM,OAAO,mBAAmB;IAK9B,YAAY,cAA8B;QAHlC,sBAAiB,GAAsB,EAAE,CAAC;QAC1C,qBAAgB,GAAmC,IAAI,GAAG,EAAE,CAAC;QAGnE,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,eAAe,CAAC,OAAe;QACnC,6BAA6B;QAC7B,IAAI,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;YACpC,MAAM,MAAM,GAAG,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;YAC/C,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;gBAC3C,OAAO,CAAC,KAAK,CAAC,2CAA2C,CAAC,CAAC;YAC7D,CAAC;YACD,kDAAkD;YAClD,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;gBAChD,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;gBACnD,IAAI,OAAO,EAAE,CAAC;oBACZ,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC;gBAC3B,CAAC;YACH,CAAC;YACD,OAAO;gBACL,OAAO;gBACP,OAAO,EAAE,MAAM,CAAC,OAAO;gBACvB,cAAc,EAAE,MAAM,CAAC,cAAc;gBACrC,QAAQ,EAAE,MAAM,CAAC,QAAQ;gBACzB,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;gBAC3C,WAAW,EAAE,MAAM,CAAC,WAAW;gBAC/B,kBAAkB,EAAE,IAAI,CAAC,qBAAqB,CAC5C,MAAM,CAAC,kBAAkB,CAC1B;aACF,CAAC;QACJ,CAAC;QAED,kEAAkE;QAClE,MAAM,SAAS,GAAG,aAAa,CAAC,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;QAC9D,IAAI,SAAS,EAAE,CAAC;YACd,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,GAAG;gBAChC,OAAO,EAAE,SAAS,CAAC,OAAO;gBAC1B,cAAc,EAAE,SAAS,CAAC,cAAc;gBACxC,QAAQ,EAAE,SAAS,CAAC,QAAQ;gBAC5B,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;gBAC9C,WAAW,EAAE,SAAS,CAAC,WAAW;gBAClC,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;aACjD,CAAC;YACF,MAAM,MAAM,GAAG;gBACb,OAAO;gBACP,OAAO,EAAE,SAAS,CAAC,OAAO;gBAC1B,cAAc,EAAE,SAAS,CAAC,cAAc;gBACxC,QAAQ,EAAE,SAAS,CAAC,QAAQ;gBAC5B,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;gBAC9C,WAAW,EAAE,SAAS,CAAC,WAAW;gBAClC,kBAAkB,EAAE,IAAI,CAAC,qBAAqB,CAC5C,SAAS,CAAC,kBAAkB,CAC7B;aACc,CAAC;YAClB,kDAAkD;YAClD,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;gBAChD,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;gBACnD,IAAI,OAAO,EAAE,CAAC;oBACZ,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC;oBACzB,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,OAAO,GAAG,OAAO,CAAC;gBACpD,CAAC;YACH,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,qCAAqC;QACrC,MAAM,gBAAgB,GACpB,cAAc,CAAC,YAAY,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;QAEtD,IAAI,gBAAgB,EAAE,CAAC;YACrB,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;gBAC3C,OAAO,CAAC,KAAK,CAAC,gDAAgD,CAAC,CAAC;YAClE,CAAC;YAED,yCAAyC;YACzC,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,GAAG;gBAChC,OAAO,EAAE,gBAAgB,CAAC,OAAO;gBACjC,cAAc,EAAE,gBAAgB,CAAC,cAAc;gBAC/C,QAAQ,EAAE,gBAAgB,CAAC,QAAQ;gBACnC,iBAAiB,EAAE,gBAAgB,CAAC,iBAAiB;gBACrD,WAAW,EAAE,gBAAgB,CAAC,WAAW;gBACzC,kBAAkB,EAAE,gBAAgB,CAAC,kBAAkB;aACxD,CAAC;YAEF,MAAM,MAAM,GAAG;gBACb,OAAO;gBACP,OAAO,EAAE,gBAAgB,CAAC,OAAO;gBACjC,cAAc,EAAE,gBAAgB,CAAC,cAAc;gBAC/C,QAAQ,EAAE,gBAAgB,CAAC,QAAQ;gBACnC,iBAAiB,EAAE,gBAAgB,CAAC,iBAAiB;gBACrD,WAAW,EAAE,gBAAgB,CAAC,WAAW;gBACzC,kBAAkB,EAAE,IAAI,CAAC,qBAAqB,CAC5C,gBAAgB,CAAC,kBAAkB,CACpC;aACc,CAAC;YAClB,kDAAkD;YAClD,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;gBAChD,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;gBACnD,IAAI,OAAO,EAAE,CAAC;oBACZ,MAAM,CAAC,OAAO,GAAG,OAAO,CAAC;oBACzB,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,OAAO,GAAG,OAAO,CAAC;gBACpD,CAAC;YACH,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;YAC3C,OAAO,CAAC,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC9D,CAAC;QAED,+CAA+C;QAC/C,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC;QACzD,IAAI,QAAQ,EAAE,CAAC;YACb,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,GAAG;gBAChC,OAAO,EAAE,QAAQ,CAAC,OAAO;gBACzB,cAAc,EAAE,QAAQ,CAAC,cAAc;gBACvC,QAAQ,EAAE,QAAQ,CAAC,QAAQ;gBAC3B,iBAAiB,EAAE,QAAQ,CAAC,iBAAiB;gBAC7C,WAAW,EAAE,QAAQ,CAAC,WAAW;gBACjC,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;aAChD,CAAC;QACJ,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED;;OAEG;IACH,oBAAoB;QAClB,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC;YACxE,OAAO;YACP,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,cAAc,EAAE,MAAM,CAAC,cAAc;YACrC,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;YAC3C,WAAW,EAAE,MAAM,CAAC,WAAW;YAC/B,kBAAkB,EAAE,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,kBAAkB,CAAC;SAC1E,CAAC,CAAC,CAAC;IACN,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,iBAAiB,CACrB,OAAe,EACf,QAA4B,EAC5B,iBAAqC;QAErC,IAAI,CAAC;YACH,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;gBAC3C,OAAO,CAAC,KAAK,CAAC,uCAAuC,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;YACtE,CAAC;YAED,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;YAC7B,MAAM,eAAe,GAAqC;gBACxD,EAAE,EAAE,MAAM,CAAC,UAAU,EAAE;gBACvB,IAAI,EAAE,WAAW,CAAC,mBAAmB;gBACrC,SAAS;gBACT,MAAM,EAAE,OAAO;gBACf,iBAAiB;aAClB,CAAC;YACF,kDAAkD;YAClD,IAAI,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC;gBAChC,eAAe,CAAC,QAAQ,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;YAC7C,CAAC;YAED,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;gBAC3C,OAAO,CAAC,KAAK,CAAC,+CAA+C,CAAC,CAAC;YACjE,CAAC;YAED,MAAM,aAAa,GACjB,MAAM,IAAI,CAAC,cAAc,CAAC,uBAAuB,CAAC,eAAe,CAAC,CAAC;YAErE,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;gBAC3C,OAAO,CAAC,KAAK,CACX,+CAA+C,EAC/C,CAAC,CAAC,aAAa,CAChB,CAAC;YACJ,CAAC;YAED,8DAA8D;YAC9D,IAAI,aAAa,EAAE,CAAC;gBAClB,IAAI,CAAC,6BAA6B,CAChC,aAAyC,CAC1C,CAAC;gBAEF,mDAAmD;gBACnD,IAAI,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;oBACpC,MAAM,eAAe,GAAG;wBACtB,GAAG,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC;wBAClC,QAAQ,EACN,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE;4BACzB,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE;4BACjB,CAAC,CAAC,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,QAAQ;wBAC9C,iBAAiB;wBACjB,WAAW,EAAE,SAAS;qBACvB,CAAC;oBAEF,aAAa,CAAC,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,GAAG,eAAe,CAAC;oBAE9D,qDAAqD;oBACrD,MAAM,cAAc,GAA6B;wBAC/C,EAAE,EAAE,eAAe,CAAC,EAAE;wBACtB,IAAI,EAAE,WAAW,CAAC,mBAAmB;wBACrC,SAAS;wBACT,MAAM,EAAE,OAAO;wBACf,iBAAiB;wBACjB,SAAS,EAAE,aAAa,CAAC,SAAS;wBAClC,aAAa,EAAE,aAAa,CAAC,aAAa;wBAC1C,eAAe,EAAE,aAAa,CAAC,eAAe;qBAC/C,CAAC;oBACF,IAAI,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC;wBAChC,cAAc,CAAC,QAAQ,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;oBAC5C,CAAC;oBAED,2CAA2C;oBAC3C,MAAM,aAAa,CAAC,YAAY,CAAC,cAAc,CAAC,CAAC;oBAEjD,2DAA2D;oBAC3D,IAAI,CAAC,sBAAsB,CAAC,OAAO,CAAC,CAAC;gBACvC,CAAC;YACH,CAAC;YAED,OAAO,CAAC,CAAC,aAAa,CAAC;QACzB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;YACvD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,mBAAmB,CAC/B,OAAe;QAEf,IAAI,CAAC;YACH,MAAM,CAAC,OAAO,EAAE,cAAc,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;gBAClD,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC;gBAC5B,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC;aACpC,CAAC,CAAC;YAEH,+CAA+C;YAC/C,MAAM,wBAAwB,GAC5B,kBAAkB,CAAC,cAAc,CAAC;YAEpC,2DAA2D;YAC3D,IAAI,kBAAkB,GACpB,mBAAmB,CAAC,kBAAkB,CAAC;YACzC,IAAI,OAAO,IAAI,cAAc,EAAE,CAAC;gBAC9B,kBAAkB,GAAG,mBAAmB,CAAC,oBAAoB,CAAC;YAChE,CAAC;YAED,OAAO;gBACL,OAAO;gBACP,OAAO,EAAE,OAAO,IAAI,SAAS;gBAC7B,cAAc,EAAE,cAAc,IAAI,SAAS;gBAC3C,QAAQ,EAAE,SAAS,EAAE,uCAAuC;gBAC5D,iBAAiB,EAAE,wBAAwB;gBAC3C,WAAW,EAAE,IAAI,CAAC,GAAG,EAAE;gBACvB,kBAAkB;aACnB,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,cAAc,CAAC,OAAe;QAC1C,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;YAC9B,OAAO,IAAI,CAAC,CAAC,0BAA0B;QACzC,CAAC;QAED,IAAI,CAAC;YACH,qCAAqC;YACrC,MAAM,EAAE,UAAU,EAAE,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC;YACnD,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,kBAAkB,CAAC,CAAC;YAEpD,MAAM,OAAO,GAAG,MAAM,UAAU,CAAC,MAAM,EAAE;gBACvC,OAAO,EAAE,OAAwB;aAClC,CAAC,CAAC;YAEH,OAAO,OAAO,IAAI,IAAI,CAAC;QACzB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,6BAA6B,EAAE,KAAK,CAAC,CAAC;YACpD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,qBAAqB,CACjC,OAAe;QAEf,IAAI,CAAC;YACH,4BAA4B;YAC5B,OAAO,CAAC,GAAG,CAAC,uBAAuB,EAAE,OAAO,CAAC,CAAC;YAC9C,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;YAC3D,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACH,6BAA6B,CAAC,OAAiC;QAC7D,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,iBAAiB,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;QAEnE,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;YACpC,gDAAgD;YAChD,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,GAAG;gBAC/B,OAAO,EAAE,SAAS;gBAClB,cAAc,EAAE,SAAS;gBACzB,QAAQ,EAAE,SAAS;gBACnB,iBAAiB;gBACjB,WAAW,EAAE,SAAS;gBACtB,kBAAkB,EAAE,mBAAmB,CAAC,kBAAkB;aAC3D,CAAC;QACJ,CAAC;QAED,uCAAuC;QACvC,IAAI,SAAS,GAAG,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC;YAC3D,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,GAAG;gBAC/B,GAAG,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC;gBACjC,QAAQ;gBACR,iBAAiB;gBACjB,WAAW,EAAE,SAAS;aACvB,CAAC;YAEF,2DAA2D;YAC3D,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IAED;;OAEG;IACK,qBAAqB,CAAC,MAAc;QAC1C,QAAQ,MAAM,EAAE,CAAC;YACf,KAAK,gBAAgB;gBACnB,OAAO,mBAAmB,CAAC,gBAAgB,CAAC;YAC9C,KAAK,gBAAgB;gBACnB,OAAO,mBAAmB,CAAC,oBAAoB,CAAC;YAClD,KAAK,WAAW;gBACd,OAAO,mBAAmB,CAAC,gBAAgB,CAAC,CAAC,sCAAsC;YACrF;gBACE,OAAO,mBAAmB,CAAC,kBAAkB,CAAC;QAClD,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,mBAAmB,CAAC,OAAe;QACvC,OAAO,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QACvC,MAAM,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;IACtC,CAAC;IAED;;OAEG;IACH,sBAAsB;QACpB,IAAI,CAAC,iBAAiB,GAAG,EAAE,CAAC;IAC9B,CAAC;IAED;;OAEG;IACH,kBAAkB,CAAC,QAAmC;QACpD,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACpC,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACtD,CAAC;IAED;;OAEG;IACK,sBAAsB,CAAC,OAAe;QAC5C,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC;IACjE,CAAC;IAED;;OAEG;IACH,cAAc,CAAC,OAAe;QAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QACjD,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACzD,CAAC;QAED,IACE,QAAQ,CAAC,iBAAiB,KAAK,kBAAkB,CAAC,SAAS;YAC3D,QAAQ,CAAC,QAAQ,EACjB,CAAC;YACD,OAAO,QAAQ,CAAC,QAAQ,CAAC;QAC3B,CAAC;QAED,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;YACrB,OAAO,QAAQ,CAAC,OAAO,CAAC;QAC1B,CAAC;QAED,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACzD,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/services/index.d.ts b/packages/core/dist/services/index.d.ts new file mode 100644 index 0000000..117bb61 --- /dev/null +++ b/packages/core/dist/services/index.d.ts @@ -0,0 +1,2 @@ +export { MessageService, type MessageServiceInterface } from './MessageService'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/services/index.d.ts.map b/packages/core/dist/services/index.d.ts.map new file mode 100644 index 0000000..13c0c84 --- /dev/null +++ b/packages/core/dist/services/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/services/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,KAAK,uBAAuB,EAAE,MAAM,kBAAkB,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/services/index.js b/packages/core/dist/services/index.js new file mode 100644 index 0000000..24fa728 --- /dev/null +++ b/packages/core/dist/services/index.js @@ -0,0 +1,2 @@ +export { MessageService } from './MessageService'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/core/dist/services/index.js.map b/packages/core/dist/services/index.js.map new file mode 100644 index 0000000..85106d5 --- /dev/null +++ b/packages/core/dist/services/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/services/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAgC,MAAM,kBAAkB,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/types/browser.d.ts b/packages/core/dist/types/browser.d.ts new file mode 100644 index 0000000..8a25015 --- /dev/null +++ b/packages/core/dist/types/browser.d.ts @@ -0,0 +1,53 @@ +export interface Cell { + id: string; + name: string; + description?: string; + createdAt: number; + author: string; +} +export interface Post { + id: string; + cellId: string; + title: string; + content: string; + author: string; + createdAt: number; + updatedAt?: number; +} +export interface Comment { + id: string; + postId: string; + content: string; + author: string; + createdAt: number; + updatedAt?: number; +} +export interface User { + address: string; + ensName?: string; + callSign?: string; + displayPreference: 'ens' | 'callsign' | 'address'; + verificationStatus: 'unverified' | 'verified' | 'pending'; +} +export interface Bookmark { + id: string; + userId: string; + type: 'post' | 'comment' | 'cell'; + targetId: string; + createdAt: number; +} +export declare const STORE_NAMES: { + readonly CELLS: "cells"; + readonly POSTS: "posts"; + readonly COMMENTS: "comments"; + readonly VOTES: "votes"; + readonly MODERATIONS: "moderations"; + readonly USER_IDENTITIES: "userIdentities"; + readonly USER_AUTH: "userAuth"; + readonly DELEGATION: "delegation"; + readonly UI_STATE: "uiState"; + readonly META: "meta"; + readonly BOOKMARKS: "bookmarks"; +}; +export type StoreName = (typeof STORE_NAMES)[keyof typeof STORE_NAMES]; +//# sourceMappingURL=browser.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/types/browser.d.ts.map b/packages/core/dist/types/browser.d.ts.map new file mode 100644 index 0000000..da50410 --- /dev/null +++ b/packages/core/dist/types/browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../src/types/browser.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,IAAI;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,IAAI;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,IAAI;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iBAAiB,EAAE,KAAK,GAAG,UAAU,GAAG,SAAS,CAAC;IAClD,kBAAkB,EAAE,YAAY,GAAG,UAAU,GAAG,SAAS,CAAC;CAC3D;AAED,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAAC;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB;AAGD,eAAO,MAAM,WAAW;;;;;;;;;;;;CAYd,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,OAAO,WAAW,CAAC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/types/browser.js b/packages/core/dist/types/browser.js new file mode 100644 index 0000000..428bd8b --- /dev/null +++ b/packages/core/dist/types/browser.js @@ -0,0 +1,16 @@ +// Browser-compatible types for the core package +// IndexedDB store names +export const STORE_NAMES = { + CELLS: 'cells', + POSTS: 'posts', + COMMENTS: 'comments', + VOTES: 'votes', + MODERATIONS: 'moderations', + USER_IDENTITIES: 'userIdentities', + USER_AUTH: 'userAuth', + DELEGATION: 'delegation', + UI_STATE: 'uiState', + META: 'meta', + BOOKMARKS: 'bookmarks', +}; +//# sourceMappingURL=browser.js.map \ No newline at end of file diff --git a/packages/core/dist/types/browser.js.map b/packages/core/dist/types/browser.js.map new file mode 100644 index 0000000..9e70f71 --- /dev/null +++ b/packages/core/dist/types/browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.js","sourceRoot":"","sources":["../../src/types/browser.ts"],"names":[],"mappings":"AAAA,gDAAgD;AA6ChD,wBAAwB;AACxB,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,KAAK,EAAE,OAAO;IACd,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,UAAU;IACpB,KAAK,EAAE,OAAO;IACd,WAAW,EAAE,aAAa;IAC1B,eAAe,EAAE,gBAAgB;IACjC,SAAS,EAAE,UAAU;IACrB,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,SAAS;IACnB,IAAI,EAAE,MAAM;IACZ,SAAS,EAAE,WAAW;CACd,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/types/forum.d.ts b/packages/core/dist/types/forum.d.ts new file mode 100644 index 0000000..70ad324 --- /dev/null +++ b/packages/core/dist/types/forum.d.ts @@ -0,0 +1,133 @@ +import { CellMessage, CommentMessage, PostMessage, VoteMessage, ModerateMessage, UserProfileUpdateMessage } from './waku'; +import { EVerificationStatus } from './identity'; +import { DelegationProof } from '../delegation/types'; +/** + * Union type of all message types + * All messages MUST have valid signature and browserPubKey for authenticity + */ +export type OpchanMessage = (CellMessage | PostMessage | CommentMessage | VoteMessage | ModerateMessage | UserProfileUpdateMessage) & SignedMessage; +/** + * Partial message type for validation + */ +export interface PartialMessage { + type?: string; + author?: string; + timestamp?: number; + signature?: string; + browserPubKey?: string; + [key: string]: unknown; +} +/** + * Relevance score calculation details + */ +export interface RelevanceScoreDetails { + baseScore: number; + engagementScore: number; + authorVerificationBonus: number; + verifiedUpvoteBonus: number; + verifiedCommenterBonus: number; + timeDecayMultiplier: number; + moderationPenalty: number; + finalScore: number; + isVerified: boolean; + upvotes: number; + comments: number; + verifiedUpvotes: number; + verifiedCommenters: number; + daysOld: number; + isModerated: boolean; +} +/** + * Extended Cell with forum-specific fields + * Extends the base CellMessage with UI and business logic properties + */ +export interface Cell extends CellMessage { + relevanceScore?: number; + activeMemberCount?: number; + recentActivity?: number; + postCount?: number; + relevanceDetails?: RelevanceScoreDetails; +} +/** + * Extended Post with forum-specific fields + * Extends the base PostMessage with UI and business logic properties + */ +export interface Post extends PostMessage { + authorAddress: string; + upvotes: VoteMessage[]; + downvotes: VoteMessage[]; + moderated?: boolean; + moderatedBy?: string; + moderationReason?: string; + moderationTimestamp?: number; + relevanceScore?: number; + verifiedUpvotes?: number; + verifiedCommenters?: string[]; + relevanceDetails?: RelevanceScoreDetails; + voteScore?: number; +} +/** + * Extended Comment with forum-specific fields + * Extends the base CommentMessage with UI and business logic properties + */ +export interface Comment extends CommentMessage { + authorAddress: string; + upvotes: VoteMessage[]; + downvotes: VoteMessage[]; + moderated?: boolean; + moderatedBy?: string; + moderationReason?: string; + moderationTimestamp?: number; + relevanceScore?: number; + relevanceDetails?: RelevanceScoreDetails; + voteScore?: number; +} +/** + * Extended message types for verification + * These fields are now REQUIRED for all valid messages + */ +export interface SignedMessage { + signature: string; + browserPubKey: string; + delegationProof: DelegationProof; +} +/** + * User verification status mapping + */ +export interface UserVerificationStatus { + [address: string]: { + isVerified: boolean; + hasENS: boolean; + hasOrdinal: boolean; + ensName?: string; + verificationStatus?: EVerificationStatus; + }; +} +/** + * Bookmark types for posts and comments + */ +export declare enum BookmarkType { + POST = "post", + COMMENT = "comment" +} +/** + * Bookmark data structure + */ +export interface Bookmark { + id: string; + type: BookmarkType; + targetId: string; + userId: string; + createdAt: number; + title?: string; + author?: string; + cellId?: string; + postId?: string; +} +/** + * Bookmark cache for in-memory storage + */ +export interface BookmarkCache { + [bookmarkId: string]: Bookmark; +} +//# sourceMappingURL=forum.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/types/forum.d.ts.map b/packages/core/dist/types/forum.d.ts.map new file mode 100644 index 0000000..3355b33 --- /dev/null +++ b/packages/core/dist/types/forum.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"forum.d.ts","sourceRoot":"","sources":["../../src/types/forum.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,cAAc,EACd,WAAW,EACX,WAAW,EACX,eAAe,EACf,wBAAwB,EACzB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,CACxB,WAAW,GACX,WAAW,GACX,cAAc,GACd,WAAW,GACX,eAAe,GACf,wBAAwB,CAC3B,GACC,aAAa,CAAC;AAEhB;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,EAAE,MAAM,CAAC;IACxB,uBAAuB,EAAE,MAAM,CAAC;IAChC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,sBAAsB,EAAE,MAAM,CAAC;IAC/B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,OAAO,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,OAAO,CAAC;CACtB;AAED;;;GAGG;AACH,MAAM,WAAW,IAAK,SAAQ,WAAW;IACvC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,qBAAqB,CAAC;CAC1C;AAED;;;GAGG;AACH,MAAM,WAAW,IAAK,SAAQ,WAAW;IACvC,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,WAAW,EAAE,CAAC;IACvB,SAAS,EAAE,WAAW,EAAE,CAAC;IACzB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9B,gBAAgB,CAAC,EAAE,qBAAqB,CAAC;IACzC,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;GAGG;AACH,MAAM,WAAW,OAAQ,SAAQ,cAAc;IAC7C,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,WAAW,EAAE,CAAC;IACvB,SAAS,EAAE,WAAW,EAAE,CAAC;IACzB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,qBAAqB,CAAC;IACzC,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,eAAe,CAAC;CAClC;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC,CAAC,OAAO,EAAE,MAAM,GAAG;QACjB,UAAU,EAAE,OAAO,CAAC;QACpB,MAAM,EAAE,OAAO,CAAC;QAChB,UAAU,EAAE,OAAO,CAAC;QACpB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,kBAAkB,CAAC,EAAE,mBAAmB,CAAC;KAC1C,CAAC;CACH;AAED;;GAEG;AACH,oBAAY,YAAY;IACtB,IAAI,SAAS;IACb,OAAO,YAAY;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,YAAY,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAElB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,CAAC,UAAU,EAAE,MAAM,GAAG,QAAQ,CAAC;CAChC"} \ No newline at end of file diff --git a/packages/core/dist/types/forum.js b/packages/core/dist/types/forum.js new file mode 100644 index 0000000..3971cd9 --- /dev/null +++ b/packages/core/dist/types/forum.js @@ -0,0 +1,9 @@ +/** + * Bookmark types for posts and comments + */ +export var BookmarkType; +(function (BookmarkType) { + BookmarkType["POST"] = "post"; + BookmarkType["COMMENT"] = "comment"; +})(BookmarkType || (BookmarkType = {})); +//# sourceMappingURL=forum.js.map \ No newline at end of file diff --git a/packages/core/dist/types/forum.js.map b/packages/core/dist/types/forum.js.map new file mode 100644 index 0000000..d6b580b --- /dev/null +++ b/packages/core/dist/types/forum.js.map @@ -0,0 +1 @@ +{"version":3,"file":"forum.js","sourceRoot":"","sources":["../../src/types/forum.ts"],"names":[],"mappings":"AAiIA;;GAEG;AACH,MAAM,CAAN,IAAY,YAGX;AAHD,WAAY,YAAY;IACtB,6BAAa,CAAA;IACb,mCAAmB,CAAA;AACrB,CAAC,EAHW,YAAY,KAAZ,YAAY,QAGvB"} \ No newline at end of file diff --git a/packages/core/dist/types/identity.d.ts b/packages/core/dist/types/identity.d.ts new file mode 100644 index 0000000..1c00ee9 --- /dev/null +++ b/packages/core/dist/types/identity.d.ts @@ -0,0 +1,31 @@ +export type User = { + address: string; + walletType: 'bitcoin' | 'ethereum'; + ordinalDetails?: OrdinalDetails; + ensDetails?: EnsDetails; + callSign?: string; + displayPreference: EDisplayPreference; + verificationStatus: EVerificationStatus; + signature?: string; + lastChecked?: number; + browserPubKey?: string; + delegationSignature?: string; + delegationExpiry?: number; +}; +export declare enum EVerificationStatus { + WALLET_UNCONNECTED = "wallet-unconnected", + WALLET_CONNECTED = "wallet-connected", + ENS_ORDINAL_VERIFIED = "ens-ordinal-verified" +} +export interface OrdinalDetails { + ordinalId: string; + ordinalDetails: string; +} +export interface EnsDetails { + ensName: string; +} +export declare enum EDisplayPreference { + CALL_SIGN = "call-sign", + WALLET_ADDRESS = "wallet-address" +} +//# sourceMappingURL=identity.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/types/identity.d.ts.map b/packages/core/dist/types/identity.d.ts.map new file mode 100644 index 0000000..b62f996 --- /dev/null +++ b/packages/core/dist/types/identity.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../../src/types/identity.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,IAAI,GAAG;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,SAAS,GAAG,UAAU,CAAC;IAEnC,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC,UAAU,CAAC,EAAE,UAAU,CAAC;IAGxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iBAAiB,EAAE,kBAAkB,CAAC;IAEtC,kBAAkB,EAAE,mBAAmB,CAAC;IAExC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF,oBAAY,mBAAmB;IAC7B,kBAAkB,uBAAuB;IACzC,gBAAgB,qBAAqB;IACrC,oBAAoB,yBAAyB;CAC9C;AAED,MAAM,WAAW,cAAc;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,oBAAY,kBAAkB;IAC5B,SAAS,cAAc;IACvB,cAAc,mBAAmB;CAClC"} \ No newline at end of file diff --git a/packages/core/dist/types/identity.js b/packages/core/dist/types/identity.js new file mode 100644 index 0000000..310c681 --- /dev/null +++ b/packages/core/dist/types/identity.js @@ -0,0 +1,12 @@ +export var EVerificationStatus; +(function (EVerificationStatus) { + EVerificationStatus["WALLET_UNCONNECTED"] = "wallet-unconnected"; + EVerificationStatus["WALLET_CONNECTED"] = "wallet-connected"; + EVerificationStatus["ENS_ORDINAL_VERIFIED"] = "ens-ordinal-verified"; +})(EVerificationStatus || (EVerificationStatus = {})); +export var EDisplayPreference; +(function (EDisplayPreference) { + EDisplayPreference["CALL_SIGN"] = "call-sign"; + EDisplayPreference["WALLET_ADDRESS"] = "wallet-address"; +})(EDisplayPreference || (EDisplayPreference = {})); +//# sourceMappingURL=identity.js.map \ No newline at end of file diff --git a/packages/core/dist/types/identity.js.map b/packages/core/dist/types/identity.js.map new file mode 100644 index 0000000..9236625 --- /dev/null +++ b/packages/core/dist/types/identity.js.map @@ -0,0 +1 @@ +{"version":3,"file":"identity.js","sourceRoot":"","sources":["../../src/types/identity.ts"],"names":[],"mappings":"AAoBA,MAAM,CAAN,IAAY,mBAIX;AAJD,WAAY,mBAAmB;IAC7B,gEAAyC,CAAA;IACzC,4DAAqC,CAAA;IACrC,oEAA6C,CAAA;AAC/C,CAAC,EAJW,mBAAmB,KAAnB,mBAAmB,QAI9B;AAWD,MAAM,CAAN,IAAY,kBAGX;AAHD,WAAY,kBAAkB;IAC5B,6CAAuB,CAAA;IACvB,uDAAiC,CAAA;AACnC,CAAC,EAHW,kBAAkB,KAAlB,kBAAkB,QAG7B"} \ No newline at end of file diff --git a/packages/core/dist/types/index.d.ts b/packages/core/dist/types/index.d.ts new file mode 100644 index 0000000..dbd2739 --- /dev/null +++ b/packages/core/dist/types/index.d.ts @@ -0,0 +1,2 @@ +export * as forum from './forum'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/types/index.d.ts.map b/packages/core/dist/types/index.d.ts.map new file mode 100644 index 0000000..edd4f96 --- /dev/null +++ b/packages/core/dist/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/types/index.js b/packages/core/dist/types/index.js new file mode 100644 index 0000000..d264bc7 --- /dev/null +++ b/packages/core/dist/types/index.js @@ -0,0 +1,2 @@ +export * as forum from './forum'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/core/dist/types/index.js.map b/packages/core/dist/types/index.js.map new file mode 100644 index 0000000..e02426c --- /dev/null +++ b/packages/core/dist/types/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/types/waku.d.ts b/packages/core/dist/types/waku.d.ts new file mode 100644 index 0000000..6f34987 --- /dev/null +++ b/packages/core/dist/types/waku.d.ts @@ -0,0 +1,138 @@ +import { EDisplayPreference, EVerificationStatus } from './identity'; +import { DelegationProof } from '../delegation/types'; +/** + * Message types for Waku communication + */ +export declare enum MessageType { + CELL = "cell", + POST = "post", + COMMENT = "comment", + VOTE = "vote", + MODERATE = "moderate", + USER_PROFILE_UPDATE = "user_profile_update" +} +/** + * Base interface for unsigned messages (before signing) + */ +export interface UnsignedBaseMessage { + id: string; + type: MessageType; + timestamp: number; + author: string; +} +/** + * Base interface for all signed message types + */ +export interface BaseMessage extends UnsignedBaseMessage { + signature: string; + browserPubKey: string; + delegationProof: DelegationProof; +} +/** + * Unsigned message types (for creation, before signing) + */ +export interface UnsignedCellMessage extends UnsignedBaseMessage { + type: MessageType.CELL; + name: string; + description: string; + icon?: string; +} +export interface UnsignedPostMessage extends UnsignedBaseMessage { + type: MessageType.POST; + cellId: string; + title: string; + content: string; +} +export interface UnsignedCommentMessage extends UnsignedBaseMessage { + type: MessageType.COMMENT; + postId: string; + content: string; +} +export interface UnsignedVoteMessage extends UnsignedBaseMessage { + type: MessageType.VOTE; + targetId: string; + value: 1 | -1; +} +export interface UnsignedModerateMessage extends UnsignedBaseMessage { + type: MessageType.MODERATE; + cellId: string; + targetType: 'post' | 'comment' | 'user'; + targetId: string; + reason?: string; +} +export interface UnsignedUserProfileUpdateMessage extends UnsignedBaseMessage { + type: MessageType.USER_PROFILE_UPDATE; + callSign?: string; + displayPreference: EDisplayPreference; +} +/** + * Signed message types (after signature is added) + */ +export interface CellMessage extends BaseMessage { + type: MessageType.CELL; + name: string; + description: string; + icon?: string; +} +export interface PostMessage extends BaseMessage { + type: MessageType.POST; + cellId: string; + title: string; + content: string; +} +export interface CommentMessage extends BaseMessage { + type: MessageType.COMMENT; + postId: string; + content: string; +} +export interface VoteMessage extends BaseMessage { + type: MessageType.VOTE; + targetId: string; + value: 1 | -1; +} +export interface ModerateMessage extends BaseMessage { + type: MessageType.MODERATE; + cellId: string; + targetType: 'post' | 'comment' | 'user'; + targetId: string; + reason?: string; +} +export interface UserProfileUpdateMessage extends BaseMessage { + type: MessageType.USER_PROFILE_UPDATE; + callSign?: string; + displayPreference: EDisplayPreference; +} +/** + * Union types for message handling + */ +export type UnsignedMessage = UnsignedCellMessage | UnsignedPostMessage | UnsignedCommentMessage | UnsignedVoteMessage | UnsignedModerateMessage | UnsignedUserProfileUpdateMessage; +export type SignedMessage = CellMessage | PostMessage | CommentMessage | VoteMessage | ModerateMessage | UserProfileUpdateMessage; +/** + * Cache objects for storing messages + */ +export interface CellCache { + [cellId: string]: CellMessage; +} +export interface PostCache { + [postId: string]: PostMessage; +} +export interface CommentCache { + [commentId: string]: CommentMessage; +} +export interface VoteCache { + [key: string]: VoteMessage; +} +export interface UserIdentityCache { + [address: string]: { + ensName?: string; + ordinalDetails?: { + ordinalId: string; + ordinalDetails: string; + }; + callSign?: string; + displayPreference: EDisplayPreference; + lastUpdated: number; + verificationStatus: EVerificationStatus; + }; +} +//# sourceMappingURL=waku.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/types/waku.d.ts.map b/packages/core/dist/types/waku.d.ts.map new file mode 100644 index 0000000..1dd3359 --- /dev/null +++ b/packages/core/dist/types/waku.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"waku.d.ts","sourceRoot":"","sources":["../../src/types/waku.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;GAEG;AACH,oBAAY,WAAW;IACrB,IAAI,SAAS;IACb,IAAI,SAAS;IACb,OAAO,YAAY;IACnB,IAAI,SAAS;IACb,QAAQ,aAAa;IACrB,mBAAmB,wBAAwB;CAC5C;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,WAAW,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,WAAY,SAAQ,mBAAmB;IACtD,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,eAAe,CAAC;CAClC;AAED;;GAEG;AACH,MAAM,WAAW,mBAAoB,SAAQ,mBAAmB;IAC9D,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,mBAAoB,SAAQ,mBAAmB;IAC9D,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,sBAAuB,SAAQ,mBAAmB;IACjE,IAAI,EAAE,WAAW,CAAC,OAAO,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,mBAAoB,SAAQ,mBAAmB;IAC9D,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;CACf;AAED,MAAM,WAAW,uBAAwB,SAAQ,mBAAmB;IAClE,IAAI,EAAE,WAAW,CAAC,QAAQ,CAAC;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAAC;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,gCAAiC,SAAQ,mBAAmB;IAC3E,IAAI,EAAE,WAAW,CAAC,mBAAmB,CAAC;IACtC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iBAAiB,EAAE,kBAAkB,CAAC;CACvC;AAED;;GAEG;AACH,MAAM,WAAW,WAAY,SAAQ,WAAW;IAC9C,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,WAAY,SAAQ,WAAW;IAC9C,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAe,SAAQ,WAAW;IACjD,IAAI,EAAE,WAAW,CAAC,OAAO,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,WAAY,SAAQ,WAAW;IAC9C,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;CACf;AAED,MAAM,WAAW,eAAgB,SAAQ,WAAW;IAClD,IAAI,EAAE,WAAW,CAAC,QAAQ,CAAC;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAAC;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,wBAAyB,SAAQ,WAAW;IAC3D,IAAI,EAAE,WAAW,CAAC,mBAAmB,CAAC;IACtC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iBAAiB,EAAE,kBAAkB,CAAC;CACvC;AAED;;GAEG;AACH,MAAM,MAAM,eAAe,GACvB,mBAAmB,GACnB,mBAAmB,GACnB,sBAAsB,GACtB,mBAAmB,GACnB,uBAAuB,GACvB,gCAAgC,CAAC;AAErC,MAAM,MAAM,aAAa,GACrB,WAAW,GACX,WAAW,GACX,cAAc,GACd,WAAW,GACX,eAAe,GACf,wBAAwB,CAAC;AAE7B;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,CAAC;CAC/B;AAED,MAAM,WAAW,SAAS;IACxB,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,CAAC;CAC/B;AAED,MAAM,WAAW,YAAY;IAC3B,CAAC,SAAS,EAAE,MAAM,GAAG,cAAc,CAAC;CACrC;AAED,MAAM,WAAW,SAAS;IACxB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAAC;CAC5B;AAED,MAAM,WAAW,iBAAiB;IAChC,CAAC,OAAO,EAAE,MAAM,GAAG;QACjB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,cAAc,CAAC,EAAE;YACf,SAAS,EAAE,MAAM,CAAC;YAClB,cAAc,EAAE,MAAM,CAAC;SACxB,CAAC;QACF,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,iBAAiB,EAAE,kBAAkB,CAAC;QACtC,WAAW,EAAE,MAAM,CAAC;QACpB,kBAAkB,EAAE,mBAAmB,CAAC;KACzC,CAAC;CACH"} \ No newline at end of file diff --git a/packages/core/dist/types/waku.js b/packages/core/dist/types/waku.js new file mode 100644 index 0000000..1fe4454 --- /dev/null +++ b/packages/core/dist/types/waku.js @@ -0,0 +1,13 @@ +/** + * Message types for Waku communication + */ +export var MessageType; +(function (MessageType) { + MessageType["CELL"] = "cell"; + MessageType["POST"] = "post"; + MessageType["COMMENT"] = "comment"; + MessageType["VOTE"] = "vote"; + MessageType["MODERATE"] = "moderate"; + MessageType["USER_PROFILE_UPDATE"] = "user_profile_update"; +})(MessageType || (MessageType = {})); +//# sourceMappingURL=waku.js.map \ No newline at end of file diff --git a/packages/core/dist/types/waku.js.map b/packages/core/dist/types/waku.js.map new file mode 100644 index 0000000..1037fa9 --- /dev/null +++ b/packages/core/dist/types/waku.js.map @@ -0,0 +1 @@ +{"version":3,"file":"waku.js","sourceRoot":"","sources":["../../src/types/waku.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,MAAM,CAAN,IAAY,WAOX;AAPD,WAAY,WAAW;IACrB,4BAAa,CAAA;IACb,4BAAa,CAAA;IACb,kCAAmB,CAAA;IACnB,4BAAa,CAAA;IACb,oCAAqB,CAAA;IACrB,0DAA2C,CAAA;AAC7C,CAAC,EAPW,WAAW,KAAX,WAAW,QAOtB"} \ No newline at end of file diff --git a/packages/core/dist/utils.d.ts b/packages/core/dist/utils.d.ts new file mode 100644 index 0000000..a80a5e8 --- /dev/null +++ b/packages/core/dist/utils.d.ts @@ -0,0 +1,4 @@ +export declare function bytesToHex(bytes: Uint8Array): string; +export declare function hexToBytes(hex: string): Uint8Array; +export declare function generateStringId(): string; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/utils.d.ts.map b/packages/core/dist/utils.d.ts.map new file mode 100644 index 0000000..9f0d2f9 --- /dev/null +++ b/packages/core/dist/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAIpD;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAMlD;AAED,wBAAgB,gBAAgB,IAAI,MAAM,CAEzC"} \ No newline at end of file diff --git a/packages/core/dist/utils.js b/packages/core/dist/utils.js new file mode 100644 index 0000000..76bff44 --- /dev/null +++ b/packages/core/dist/utils.js @@ -0,0 +1,16 @@ +export function bytesToHex(bytes) { + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, '0')) + .join(''); +} +export function hexToBytes(hex) { + const bytes = new Uint8Array(hex.length / 2); + for (let i = 0; i < hex.length; i += 2) { + bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16); + } + return bytes; +} +export function generateStringId() { + return crypto.randomUUID(); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/packages/core/dist/utils.js.map b/packages/core/dist/utils.js.map new file mode 100644 index 0000000..eabacb7 --- /dev/null +++ b/packages/core/dist/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,UAAU,CAAC,KAAiB;IAC1C,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;SACrB,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;SAC3C,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACvC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,gBAAgB;IAC9B,OAAO,MAAM,CAAC,UAAU,EAAE,CAAC;AAC7B,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/utils/MessageValidator.d.ts b/packages/core/dist/utils/MessageValidator.d.ts new file mode 100644 index 0000000..42ae760 --- /dev/null +++ b/packages/core/dist/utils/MessageValidator.d.ts @@ -0,0 +1,85 @@ +import { OpchanMessage } from '../types/forum'; +import { DelegationManager } from '../delegation'; +interface ValidationReport { + validMessages: OpchanMessage[]; + invalidMessages: unknown[]; + totalProcessed: number; + validationErrors: string[]; +} +export declare class MessageValidator { + private delegationManager?; + constructor(delegationManager?: DelegationManager); + private getDelegationManager; + /** + * Validates that a message has required signature fields and valid signature + */ + isValidMessage(message: unknown): Promise; + /** + * Checks if message has required signature and browserPubKey fields + */ + private hasRequiredFields; + /** + * Validates multiple messages and returns validation report + */ + validateMessages(messages: unknown[]): Promise; + /** + * Validates and returns a single message if valid + */ + validateSingleMessage(message: unknown): Promise; + /** + * Batch validation with performance optimization + */ + batchValidate(messages: unknown[], options?: { + maxConcurrent?: number; + skipInvalid?: boolean; + }): Promise; + /** + * Quick validation check without full verification (for performance) + */ + quickValidate(message: unknown): boolean; + /** + * Get validation statistics + */ + getValidationStats(report: ValidationReport): { + validCount: number; + invalidCount: number; + totalProcessed: number; + successRate: number; + errorCount: number; + hasErrors: boolean; + }; + /** + * Filter messages by type after validation + */ + filterByType(messages: OpchanMessage[], messageType: string): T[]; + /** + * Sort messages by timestamp + */ + sortByTimestamp(messages: OpchanMessage[], ascending?: boolean): OpchanMessage[]; + /** + * Group messages by author + */ + groupByAuthor(messages: OpchanMessage[]): Record; + /** + * Get validation report for a message (for backward compatibility) + */ + getValidationReport(message: unknown): Promise<{ + isValid: boolean; + hasValidSignature: boolean; + missingFields: string[]; + invalidFields: string[]; + warnings: string[]; + errors: string[]; + }>; + /** + * Validate message structure and return detailed report + */ + validateStructure(message: unknown): { + isValid: boolean; + missingFields: string[]; + invalidFields: string[]; + warnings: string[]; + }; +} +export {}; +//# sourceMappingURL=MessageValidator.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/utils/MessageValidator.d.ts.map b/packages/core/dist/utils/MessageValidator.d.ts.map new file mode 100644 index 0000000..8d0d1f6 --- /dev/null +++ b/packages/core/dist/utils/MessageValidator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"MessageValidator.d.ts","sourceRoot":"","sources":["../../src/utils/MessageValidator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAkB,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,UAAU,gBAAgB;IACxB,aAAa,EAAE,aAAa,EAAE,CAAC;IAC/B,eAAe,EAAE,OAAO,EAAE,CAAC;IAC3B,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,EAAE,MAAM,EAAE,CAAC;CAC5B;AAED,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,iBAAiB,CAAC,CAAoB;gBAElC,iBAAiB,CAAC,EAAE,iBAAiB;IAIjD,OAAO,CAAC,oBAAoB;IAO5B;;OAEG;IACG,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IAgBxD;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAwBzB;;OAEG;IACG,gBAAgB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC;IA6CtE;;OAEG;IACG,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,aAAa,CAAC;IAoBrE;;OAEG;IACG,aAAa,CACjB,QAAQ,EAAE,OAAO,EAAE,EACnB,OAAO,GAAE;QACP,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,WAAW,CAAC,EAAE,OAAO,CAAC;KAClB,GACL,OAAO,CAAC,gBAAgB,CAAC;IAsD5B;;OAEG;IACH,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO;IAIxC;;OAEG;IACH,kBAAkB,CAAC,MAAM,EAAE,gBAAgB;;;;;;;;IAgB3C;;OAEG;IACH,YAAY,CAAC,CAAC,SAAS,aAAa,EAClC,QAAQ,EAAE,aAAa,EAAE,EACzB,WAAW,EAAE,MAAM,GAClB,CAAC,EAAE;IAIN;;OAEG;IACH,eAAe,CACb,QAAQ,EAAE,aAAa,EAAE,EACzB,SAAS,UAAO,GACf,aAAa,EAAE;IAMlB;;OAEG;IACH,aAAa,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,aAAa,EAAE,CAAC;IAgBzE;;OAEG;IACG,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC;QACnD,OAAO,EAAE,OAAO,CAAC;QACjB,iBAAiB,EAAE,OAAO,CAAC;QAC3B,aAAa,EAAE,MAAM,EAAE,CAAC;QACxB,aAAa,EAAE,MAAM,EAAE,CAAC;QACxB,QAAQ,EAAE,MAAM,EAAE,CAAC;QACnB,MAAM,EAAE,MAAM,EAAE,CAAC;KAClB,CAAC;IAgBF;;OAEG;IACH,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG;QACnC,OAAO,EAAE,OAAO,CAAC;QACjB,aAAa,EAAE,MAAM,EAAE,CAAC;QACxB,aAAa,EAAE,MAAM,EAAE,CAAC;QACxB,QAAQ,EAAE,MAAM,EAAE,CAAC;KACpB;CAwDF"} \ No newline at end of file diff --git a/packages/core/dist/utils/MessageValidator.js b/packages/core/dist/utils/MessageValidator.js new file mode 100644 index 0000000..f17d325 --- /dev/null +++ b/packages/core/dist/utils/MessageValidator.js @@ -0,0 +1,279 @@ +import { DelegationManager } from '../delegation'; +export class MessageValidator { + constructor(delegationManager) { + this.delegationManager = delegationManager; + } + getDelegationManager() { + if (!this.delegationManager) { + this.delegationManager = new DelegationManager(); + } + return this.delegationManager; + } + /** + * Validates that a message has required signature fields and valid signature + */ + async isValidMessage(message) { + // Check basic structure + if (!this.hasRequiredFields(message)) { + return false; + } + // Verify signature and delegation proof - we know it's safe to cast here since hasRequiredFields passed + try { + return await this.getDelegationManager().verify(message); + } + catch { + return false; + } + } + /** + * Checks if message has required signature and browserPubKey fields + */ + hasRequiredFields(message) { + if (!message || typeof message !== 'object') { + return false; + } + const msg = message; + return (typeof msg.signature === 'string' && + typeof msg.browserPubKey === 'string' && + typeof msg.id === 'string' && + typeof msg.type === 'string' && + typeof msg.timestamp === 'number' && + typeof msg.author === 'string'); + } + /** + * Validates multiple messages and returns validation report + */ + async validateMessages(messages) { + const validMessages = []; + const invalidMessages = []; + const validationErrors = []; + for (const message of messages) { + try { + // Check basic structure first + if (!this.hasRequiredFields(message)) { + invalidMessages.push(message); + validationErrors.push('Missing required fields'); + continue; + } + // Verify signature + try { + const isValid = await this.getDelegationManager().verify(message); + if (!isValid) { + invalidMessages.push(message); + validationErrors.push('Invalid signature'); + continue; + } + validMessages.push(message); + } + catch { + invalidMessages.push(message); + validationErrors.push('Signature verification failed'); + } + } + catch (error) { + invalidMessages.push(message); + validationErrors.push(error instanceof Error ? error.message : 'Unknown validation error'); + } + } + return { + validMessages, + invalidMessages, + totalProcessed: messages.length, + validationErrors, + }; + } + /** + * Validates and returns a single message if valid + */ + async validateSingleMessage(message) { + // Check basic structure + if (!this.hasRequiredFields(message)) { + throw new Error('Message missing required fields'); + } + // Verify signature and delegation proof + try { + const isValid = await this.getDelegationManager().verify(message); + if (!isValid) { + throw new Error('Invalid message signature'); + } + return message; + } + catch (error) { + throw new Error(`Message validation failed: ${error}`); + } + } + /** + * Batch validation with performance optimization + */ + async batchValidate(messages, options = {}) { + const { maxConcurrent = 10, skipInvalid = true } = options; + const validMessages = []; + const invalidMessages = []; + const validationErrors = []; + // Process messages in batches to avoid overwhelming the system + for (let i = 0; i < messages.length; i += maxConcurrent) { + const batch = messages.slice(i, i + maxConcurrent); + const batchPromises = batch.map(async (message, index) => { + try { + const isValid = await this.isValidMessage(message); + return { message, isValid, index: i + index, error: null }; + } + catch (error) { + return { + message, + isValid: false, + index: i + index, + error: error instanceof Error ? error.message : 'Unknown error', + }; + } + }); + const batchResults = await Promise.allSettled(batchPromises); + for (const result of batchResults) { + if (result.status === 'fulfilled') { + const { message, isValid, error } = result.value; + if (isValid) { + validMessages.push(message); + } + else { + if (!skipInvalid) { + invalidMessages.push(message); + if (error) + validationErrors.push(error); + } + } + } + else { + if (!skipInvalid) { + validationErrors.push(result.reason?.message || 'Batch validation failed'); + } + } + } + } + return { + validMessages, + invalidMessages, + totalProcessed: messages.length, + validationErrors, + }; + } + /** + * Quick validation check without full verification (for performance) + */ + quickValidate(message) { + return this.hasRequiredFields(message); + } + /** + * Get validation statistics + */ + getValidationStats(report) { + const validCount = report.validMessages.length; + const invalidCount = report.invalidMessages.length; + const successRate = report.totalProcessed > 0 ? validCount / report.totalProcessed : 0; + return { + validCount, + invalidCount, + totalProcessed: report.totalProcessed, + successRate, + errorCount: report.validationErrors.length, + hasErrors: report.validationErrors.length > 0, + }; + } + /** + * Filter messages by type after validation + */ + filterByType(messages, messageType) { + return messages.filter((msg) => msg.type === messageType); + } + /** + * Sort messages by timestamp + */ + sortByTimestamp(messages, ascending = true) { + return [...messages].sort((a, b) => ascending ? a.timestamp - b.timestamp : b.timestamp - a.timestamp); + } + /** + * Group messages by author + */ + groupByAuthor(messages) { + const grouped = {}; + for (const message of messages) { + if (!grouped[message.author]) { + grouped[message.author] = []; + } + const authorMessages = grouped[message.author]; + if (authorMessages) { + authorMessages.push(message); + } + } + return grouped; + } + /** + * Get validation report for a message (for backward compatibility) + */ + async getValidationReport(message) { + const structureReport = this.validateStructure(message); + const hasValidSignature = structureReport.isValid + ? await this.isValidMessage(message) + : false; + return { + ...structureReport, + hasValidSignature, + errors: [ + ...structureReport.missingFields, + ...structureReport.invalidFields, + ], + }; + } + /** + * Validate message structure and return detailed report + */ + validateStructure(message) { + const missingFields = []; + const invalidFields = []; + const warnings = []; + if (!message || typeof message !== 'object') { + return { + isValid: false, + missingFields: ['message'], + invalidFields: [], + warnings: ['Message is not an object'], + }; + } + const msg = message; + const requiredFields = [ + 'signature', + 'browserPubKey', + 'id', + 'type', + 'timestamp', + 'author', + ]; + for (const field of requiredFields) { + if (!(field in msg)) { + missingFields.push(field); + } + else if (typeof msg[field] !== (field === 'timestamp' ? 'number' : 'string')) { + invalidFields.push(field); + } + } + // Additional validation warnings + if (typeof msg.timestamp === 'number') { + const age = Date.now() - msg.timestamp; + if (age > 24 * 60 * 60 * 1000) { + // Older than 24 hours + warnings.push('Message is older than 24 hours'); + } + if (msg.timestamp > Date.now() + 5 * 60 * 1000) { + // More than 5 minutes in future + warnings.push('Message timestamp is in the future'); + } + } + const isValid = missingFields.length === 0 && invalidFields.length === 0; + return { + isValid, + missingFields, + invalidFields, + warnings, + }; + } +} +//# sourceMappingURL=MessageValidator.js.map \ No newline at end of file diff --git a/packages/core/dist/utils/MessageValidator.js.map b/packages/core/dist/utils/MessageValidator.js.map new file mode 100644 index 0000000..2e115ae --- /dev/null +++ b/packages/core/dist/utils/MessageValidator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MessageValidator.js","sourceRoot":"","sources":["../../src/utils/MessageValidator.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AASlD,MAAM,OAAO,gBAAgB;IAG3B,YAAY,iBAAqC;QAC/C,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;IAC7C,CAAC;IAEO,oBAAoB;QAC1B,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC5B,IAAI,CAAC,iBAAiB,GAAG,IAAI,iBAAiB,EAAE,CAAC;QACnD,CAAC;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC;IAChC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,cAAc,CAAC,OAAgB;QACnC,wBAAwB;QACxB,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;YACrC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,wGAAwG;QACxG,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,CAAC,oBAAoB,EAAE,CAAC,MAAM,CAC7C,OAAmC,CACpC,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED;;OAEG;IACK,iBAAiB,CAAC,OAAgB;QAQxC,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAC5C,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,GAAG,GAAG,OAAkC,CAAC;QAE/C,OAAO,CACL,OAAO,GAAG,CAAC,SAAS,KAAK,QAAQ;YACjC,OAAO,GAAG,CAAC,aAAa,KAAK,QAAQ;YACrC,OAAO,GAAG,CAAC,EAAE,KAAK,QAAQ;YAC1B,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ;YAC5B,OAAO,GAAG,CAAC,SAAS,KAAK,QAAQ;YACjC,OAAO,GAAG,CAAC,MAAM,KAAK,QAAQ,CAC/B,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,gBAAgB,CAAC,QAAmB;QACxC,MAAM,aAAa,GAAoB,EAAE,CAAC;QAC1C,MAAM,eAAe,GAAc,EAAE,CAAC;QACtC,MAAM,gBAAgB,GAAa,EAAE,CAAC;QAEtC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC/B,IAAI,CAAC;gBACH,8BAA8B;gBAC9B,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;oBACrC,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBAC9B,gBAAgB,CAAC,IAAI,CAAC,yBAAyB,CAAC,CAAC;oBACjD,SAAS;gBACX,CAAC;gBAED,mBAAmB;gBACnB,IAAI,CAAC;oBACH,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,oBAAoB,EAAE,CAAC,MAAM,CACtD,OAAmC,CACpC,CAAC;oBACF,IAAI,CAAC,OAAO,EAAE,CAAC;wBACb,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;wBAC9B,gBAAgB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;wBAC3C,SAAS;oBACX,CAAC;oBACD,aAAa,CAAC,IAAI,CAAC,OAAmC,CAAC,CAAC;gBAC1D,CAAC;gBAAC,MAAM,CAAC;oBACP,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBAC9B,gBAAgB,CAAC,IAAI,CAAC,+BAA+B,CAAC,CAAC;gBACzD,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBAC9B,gBAAgB,CAAC,IAAI,CACnB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,0BAA0B,CACpE,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO;YACL,aAAa;YACb,eAAe;YACf,cAAc,EAAE,QAAQ,CAAC,MAAM;YAC/B,gBAAgB;SACjB,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,qBAAqB,CAAC,OAAgB;QAC1C,wBAAwB;QACxB,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;YACrC,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;QACrD,CAAC;QAED,wCAAwC;QACxC,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,oBAAoB,EAAE,CAAC,MAAM,CACtD,OAAmC,CACpC,CAAC;YACF,IAAI,CAAC,OAAO,EAAE,CAAC;gBACb,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;YAC/C,CAAC;YACD,OAAO,OAAmC,CAAC;QAC7C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CAAC,8BAA8B,KAAK,EAAE,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa,CACjB,QAAmB,EACnB,UAGI,EAAE;QAEN,MAAM,EAAE,aAAa,GAAG,EAAE,EAAE,WAAW,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;QAC3D,MAAM,aAAa,GAAoB,EAAE,CAAC;QAC1C,MAAM,eAAe,GAAc,EAAE,CAAC;QACtC,MAAM,gBAAgB,GAAa,EAAE,CAAC;QAEtC,+DAA+D;QAC/D,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,aAAa,EAAE,CAAC;YACxD,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,aAAa,CAAC,CAAC;YACnD,MAAM,aAAa,GAAG,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE;gBACvD,IAAI,CAAC;oBACH,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;oBACnD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,GAAG,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;gBAC7D,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,OAAO;wBACL,OAAO;wBACP,OAAO,EAAE,KAAK;wBACd,KAAK,EAAE,CAAC,GAAG,KAAK;wBAChB,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe;qBAChE,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;YAEH,MAAM,YAAY,GAAG,MAAM,OAAO,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;YAE7D,KAAK,MAAM,MAAM,IAAI,YAAY,EAAE,CAAC;gBAClC,IAAI,MAAM,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;oBAClC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC;oBACjD,IAAI,OAAO,EAAE,CAAC;wBACZ,aAAa,CAAC,IAAI,CAAC,OAAmC,CAAC,CAAC;oBAC1D,CAAC;yBAAM,CAAC;wBACN,IAAI,CAAC,WAAW,EAAE,CAAC;4BACjB,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;4BAC9B,IAAI,KAAK;gCAAE,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;wBAC1C,CAAC;oBACH,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,IAAI,CAAC,WAAW,EAAE,CAAC;wBACjB,gBAAgB,CAAC,IAAI,CACnB,MAAM,CAAC,MAAM,EAAE,OAAO,IAAI,yBAAyB,CACpD,CAAC;oBACJ,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO;YACL,aAAa;YACb,eAAe;YACf,cAAc,EAAE,QAAQ,CAAC,MAAM;YAC/B,gBAAgB;SACjB,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,OAAgB;QAC5B,OAAO,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;IACzC,CAAC;IAED;;OAEG;IACH,kBAAkB,CAAC,MAAwB;QACzC,MAAM,UAAU,GAAG,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;QAC/C,MAAM,YAAY,GAAG,MAAM,CAAC,eAAe,CAAC,MAAM,CAAC;QACnD,MAAM,WAAW,GACf,MAAM,CAAC,cAAc,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC;QAErE,OAAO;YACL,UAAU;YACV,YAAY;YACZ,cAAc,EAAE,MAAM,CAAC,cAAc;YACrC,WAAW;YACX,UAAU,EAAE,MAAM,CAAC,gBAAgB,CAAC,MAAM;YAC1C,SAAS,EAAE,MAAM,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC;SAC9C,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,YAAY,CACV,QAAyB,EACzB,WAAmB;QAEnB,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,KAAK,WAAW,CAAQ,CAAC;IACnE,CAAC;IAED;;OAEG;IACH,eAAe,CACb,QAAyB,EACzB,SAAS,GAAG,IAAI;QAEhB,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACjC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAClE,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,QAAyB;QACrC,MAAM,OAAO,GAAoC,EAAE,CAAC;QAEpD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC/B,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC7B,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;YAC/B,CAAC;YACD,MAAM,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAC/C,IAAI,cAAc,EAAE,CAAC;gBACnB,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAC/B,CAAC;QACH,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,mBAAmB,CAAC,OAAgB;QAQxC,MAAM,eAAe,GAAG,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QACxD,MAAM,iBAAiB,GAAG,eAAe,CAAC,OAAO;YAC/C,CAAC,CAAC,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC;YACpC,CAAC,CAAC,KAAK,CAAC;QAEV,OAAO;YACL,GAAG,eAAe;YAClB,iBAAiB;YACjB,MAAM,EAAE;gBACN,GAAG,eAAe,CAAC,aAAa;gBAChC,GAAG,eAAe,CAAC,aAAa;aACjC;SACF,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,iBAAiB,CAAC,OAAgB;QAMhC,MAAM,aAAa,GAAa,EAAE,CAAC;QACnC,MAAM,aAAa,GAAa,EAAE,CAAC;QACnC,MAAM,QAAQ,GAAa,EAAE,CAAC;QAE9B,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAC5C,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,aAAa,EAAE,CAAC,SAAS,CAAC;gBAC1B,aAAa,EAAE,EAAE;gBACjB,QAAQ,EAAE,CAAC,0BAA0B,CAAC;aACvC,CAAC;QACJ,CAAC;QAED,MAAM,GAAG,GAAG,OAAkC,CAAC;QAC/C,MAAM,cAAc,GAAG;YACrB,WAAW;YACX,eAAe;YACf,IAAI;YACJ,MAAM;YACN,WAAW;YACX,QAAQ;SACT,CAAC;QAEF,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE,CAAC;YACnC,IAAI,CAAC,CAAC,KAAK,IAAI,GAAG,CAAC,EAAE,CAAC;gBACpB,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAC5B,CAAC;iBAAM,IACL,OAAO,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,KAAK,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,EACnE,CAAC;gBACD,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;QAED,iCAAiC;QACjC,IAAI,OAAO,GAAG,CAAC,SAAS,KAAK,QAAQ,EAAE,CAAC;YACtC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,SAAS,CAAC;YACvC,IAAI,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC;gBAC9B,sBAAsB;gBACtB,QAAQ,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC;YAClD,CAAC;YACD,IAAI,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC;gBAC/C,gCAAgC;gBAChC,QAAQ,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAC;YACtD,CAAC;QACH,CAAC;QAED,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,KAAK,CAAC,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC,CAAC;QAEzE,OAAO;YACL,OAAO;YACP,aAAa;YACb,aAAa;YACb,QAAQ;SACT,CAAC;IACJ,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/utils/sorting.d.ts b/packages/core/dist/utils/sorting.d.ts new file mode 100644 index 0000000..49acf46 --- /dev/null +++ b/packages/core/dist/utils/sorting.d.ts @@ -0,0 +1,23 @@ +import { Post, Comment, Cell } from '../types/forum'; +export type SortOption = 'relevance' | 'time'; +/** + * Sort posts by relevance score (highest first) + */ +export declare const sortByRelevance: (items: Post[] | Comment[] | Cell[]) => Comment[] | Post[] | Cell[]; +/** + * Sort by timestamp (newest first) + */ +export declare const sortByTime: (items: Post[] | Comment[] | Cell[]) => Comment[] | Post[] | Cell[]; +/** + * Sort posts with a specific option + */ +export declare const sortPosts: (posts: Post[], option: SortOption) => Post[]; +/** + * Sort comments with a specific option + */ +export declare const sortComments: (comments: Comment[], option: SortOption) => Comment[]; +/** + * Sort cells with a specific option + */ +export declare const sortCells: (cells: Cell[], option: SortOption) => Cell[]; +//# sourceMappingURL=sorting.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/utils/sorting.d.ts.map b/packages/core/dist/utils/sorting.d.ts.map new file mode 100644 index 0000000..295e775 --- /dev/null +++ b/packages/core/dist/utils/sorting.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sorting.d.ts","sourceRoot":"","sources":["../../src/utils/sorting.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAErD,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG,MAAM,CAAC;AAE9C;;GAEG;AACH,eAAO,MAAM,eAAe,GAAI,OAAO,IAAI,EAAE,GAAG,OAAO,EAAE,GAAG,IAAI,EAAE,gCAIjE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,UAAU,GAAI,OAAO,IAAI,EAAE,GAAG,OAAO,EAAE,GAAG,IAAI,EAAE,gCAE5D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,SAAS,GAAI,OAAO,IAAI,EAAE,EAAE,QAAQ,UAAU,KAAG,IAAI,EASjE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,YAAY,GACvB,UAAU,OAAO,EAAE,EACnB,QAAQ,UAAU,KACjB,OAAO,EAST,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,SAAS,GAAI,OAAO,IAAI,EAAE,EAAE,QAAQ,UAAU,KAAG,IAAI,EASjE,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/utils/sorting.js b/packages/core/dist/utils/sorting.js new file mode 100644 index 0000000..6fb8dd6 --- /dev/null +++ b/packages/core/dist/utils/sorting.js @@ -0,0 +1,52 @@ +/** + * Sort posts by relevance score (highest first) + */ +export const sortByRelevance = (items) => { + return items.sort((a, b) => (b.relevanceScore || 0) - (a.relevanceScore || 0)); +}; +/** + * Sort by timestamp (newest first) + */ +export const sortByTime = (items) => { + return items.sort((a, b) => b.timestamp - a.timestamp); +}; +/** + * Sort posts with a specific option + */ +export const sortPosts = (posts, option) => { + switch (option) { + case 'relevance': + return sortByRelevance(posts); + case 'time': + return sortByTime(posts); + default: + return sortByRelevance(posts); + } +}; +/** + * Sort comments with a specific option + */ +export const sortComments = (comments, option) => { + switch (option) { + case 'relevance': + return sortByRelevance(comments); + case 'time': + return sortByTime(comments); + default: + return sortByRelevance(comments); + } +}; +/** + * Sort cells with a specific option + */ +export const sortCells = (cells, option) => { + switch (option) { + case 'relevance': + return sortByRelevance(cells); + case 'time': + return sortByTime(cells); + default: + return sortByRelevance(cells); + } +}; +//# sourceMappingURL=sorting.js.map \ No newline at end of file diff --git a/packages/core/dist/utils/sorting.js.map b/packages/core/dist/utils/sorting.js.map new file mode 100644 index 0000000..9f71454 --- /dev/null +++ b/packages/core/dist/utils/sorting.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sorting.js","sourceRoot":"","sources":["../../src/utils/sorting.ts"],"names":[],"mappings":"AAIA;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,KAAkC,EAAE,EAAE;IACpE,OAAO,KAAK,CAAC,IAAI,CACf,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,cAAc,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,cAAc,IAAI,CAAC,CAAC,CAC5D,CAAC;AACJ,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,KAAkC,EAAE,EAAE;IAC/D,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC;AACzD,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,KAAa,EAAE,MAAkB,EAAU,EAAE;IACrE,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,WAAW;YACd,OAAO,eAAe,CAAC,KAAK,CAAW,CAAC;QAC1C,KAAK,MAAM;YACT,OAAO,UAAU,CAAC,KAAK,CAAW,CAAC;QACrC;YACE,OAAO,eAAe,CAAC,KAAK,CAAW,CAAC;IAC5C,CAAC;AACH,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAC1B,QAAmB,EACnB,MAAkB,EACP,EAAE;IACb,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,WAAW;YACd,OAAO,eAAe,CAAC,QAAQ,CAAc,CAAC;QAChD,KAAK,MAAM;YACT,OAAO,UAAU,CAAC,QAAQ,CAAc,CAAC;QAC3C;YACE,OAAO,eAAe,CAAC,QAAQ,CAAc,CAAC;IAClD,CAAC;AACH,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,KAAa,EAAE,MAAkB,EAAU,EAAE;IACrE,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,WAAW;YACd,OAAO,eAAe,CAAC,KAAK,CAAW,CAAC;QAC1C,KAAK,MAAM;YACT,OAAO,UAAU,CAAC,KAAK,CAAW,CAAC;QACrC;YACE,OAAO,eAAe,CAAC,KAAK,CAAW,CAAC;IAC5C,CAAC;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/utils/urlLoads.d.ts b/packages/core/dist/utils/urlLoads.d.ts new file mode 100644 index 0000000..26e55a4 --- /dev/null +++ b/packages/core/dist/utils/urlLoads.d.ts @@ -0,0 +1,5 @@ +/** + * Utility to check if a URL loads successfully within a timeout + */ +export declare function urlLoads(url: string, timeoutMs?: number): Promise; +//# sourceMappingURL=urlLoads.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/utils/urlLoads.d.ts.map b/packages/core/dist/utils/urlLoads.d.ts.map new file mode 100644 index 0000000..cfa5076 --- /dev/null +++ b/packages/core/dist/utils/urlLoads.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"urlLoads.d.ts","sourceRoot":"","sources":["../../src/utils/urlLoads.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAsB,QAAQ,CAC5B,GAAG,EAAE,MAAM,EACX,SAAS,GAAE,MAAa,GACvB,OAAO,CAAC,OAAO,CAAC,CAgBlB"} \ No newline at end of file diff --git a/packages/core/dist/utils/urlLoads.js b/packages/core/dist/utils/urlLoads.js new file mode 100644 index 0000000..a4b07a7 --- /dev/null +++ b/packages/core/dist/utils/urlLoads.js @@ -0,0 +1,20 @@ +/** + * Utility to check if a URL loads successfully within a timeout + */ +export async function urlLoads(url, timeoutMs = 5000) { + try { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), timeoutMs); + const response = await fetch(url, { + method: 'HEAD', + signal: controller.signal, + cache: 'no-cache', + }); + clearTimeout(timeoutId); + return response.ok; + } + catch { + return false; + } +} +//# sourceMappingURL=urlLoads.js.map \ No newline at end of file diff --git a/packages/core/dist/utils/urlLoads.js.map b/packages/core/dist/utils/urlLoads.js.map new file mode 100644 index 0000000..f33240b --- /dev/null +++ b/packages/core/dist/utils/urlLoads.js.map @@ -0,0 +1 @@ +{"version":3,"file":"urlLoads.js","sourceRoot":"","sources":["../../src/utils/urlLoads.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,GAAW,EACX,YAAoB,IAAI;IAExB,IAAI,CAAC;QACH,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;QACzC,MAAM,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,SAAS,CAAC,CAAC;QAElE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;YAChC,MAAM,EAAE,MAAM;YACd,MAAM,EAAE,UAAU,CAAC,MAAM;YACzB,KAAK,EAAE,UAAU;SAClB,CAAC,CAAC;QAEH,YAAY,CAAC,SAAS,CAAC,CAAC;QACxB,OAAO,QAAQ,CAAC,EAAE,CAAC;IACrB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/waku/CodecManager.d.ts b/packages/core/dist/waku/CodecManager.d.ts new file mode 100644 index 0000000..e14045e --- /dev/null +++ b/packages/core/dist/waku/CodecManager.d.ts @@ -0,0 +1,34 @@ +import { IDecodedMessage, IDecoder, IEncoder, LightNode } from '@waku/sdk'; +import { MessageType } from '../types/waku'; +import { OpchanMessage } from '../types/forum'; +export declare class CodecManager { + private node; + private encoder; + private decoder; + constructor(node: LightNode); + /** + * Encode a message for transmission + */ + encodeMessage(message: OpchanMessage): Uint8Array; + /** + * Decode a received message + */ + decodeMessage(payload: Uint8Array): OpchanMessage; + /** + * Get the single encoder for all message types + */ + getEncoder(): IEncoder; + /** + * Get the single decoder for all message types + */ + getDecoder(): IDecoder; + /** + * Get all decoders (returns single decoder in array for compatibility) + */ + getAllDecoders(): IDecoder[]; + /** + * Get decoders for specific message types (returns single decoder for all types) + */ + getDecoders(_messageTypes: MessageType[]): IDecoder[]; +} +//# sourceMappingURL=CodecManager.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/waku/CodecManager.d.ts.map b/packages/core/dist/waku/CodecManager.d.ts.map new file mode 100644 index 0000000..8b5a318 --- /dev/null +++ b/packages/core/dist/waku/CodecManager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"CodecManager.d.ts","sourceRoot":"","sources":["../../src/waku/CodecManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAC3E,OAAO,EAAE,WAAW,EAA4B,MAAM,eAAe,CAAC;AAStE,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C,qBAAa,YAAY;IAIX,OAAO,CAAC,IAAI;IAHxB,OAAO,CAAC,OAAO,CAAW;IAC1B,OAAO,CAAC,OAAO,CAA4B;gBAEvB,IAAI,EAAE,SAAS;IAKnC;;OAEG;IACH,aAAa,CAAC,OAAO,EAAE,aAAa,GAAG,UAAU;IAKjD;;OAEG;IACH,aAAa,CAAC,OAAO,EAAE,UAAU,GAAG,aAAa;IAsBjD;;OAEG;IACH,UAAU,IAAI,QAAQ;IAItB;;OAEG;IACH,UAAU,IAAI,QAAQ,CAAC,eAAe,CAAC;IAIvC;;OAEG;IACH,cAAc,IAAI,QAAQ,CAAC,eAAe,CAAC,EAAE;IAI7C;;OAEG;IACH,WAAW,CAAC,aAAa,EAAE,WAAW,EAAE,GAAG,QAAQ,CAAC,eAAe,CAAC,EAAE;CAGvE"} \ No newline at end of file diff --git a/packages/core/dist/waku/CodecManager.js b/packages/core/dist/waku/CodecManager.js new file mode 100644 index 0000000..54b8fcb --- /dev/null +++ b/packages/core/dist/waku/CodecManager.js @@ -0,0 +1,64 @@ +import { MessageType } from '../types/waku'; +import { CONTENT_TOPIC } from './constants'; +export class CodecManager { + constructor(node) { + this.node = node; + this.encoder = this.node.createEncoder({ contentTopic: CONTENT_TOPIC }); + this.decoder = this.node.createDecoder({ contentTopic: CONTENT_TOPIC }); + } + /** + * Encode a message for transmission + */ + encodeMessage(message) { + const messageJson = JSON.stringify(message); + return new TextEncoder().encode(messageJson); + } + /** + * Decode a received message + */ + decodeMessage(payload) { + const messageJson = new TextDecoder().decode(payload); + const message = JSON.parse(messageJson); + switch (message.type) { + case MessageType.CELL: + return message; + case MessageType.POST: + return message; + case MessageType.COMMENT: + return message; + case MessageType.VOTE: + return message; + case MessageType.MODERATE: + return message; + case MessageType.USER_PROFILE_UPDATE: + return message; + default: + throw new Error(`Unknown message type: ${message}`); + } + } + /** + * Get the single encoder for all message types + */ + getEncoder() { + return this.encoder; + } + /** + * Get the single decoder for all message types + */ + getDecoder() { + return this.decoder; + } + /** + * Get all decoders (returns single decoder in array for compatibility) + */ + getAllDecoders() { + return [this.decoder]; + } + /** + * Get decoders for specific message types (returns single decoder for all types) + */ + getDecoders(_messageTypes) { + return [this.decoder]; + } +} +//# sourceMappingURL=CodecManager.js.map \ No newline at end of file diff --git a/packages/core/dist/waku/CodecManager.js.map b/packages/core/dist/waku/CodecManager.js.map new file mode 100644 index 0000000..1744f96 --- /dev/null +++ b/packages/core/dist/waku/CodecManager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"CodecManager.js","sourceRoot":"","sources":["../../src/waku/CodecManager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAA4B,MAAM,eAAe,CAAC;AAQtE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,MAAM,OAAO,YAAY;IAIvB,YAAoB,IAAe;QAAf,SAAI,GAAJ,IAAI,CAAW;QACjC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC,CAAC;IAC1E,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,OAAsB;QAClC,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QAC5C,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC/C,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,OAAmB;QAC/B,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACtD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAkB,CAAC;QAEzD,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;YACrB,KAAK,WAAW,CAAC,IAAI;gBACnB,OAAO,OAAsB,CAAC;YAChC,KAAK,WAAW,CAAC,IAAI;gBACnB,OAAO,OAAsB,CAAC;YAChC,KAAK,WAAW,CAAC,OAAO;gBACtB,OAAO,OAAyB,CAAC;YACnC,KAAK,WAAW,CAAC,IAAI;gBACnB,OAAO,OAAsB,CAAC;YAChC,KAAK,WAAW,CAAC,QAAQ;gBACvB,OAAO,OAA0B,CAAC;YACpC,KAAK,WAAW,CAAC,mBAAmB;gBAClC,OAAO,OAAmC,CAAC;YAC7C;gBACE,MAAM,IAAI,KAAK,CAAC,yBAAyB,OAAO,EAAE,CAAC,CAAC;QACxD,CAAC;IACH,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;OAEG;IACH,cAAc;QACZ,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;IAED;;OAEG;IACH,WAAW,CAAC,aAA4B;QACtC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/waku/constants.d.ts b/packages/core/dist/waku/constants.d.ts new file mode 100644 index 0000000..c852071 --- /dev/null +++ b/packages/core/dist/waku/constants.d.ts @@ -0,0 +1,13 @@ +/** + * Single content topic for all message types + * Different message types are parsed from the message content itself + */ +export declare const CONTENT_TOPIC = "/opchan-test-1/1/messages/proto"; +/** + * Bootstrap nodes for the Waku network + * These are public Waku nodes that our node will connect to on startup + */ +export declare const BOOTSTRAP_NODES: { + '42': string[]; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/waku/constants.d.ts.map b/packages/core/dist/waku/constants.d.ts.map new file mode 100644 index 0000000..b9c4321 --- /dev/null +++ b/packages/core/dist/waku/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/waku/constants.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,aAAa,oCAAoC,CAAC;AAE/D;;;GAGG;AACH,eAAO,MAAM,eAAe;;CAM3B,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/waku/constants.js b/packages/core/dist/waku/constants.js new file mode 100644 index 0000000..6825a3b --- /dev/null +++ b/packages/core/dist/waku/constants.js @@ -0,0 +1,17 @@ +/** + * Single content topic for all message types + * Different message types are parsed from the message content itself + */ +export const CONTENT_TOPIC = '/opchan-test-1/1/messages/proto'; +/** + * Bootstrap nodes for the Waku network + * These are public Waku nodes that our node will connect to on startup + */ +export const BOOTSTRAP_NODES = { + '42': [ + '/dns4/waku-test.bloxy.one/tcp/8095/wss/p2p/16Uiu2HAmSZbDB7CusdRhgkD81VssRjQV5ZH13FbzCGcdnbbh6VwZ', + '/dns4/node-01.do-ams3.waku.sandbox.status.im/tcp/30303/p2p/16Uiu2HAmNaeL4p3WEYzC9mgXBmBWSgWjPHRvatZTXnp8Jgv3iKsb', + '/dns4/vps-aaa00d52.vps.ovh.ca/tcp/8000/wss/p2p/16Uiu2HAm9PftGgHZwWE3wzdMde4m3kT2eYJFXLZfGoSED3gysofk', + ], +}; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/packages/core/dist/waku/constants.js.map b/packages/core/dist/waku/constants.js.map new file mode 100644 index 0000000..436f10d --- /dev/null +++ b/packages/core/dist/waku/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/waku/constants.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,iCAAiC,CAAC;AAE/D;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE;QACJ,kGAAkG;QAClG,kHAAkH;QAClH,sGAAsG;KACvG;CACF,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/waku/core/ReliableMessaging.d.ts b/packages/core/dist/waku/core/ReliableMessaging.d.ts new file mode 100644 index 0000000..d62aa5a --- /dev/null +++ b/packages/core/dist/waku/core/ReliableMessaging.d.ts @@ -0,0 +1,21 @@ +import { LightNode } from '@waku/sdk'; +import { OpchanMessage } from '../../types/forum'; +export interface MessageStatusCallback { + onSent?: (messageId: string) => void; + onAcknowledged?: (messageId: string) => void; + onError?: (messageId: string, error: string) => void; +} +export type IncomingMessageCallback = (message: OpchanMessage) => void; +export declare class ReliableMessaging { + private channel; + private messageCallbacks; + private incomingMessageCallbacks; + private codecManager; + constructor(node: LightNode); + private initializeChannel; + private setupChannelListeners; + sendMessage(message: OpchanMessage, statusCallback?: MessageStatusCallback): Promise; + onMessage(callback: IncomingMessageCallback): () => void; + cleanup(): void; +} +//# sourceMappingURL=ReliableMessaging.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/waku/core/ReliableMessaging.d.ts.map b/packages/core/dist/waku/core/ReliableMessaging.d.ts.map new file mode 100644 index 0000000..3e06fe7 --- /dev/null +++ b/packages/core/dist/waku/core/ReliableMessaging.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ReliableMessaging.d.ts","sourceRoot":"","sources":["../../../src/waku/core/ReliableMessaging.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,SAAS,EAGV,MAAM,WAAW,CAAC;AAGnB,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,MAAM,WAAW,qBAAqB;IACpC,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,cAAc,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7C,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;CACtD;AAED,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,CAAC;AAEvE,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,OAAO,CAAiD;IAChE,OAAO,CAAC,gBAAgB,CAAiD;IACzE,OAAO,CAAC,wBAAwB,CAA2C;IAC3E,OAAO,CAAC,YAAY,CAAe;gBAEvB,IAAI,EAAE,SAAS;YAKb,iBAAiB;IAoB/B,OAAO,CAAC,qBAAqB;IAmDhB,WAAW,CACtB,OAAO,EAAE,aAAa,EACtB,cAAc,CAAC,EAAE,qBAAqB,GACrC,OAAO,CAAC,IAAI,CAAC;IAoBT,SAAS,CAAC,QAAQ,EAAE,uBAAuB,GAAG,MAAM,IAAI;IAKxD,OAAO,IAAI,IAAI;CAKvB"} \ No newline at end of file diff --git a/packages/core/dist/waku/core/ReliableMessaging.js b/packages/core/dist/waku/core/ReliableMessaging.js new file mode 100644 index 0000000..8f7a3ab --- /dev/null +++ b/packages/core/dist/waku/core/ReliableMessaging.js @@ -0,0 +1,83 @@ +import { ReliableChannel, ReliableChannelEvent, } from '@waku/sdk'; +import { CodecManager } from '../CodecManager'; +import { generateStringId } from '../../utils'; +export class ReliableMessaging { + constructor(node) { + this.channel = null; + this.messageCallbacks = new Map(); + this.incomingMessageCallbacks = new Set(); + this.codecManager = new CodecManager(node); + this.initializeChannel(node); + } + async initializeChannel(node) { + const encoder = this.codecManager.getEncoder(); + const decoder = this.codecManager.getDecoder(); + const senderId = generateStringId(); + const channelId = 'opchan-messages'; + try { + this.channel = await ReliableChannel.create(node, channelId, senderId, encoder, decoder); + this.setupChannelListeners(this.channel); + } + catch (error) { + console.error('Failed to create reliable channel:', error); + } + } + setupChannelListeners(channel) { + channel.addEventListener(ReliableChannelEvent.InMessageReceived, (event) => { + try { + const wakuMessage = event.detail; + if (wakuMessage.payload) { + const opchanMessage = this.codecManager.decodeMessage(wakuMessage.payload); + this.incomingMessageCallbacks.forEach((callback) => callback(opchanMessage)); + } + } + catch (error) { + console.error('Failed to process incoming message:', error); + } + }); + channel.addEventListener(ReliableChannelEvent.OutMessageSent, (event) => { + const messageId = event.detail; + this.messageCallbacks.get(messageId)?.onSent?.(messageId); + }); + channel.addEventListener(ReliableChannelEvent.OutMessageAcknowledged, (event) => { + const messageId = event.detail; + this.messageCallbacks.get(messageId)?.onAcknowledged?.(messageId); + }); + channel.addEventListener(ReliableChannelEvent.OutMessageIrrecoverableError, (event) => { + const messageId = event.detail.messageId; + const error = event.detail.error; + const callback = this.messageCallbacks.get(messageId); + if (callback?.onError) { + callback.onError(messageId, error?.toString() || 'Unknown error'); + } + this.messageCallbacks.delete(messageId); + }); + } + async sendMessage(message, statusCallback) { + if (!this.channel) { + throw new Error('Reliable channel not initialized'); + } + const encodedMessage = this.codecManager.encodeMessage(message); + const messageId = ReliableChannel.getMessageId(encodedMessage); + if (statusCallback) { + this.messageCallbacks.set(messageId, statusCallback); + } + try { + return this.channel.send(encodedMessage); + } + catch (error) { + this.messageCallbacks.delete(messageId); + throw error; + } + } + onMessage(callback) { + this.incomingMessageCallbacks.add(callback); + return () => this.incomingMessageCallbacks.delete(callback); + } + cleanup() { + this.messageCallbacks.clear(); + this.incomingMessageCallbacks.clear(); + this.channel = null; + } +} +//# sourceMappingURL=ReliableMessaging.js.map \ No newline at end of file diff --git a/packages/core/dist/waku/core/ReliableMessaging.js.map b/packages/core/dist/waku/core/ReliableMessaging.js.map new file mode 100644 index 0000000..5d5bedc --- /dev/null +++ b/packages/core/dist/waku/core/ReliableMessaging.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ReliableMessaging.js","sourceRoot":"","sources":["../../../src/waku/core/ReliableMessaging.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,eAAe,EACf,oBAAoB,GACrB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAW/C,MAAM,OAAO,iBAAiB;IAM5B,YAAY,IAAe;QALnB,YAAO,GAA4C,IAAI,CAAC;QACxD,qBAAgB,GAAuC,IAAI,GAAG,EAAE,CAAC;QACjE,6BAAwB,GAAiC,IAAI,GAAG,EAAE,CAAC;QAIzE,IAAI,CAAC,YAAY,GAAG,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC;QAC3C,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAEO,KAAK,CAAC,iBAAiB,CAAC,IAAe;QAC7C,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,UAAU,EAAE,CAAC;QAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,UAAU,EAAE,CAAC;QAC/C,MAAM,QAAQ,GAAG,gBAAgB,EAAE,CAAC;QACpC,MAAM,SAAS,GAAG,iBAAiB,CAAC;QAEpC,IAAI,CAAC;YACH,IAAI,CAAC,OAAO,GAAG,MAAM,eAAe,CAAC,MAAM,CACzC,IAAI,EACJ,SAAS,EACT,QAAQ,EACR,OAAO,EACP,OAAO,CACR,CAAC;YACF,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC3C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;QAC7D,CAAC;IACH,CAAC;IAEO,qBAAqB,CAC3B,OAAyC;QAEzC,OAAO,CAAC,gBAAgB,CACtB,oBAAoB,CAAC,iBAAiB,EACtC,CAAC,KAAK,EAAE,EAAE;YACR,IAAI,CAAC;gBACH,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC;gBACjC,IAAI,WAAW,CAAC,OAAO,EAAE,CAAC;oBACxB,MAAM,aAAa,GAAG,IAAI,CAAC,YAAY,CAAC,aAAa,CACnD,WAAW,CAAC,OAAO,CACpB,CAAC;oBACF,IAAI,CAAC,wBAAwB,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CACjD,QAAQ,CAAC,aAAa,CAAC,CACxB,CAAC;gBACJ,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;YAC9D,CAAC;QACH,CAAC,CACF,CAAC;QAEF,OAAO,CAAC,gBAAgB,CAAC,oBAAoB,CAAC,cAAc,EAAE,CAAC,KAAK,EAAE,EAAE;YACtE,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC;YAC/B,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5D,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,gBAAgB,CACtB,oBAAoB,CAAC,sBAAsB,EAC3C,CAAC,KAAK,EAAE,EAAE;YACR,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC;YAC/B,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,cAAc,EAAE,CAAC,SAAS,CAAC,CAAC;QACpE,CAAC,CACF,CAAC;QAEF,OAAO,CAAC,gBAAgB,CACtB,oBAAoB,CAAC,4BAA4B,EACjD,CAAC,KAAK,EAAE,EAAE;YACR,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC;YACzC,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC;YACjC,MAAM,QAAQ,GAAG,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;YAEtD,IAAI,QAAQ,EAAE,OAAO,EAAE,CAAC;gBACtB,QAAQ,CAAC,OAAO,CAAC,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,eAAe,CAAC,CAAC;YACpE,CAAC;YAED,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC1C,CAAC,CACF,CAAC;IACJ,CAAC;IAEM,KAAK,CAAC,WAAW,CACtB,OAAsB,EACtB,cAAsC;QAEtC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;QACtD,CAAC;QAED,MAAM,cAAc,GAAG,IAAI,CAAC,YAAY,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QAChE,MAAM,SAAS,GAAG,eAAe,CAAC,YAAY,CAAC,cAAc,CAAC,CAAC;QAE/D,IAAI,cAAc,EAAE,CAAC;YACnB,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;QACvD,CAAC;QAED,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAC3C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;YACxC,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAEM,SAAS,CAAC,QAAiC;QAChD,IAAI,CAAC,wBAAwB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC5C,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC9D,CAAC;IAEM,OAAO;QACZ,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,CAAC;QAC9B,IAAI,CAAC,wBAAwB,CAAC,KAAK,EAAE,CAAC;QACtC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;IACtB,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/waku/core/WakuNodeManager.d.ts b/packages/core/dist/waku/core/WakuNodeManager.d.ts new file mode 100644 index 0000000..d27c6c1 --- /dev/null +++ b/packages/core/dist/waku/core/WakuNodeManager.d.ts @@ -0,0 +1,19 @@ +import { LightNode, HealthStatus } from '@waku/sdk'; +export type HealthChangeCallback = (isReady: boolean, health: HealthStatus) => void; +export declare class WakuNodeManager { + private node; + private _isReady; + private _currentHealth; + private healthListeners; + static create(): Promise; + private initialize; + private setupHealthMonitoring; + private notifyHealthChange; + getNode(): LightNode; + stop(): Promise; + get isInitialized(): boolean; + get isReady(): boolean; + get currentHealth(): HealthStatus; + onHealthChange(callback: HealthChangeCallback): () => void; +} +//# sourceMappingURL=WakuNodeManager.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/waku/core/WakuNodeManager.d.ts.map b/packages/core/dist/waku/core/WakuNodeManager.d.ts.map new file mode 100644 index 0000000..d2bcddf --- /dev/null +++ b/packages/core/dist/waku/core/WakuNodeManager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WakuNodeManager.d.ts","sourceRoot":"","sources":["../../../src/waku/core/WakuNodeManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,SAAS,EAAa,YAAY,EAAE,MAAM,WAAW,CAAC;AAEhF,MAAM,MAAM,oBAAoB,GAAG,CACjC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,YAAY,KACjB,IAAI,CAAC;AAEV,qBAAa,eAAe;IAC1B,OAAO,CAAC,IAAI,CAA0B;IACtC,OAAO,CAAC,QAAQ,CAAkB;IAClC,OAAO,CAAC,cAAc,CAAwC;IAC9D,OAAO,CAAC,eAAe,CAAwC;WAE3C,MAAM,IAAI,OAAO,CAAC,eAAe,CAAC;YAMxC,UAAU;IAQxB,OAAO,CAAC,qBAAqB;IAsB7B,OAAO,CAAC,kBAAkB;IAMnB,OAAO,IAAI,SAAS;IAOd,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAQlC,IAAW,aAAa,IAAI,OAAO,CAElC;IAED,IAAW,OAAO,IAAI,OAAO,CAE5B;IAED,IAAW,aAAa,IAAI,YAAY,CAEvC;IAEM,cAAc,CAAC,QAAQ,EAAE,oBAAoB,GAAG,MAAM,IAAI;CAWlE"} \ No newline at end of file diff --git a/packages/core/dist/waku/core/WakuNodeManager.js b/packages/core/dist/waku/core/WakuNodeManager.js new file mode 100644 index 0000000..c2c344a --- /dev/null +++ b/packages/core/dist/waku/core/WakuNodeManager.js @@ -0,0 +1,74 @@ +import { createLightNode, WakuEvent, HealthStatus } from '@waku/sdk'; +export class WakuNodeManager { + constructor() { + this.node = null; + this._isReady = false; + this._currentHealth = HealthStatus.Unhealthy; + this.healthListeners = new Set(); + } + static async create() { + const manager = new WakuNodeManager(); + await manager.initialize(); + return manager; + } + async initialize() { + this.node = await createLightNode({ + defaultBootstrap: true, + autoStart: true, + }); + this.setupHealthMonitoring(); + } + setupHealthMonitoring() { + if (!this.node) + return; + this.node.events.addEventListener(WakuEvent.Health, (event) => { + const health = event.detail; + this._currentHealth = health; + if (process.env.NODE_ENV === 'development') { + console.debug(`Waku health status: ${health}`); + } + const wasReady = this._isReady; + this._isReady = + health === HealthStatus.SufficientlyHealthy || + health === HealthStatus.MinimallyHealthy; + if (wasReady !== this._isReady) { + this.notifyHealthChange(); + } + }); + } + notifyHealthChange() { + this.healthListeners.forEach((listener) => listener(this._isReady, this._currentHealth)); + } + getNode() { + if (!this.node) { + throw new Error('Node not initialized'); + } + return this.node; + } + async stop() { + this.healthListeners.clear(); + if (this.node) { + await this.node.stop(); + this.node = null; + } + } + get isInitialized() { + return this.node !== null; + } + get isReady() { + return this._isReady; + } + get currentHealth() { + return this._currentHealth; + } + onHealthChange(callback) { + this.healthListeners.add(callback); + // Immediately call with current status + callback(this._isReady, this._currentHealth); + // Return unsubscribe function + return () => { + this.healthListeners.delete(callback); + }; + } +} +//# sourceMappingURL=WakuNodeManager.js.map \ No newline at end of file diff --git a/packages/core/dist/waku/core/WakuNodeManager.js.map b/packages/core/dist/waku/core/WakuNodeManager.js.map new file mode 100644 index 0000000..6377605 --- /dev/null +++ b/packages/core/dist/waku/core/WakuNodeManager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WakuNodeManager.js","sourceRoot":"","sources":["../../../src/waku/core/WakuNodeManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAa,SAAS,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAOhF,MAAM,OAAO,eAAe;IAA5B;QACU,SAAI,GAAqB,IAAI,CAAC;QAC9B,aAAQ,GAAY,KAAK,CAAC;QAC1B,mBAAc,GAAiB,YAAY,CAAC,SAAS,CAAC;QACtD,oBAAe,GAA8B,IAAI,GAAG,EAAE,CAAC;IAkFjE,CAAC;IAhFQ,MAAM,CAAC,KAAK,CAAC,MAAM;QACxB,MAAM,OAAO,GAAG,IAAI,eAAe,EAAE,CAAC;QACtC,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC;QAC3B,OAAO,OAAO,CAAC;IACjB,CAAC;IAEO,KAAK,CAAC,UAAU;QACtB,IAAI,CAAC,IAAI,GAAG,MAAM,eAAe,CAAC;YAChC,gBAAgB,EAAE,IAAI;YACtB,SAAS,EAAE,IAAI;SAChB,CAAC,CAAC;QACH,IAAI,CAAC,qBAAqB,EAAE,CAAC;IAC/B,CAAC;IAEO,qBAAqB;QAC3B,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,OAAO;QAEvB,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;YAC5D,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;YAC5B,IAAI,CAAC,cAAc,GAAG,MAAM,CAAC;YAE7B,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;gBAC3C,OAAO,CAAC,KAAK,CAAC,uBAAuB,MAAM,EAAE,CAAC,CAAC;YACjD,CAAC;YAED,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;YAC/B,IAAI,CAAC,QAAQ;gBACX,MAAM,KAAK,YAAY,CAAC,mBAAmB;oBAC3C,MAAM,KAAK,YAAY,CAAC,gBAAgB,CAAC;YAE3C,IAAI,QAAQ,KAAK,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAC/B,IAAI,CAAC,kBAAkB,EAAE,CAAC;YAC5B,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,kBAAkB;QACxB,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CACxC,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,cAAc,CAAC,CAC7C,CAAC;IACJ,CAAC;IAEM,OAAO;QACZ,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;QAC1C,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAEM,KAAK,CAAC,IAAI;QACf,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACd,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACnB,CAAC;IACH,CAAC;IAED,IAAW,aAAa;QACtB,OAAO,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC;IAC5B,CAAC;IAED,IAAW,OAAO;QAChB,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,IAAW,aAAa;QACtB,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;IAEM,cAAc,CAAC,QAA8B;QAClD,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAEnC,uCAAuC;QACvC,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;QAE7C,8BAA8B;QAC9B,OAAO,GAAG,EAAE;YACV,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACxC,CAAC,CAAC;IACJ,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/waku/index.d.ts b/packages/core/dist/waku/index.d.ts new file mode 100644 index 0000000..013f54d --- /dev/null +++ b/packages/core/dist/waku/index.d.ts @@ -0,0 +1,25 @@ +import { HealthStatus } from '@waku/sdk'; +import { OpchanMessage } from '../types/forum'; +import { HealthChangeCallback } from './core/WakuNodeManager'; +import { MessageStatusCallback } from './services/MessageService'; +export type { HealthChangeCallback, MessageStatusCallback }; +declare class MessageManager { + private nodeManager; + private messageService; + private reliableMessaging; + constructor(); + static create(): Promise; + private initialize; + private initializeReliableMessaging; + private cleanupReliableMessaging; + stop(): Promise; + get isReady(): boolean; + get currentHealth(): HealthStatus; + onHealthChange(callback: HealthChangeCallback): () => void; + sendMessage(message: OpchanMessage, statusCallback?: MessageStatusCallback): Promise; + onMessageReceived(callback: (message: OpchanMessage) => void): () => void; + get messageCache(): import("../database/LocalDatabase").LocalDatabaseCache; +} +declare const messageManager: MessageManager; +export default messageManager; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/waku/index.d.ts.map b/packages/core/dist/waku/index.d.ts.map new file mode 100644 index 0000000..04f4765 --- /dev/null +++ b/packages/core/dist/waku/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/waku/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAmB,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAEL,qBAAqB,EACtB,MAAM,2BAA2B,CAAC;AAGnC,YAAY,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,CAAC;AAE5D,cAAM,cAAc;IAClB,OAAO,CAAC,WAAW,CAAgC;IAEnD,OAAO,CAAC,cAAc,CAA+B;IACrD,OAAO,CAAC,iBAAiB,CAAkC;;WAIvC,MAAM,IAAI,OAAO,CAAC,cAAc,CAAC;YAMvC,UAAU;YAwBV,2BAA2B;IAiBzC,OAAO,CAAC,wBAAwB;IASnB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAMlC,IAAW,OAAO,IAAI,OAAO,CAE5B;IAED,IAAW,aAAa,IAAI,YAAY,CAEvC;IAEM,cAAc,CAAC,QAAQ,EAAE,oBAAoB,GAAG,MAAM,IAAI;IAQpD,WAAW,CACtB,OAAO,EAAE,aAAa,EACtB,cAAc,CAAC,EAAE,qBAAqB,GACrC,OAAO,CAAC,IAAI,CAAC;IAOT,iBAAiB,CACtB,QAAQ,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,GACzC,MAAM,IAAI;IAOb,IAAW,YAAY,2DAKtB;CACF;AAED,QAAA,MAAM,cAAc,gBAAgC,CAAC;AACrD,eAAe,cAAc,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/waku/index.js b/packages/core/dist/waku/index.js new file mode 100644 index 0000000..9f82c33 --- /dev/null +++ b/packages/core/dist/waku/index.js @@ -0,0 +1,98 @@ +import { HealthStatus } from '@waku/sdk'; +import { WakuNodeManager } from './core/WakuNodeManager'; +import { MessageService, } from './services/MessageService'; +import { ReliableMessaging } from './core/ReliableMessaging'; +class MessageManager { + constructor() { + this.nodeManager = null; + // LocalDatabase eliminates the need for CacheService + this.messageService = null; + this.reliableMessaging = null; + } + static async create() { + const manager = new MessageManager(); + await manager.initialize(); + return manager; + } + async initialize() { + try { + this.nodeManager = await WakuNodeManager.create(); + // Now create message service with proper dependencies + this.messageService = new MessageService(this.reliableMessaging, this.nodeManager); + // Set up health-based reliable messaging initialization + this.nodeManager.onHealthChange((isReady) => { + if (isReady && !this.reliableMessaging) { + this.initializeReliableMessaging(); + } + else if (!isReady && this.reliableMessaging) { + this.cleanupReliableMessaging(); + } + }); + } + catch (error) { + console.error('Failed to initialize MessageManager:', error); + throw error; + } + } + async initializeReliableMessaging() { + if (!this.nodeManager || this.reliableMessaging) { + return; + } + try { + console.log('Initializing reliable messaging...'); + this.reliableMessaging = new ReliableMessaging(this.nodeManager.getNode()); + this.messageService?.updateReliableMessaging(this.reliableMessaging); + console.log('Reliable messaging initialized successfully'); + } + catch (error) { + console.error('Failed to initialize reliable messaging:', error); + } + } + cleanupReliableMessaging() { + if (this.reliableMessaging) { + console.log('Cleaning up reliable messaging due to health status'); + this.reliableMessaging.cleanup(); + this.reliableMessaging = null; + this.messageService?.updateReliableMessaging(null); + } + } + async stop() { + this.cleanupReliableMessaging(); + this.messageService?.cleanup(); + await this.nodeManager?.stop(); + } + get isReady() { + return this.nodeManager?.isReady ?? false; + } + get currentHealth() { + return this.nodeManager?.currentHealth ?? HealthStatus.Unhealthy; + } + onHealthChange(callback) { + if (!this.nodeManager) { + throw new Error('Node manager not initialized'); + } + return this.nodeManager.onHealthChange(callback); + } + //TODO: return event handlers? + async sendMessage(message, statusCallback) { + if (!this.messageService) { + throw new Error('MessageManager not fully initialized'); + } + this.messageService.sendMessage(message, statusCallback); + } + onMessageReceived(callback) { + if (!this.messageService) { + throw new Error('MessageManager not fully initialized'); + } + return this.messageService.onMessageReceived(callback); + } + get messageCache() { + if (!this.messageService) { + throw new Error('MessageManager not fully initialized'); + } + return this.messageService.messageCache; + } +} +const messageManager = await MessageManager.create(); +export default messageManager; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/core/dist/waku/index.js.map b/packages/core/dist/waku/index.js.map new file mode 100644 index 0000000..c8d103b --- /dev/null +++ b/packages/core/dist/waku/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/waku/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,EAAE,eAAe,EAAwB,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EACL,cAAc,GAEf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAI7D,MAAM,cAAc;IAMlB;QALQ,gBAAW,GAA2B,IAAI,CAAC;QACnD,qDAAqD;QAC7C,mBAAc,GAA0B,IAAI,CAAC;QAC7C,sBAAiB,GAA6B,IAAI,CAAC;IAE5C,CAAC;IAET,MAAM,CAAC,KAAK,CAAC,MAAM;QACxB,MAAM,OAAO,GAAG,IAAI,cAAc,EAAE,CAAC;QACrC,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC;QAC3B,OAAO,OAAO,CAAC;IACjB,CAAC;IAEO,KAAK,CAAC,UAAU;QACtB,IAAI,CAAC;YACH,IAAI,CAAC,WAAW,GAAG,MAAM,eAAe,CAAC,MAAM,EAAE,CAAC;YAElD,sDAAsD;YACtD,IAAI,CAAC,cAAc,GAAG,IAAI,cAAc,CACtC,IAAI,CAAC,iBAAiB,EACtB,IAAI,CAAC,WAAW,CACjB,CAAC;YAEF,wDAAwD;YACxD,IAAI,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC,OAAO,EAAE,EAAE;gBAC1C,IAAI,OAAO,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC;oBACvC,IAAI,CAAC,2BAA2B,EAAE,CAAC;gBACrC,CAAC;qBAAM,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;oBAC9C,IAAI,CAAC,wBAAwB,EAAE,CAAC;gBAClC,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,sCAAsC,EAAE,KAAK,CAAC,CAAC;YAC7D,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,2BAA2B;QACvC,IAAI,CAAC,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAChD,OAAO;QACT,CAAC;QAED,IAAI,CAAC;YACH,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;YAClD,IAAI,CAAC,iBAAiB,GAAG,IAAI,iBAAiB,CAC5C,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAC3B,CAAC;YACF,IAAI,CAAC,cAAc,EAAE,uBAAuB,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;YACrE,OAAO,CAAC,GAAG,CAAC,6CAA6C,CAAC,CAAC;QAC7D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,0CAA0C,EAAE,KAAK,CAAC,CAAC;QACnE,CAAC;IACH,CAAC;IAEO,wBAAwB;QAC9B,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC3B,OAAO,CAAC,GAAG,CAAC,qDAAqD,CAAC,CAAC;YACnE,IAAI,CAAC,iBAAiB,CAAC,OAAO,EAAE,CAAC;YACjC,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;YAC9B,IAAI,CAAC,cAAc,EAAE,uBAAuB,CAAC,IAAI,CAAC,CAAC;QACrD,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,IAAI;QACf,IAAI,CAAC,wBAAwB,EAAE,CAAC;QAChC,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CAAC;QAC/B,MAAM,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;IACjC,CAAC;IAED,IAAW,OAAO;QAChB,OAAO,IAAI,CAAC,WAAW,EAAE,OAAO,IAAI,KAAK,CAAC;IAC5C,CAAC;IAED,IAAW,aAAa;QACtB,OAAO,IAAI,CAAC,WAAW,EAAE,aAAa,IAAI,YAAY,CAAC,SAAS,CAAC;IACnE,CAAC;IAEM,cAAc,CAAC,QAA8B;QAClD,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;QAClD,CAAC;QACD,OAAO,IAAI,CAAC,WAAW,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;IACnD,CAAC;IAED,8BAA8B;IACvB,KAAK,CAAC,WAAW,CACtB,OAAsB,EACtB,cAAsC;QAEtC,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QAC1D,CAAC;QACD,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;IAC3D,CAAC;IAEM,iBAAiB,CACtB,QAA0C;QAE1C,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAC;IACzD,CAAC;IAED,IAAW,YAAY;QACrB,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC,YAAY,CAAC;IAC1C,CAAC;CACF;AAED,MAAM,cAAc,GAAG,MAAM,cAAc,CAAC,MAAM,EAAE,CAAC;AACrD,eAAe,cAAc,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/waku/network.d.ts b/packages/core/dist/waku/network.d.ts new file mode 100644 index 0000000..abd3c71 --- /dev/null +++ b/packages/core/dist/waku/network.d.ts @@ -0,0 +1,11 @@ +export type ToastFunction = (props: { + title: string; + description: string; + variant?: 'default' | 'destructive'; +}) => void; +export declare const refreshData: (isNetworkConnected: boolean, toast: ToastFunction, updateStateFromCache: () => void, setError: (error: string | null) => void) => Promise; +export declare const initializeNetwork: (toast: ToastFunction, setError: (error: string | null) => void) => Promise; +export declare const monitorNetworkHealth: (setIsNetworkConnected: (isConnected: boolean) => void, toast: ToastFunction) => { + unsubscribe: () => void; +}; +//# sourceMappingURL=network.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/waku/network.d.ts.map b/packages/core/dist/waku/network.d.ts.map new file mode 100644 index 0000000..d72db0e --- /dev/null +++ b/packages/core/dist/waku/network.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"network.d.ts","sourceRoot":"","sources":["../../src/waku/network.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,SAAS,GAAG,aAAa,CAAC;CACrC,KAAK,IAAI,CAAC;AAEX,eAAO,MAAM,WAAW,GACtB,oBAAoB,OAAO,EAC3B,OAAO,aAAa,EACpB,sBAAsB,MAAM,IAAI,EAChC,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,KAAK,IAAI,KACvC,OAAO,CAAC,IAAI,CA+Bd,CAAC;AAEF,eAAO,MAAM,iBAAiB,GAC5B,OAAO,aAAa,EACpB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,KAAK,IAAI,KACvC,OAAO,CAAC,IAAI,CA8Bd,CAAC;AAEF,eAAO,MAAM,oBAAoB,GAC/B,uBAAuB,CAAC,WAAW,EAAE,OAAO,KAAK,IAAI,EACrD,OAAO,aAAa,KACnB;IAAE,WAAW,EAAE,MAAM,IAAI,CAAA;CA0B3B,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/waku/network.js b/packages/core/dist/waku/network.js new file mode 100644 index 0000000..a7a8b44 --- /dev/null +++ b/packages/core/dist/waku/network.js @@ -0,0 +1,91 @@ +import messageManager from './index'; +import { HealthStatus } from '@waku/sdk'; +export const refreshData = async (isNetworkConnected, toast, updateStateFromCache, setError) => { + try { + toast({ + title: 'Refreshing data', + description: 'SDS handles message syncing automatically...', + }); + if (!isNetworkConnected) { + toast({ + title: 'Network disconnected', + description: 'Unable to refresh data. Please wait for network connection to be restored.', + variant: 'destructive', + }); + return; + } + updateStateFromCache(); + toast({ + title: 'Data refreshed', + description: 'Your view has been updated with the latest messages.', + }); + } + catch (err) { + console.error('Error refreshing data:', err); + toast({ + title: 'Refresh failed', + description: 'Could not sync with network. Please try again.', + variant: 'destructive', + }); + setError('Failed to refresh data. Please try again later.'); + } +}; +export const initializeNetwork = async (toast, setError) => { + try { + toast({ + title: 'Loading data', + description: 'Connecting to the Waku network...', + }); + // Check current network status and provide appropriate feedback + if (messageManager.isReady) { + toast({ + title: 'Connected', + description: 'Successfully connected to Waku network.', + }); + } + else { + toast({ + title: 'Connecting...', + description: 'Establishing network connection. You can view cached data while we connect.', + variant: 'default', + }); + } + } + catch (err) { + console.error('Error loading forum data:', err); + setError('Failed to load forum data. Please try again later.'); + toast({ + title: 'Load error', + description: 'Failed to load forum data. Please try refreshing.', + variant: 'destructive', + }); + } +}; +export const monitorNetworkHealth = (setIsNetworkConnected, toast) => { + setIsNetworkConnected(messageManager.isReady); + const unsubscribe = messageManager.onHealthChange((isReady, health) => { + setIsNetworkConnected(isReady); + if (health === HealthStatus.SufficientlyHealthy) { + toast({ + title: 'Network connected', + description: 'Connected to the Waku network with excellent connectivity', + }); + } + else if (health === HealthStatus.MinimallyHealthy) { + toast({ + title: 'Network connected', + description: 'Connected to Waku network. Some features may be limited.', + variant: 'default', + }); + } + else { + toast({ + title: 'Network disconnected', + description: 'Lost connection to the Waku network', + variant: 'destructive', + }); + } + }); + return { unsubscribe }; +}; +//# sourceMappingURL=network.js.map \ No newline at end of file diff --git a/packages/core/dist/waku/network.js.map b/packages/core/dist/waku/network.js.map new file mode 100644 index 0000000..30cc2df --- /dev/null +++ b/packages/core/dist/waku/network.js.map @@ -0,0 +1 @@ +{"version":3,"file":"network.js","sourceRoot":"","sources":["../../src/waku/network.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAQzC,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAC9B,kBAA2B,EAC3B,KAAoB,EACpB,oBAAgC,EAChC,QAAwC,EACzB,EAAE;IACjB,IAAI,CAAC;QACH,KAAK,CAAC;YACJ,KAAK,EAAE,iBAAiB;YACxB,WAAW,EAAE,8CAA8C;SAC5D,CAAC,CAAC;QAEH,IAAI,CAAC,kBAAkB,EAAE,CAAC;YACxB,KAAK,CAAC;gBACJ,KAAK,EAAE,sBAAsB;gBAC7B,WAAW,EACT,4EAA4E;gBAC9E,OAAO,EAAE,aAAa;aACvB,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QAED,oBAAoB,EAAE,CAAC;QACvB,KAAK,CAAC;YACJ,KAAK,EAAE,gBAAgB;YACvB,WAAW,EAAE,sDAAsD;SACpE,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,GAAG,CAAC,CAAC;QAC7C,KAAK,CAAC;YACJ,KAAK,EAAE,gBAAgB;YACvB,WAAW,EAAE,gDAAgD;YAC7D,OAAO,EAAE,aAAa;SACvB,CAAC,CAAC;QACH,QAAQ,CAAC,iDAAiD,CAAC,CAAC;IAC9D,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,EACpC,KAAoB,EACpB,QAAwC,EACzB,EAAE;IACjB,IAAI,CAAC;QACH,KAAK,CAAC;YACJ,KAAK,EAAE,cAAc;YACrB,WAAW,EAAE,mCAAmC;SACjD,CAAC,CAAC;QAEH,gEAAgE;QAChE,IAAI,cAAc,CAAC,OAAO,EAAE,CAAC;YAC3B,KAAK,CAAC;gBACJ,KAAK,EAAE,WAAW;gBAClB,WAAW,EAAE,yCAAyC;aACvD,CAAC,CAAC;QACL,CAAC;aAAM,CAAC;YACN,KAAK,CAAC;gBACJ,KAAK,EAAE,eAAe;gBACtB,WAAW,EACT,6EAA6E;gBAC/E,OAAO,EAAE,SAAS;aACnB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,GAAG,CAAC,CAAC;QAChD,QAAQ,CAAC,oDAAoD,CAAC,CAAC;QAC/D,KAAK,CAAC;YACJ,KAAK,EAAE,YAAY;YACnB,WAAW,EAAE,mDAAmD;YAChE,OAAO,EAAE,aAAa;SACvB,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,qBAAqD,EACrD,KAAoB,EACS,EAAE;IAC/B,qBAAqB,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;IAC9C,MAAM,WAAW,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACpE,qBAAqB,CAAC,OAAO,CAAC,CAAC;QAE/B,IAAI,MAAM,KAAK,YAAY,CAAC,mBAAmB,EAAE,CAAC;YAChD,KAAK,CAAC;gBACJ,KAAK,EAAE,mBAAmB;gBAC1B,WAAW,EACT,2DAA2D;aAC9D,CAAC,CAAC;QACL,CAAC;aAAM,IAAI,MAAM,KAAK,YAAY,CAAC,gBAAgB,EAAE,CAAC;YACpD,KAAK,CAAC;gBACJ,KAAK,EAAE,mBAAmB;gBAC1B,WAAW,EAAE,0DAA0D;gBACvE,OAAO,EAAE,SAAS;aACnB,CAAC,CAAC;QACL,CAAC;aAAM,CAAC;YACN,KAAK,CAAC;gBACJ,KAAK,EAAE,sBAAsB;gBAC7B,WAAW,EAAE,qCAAqC;gBAClD,OAAO,EAAE,aAAa;aACvB,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,WAAW,EAAE,CAAC;AACzB,CAAC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/waku/services/MessageService.d.ts b/packages/core/dist/waku/services/MessageService.d.ts new file mode 100644 index 0000000..26b4a19 --- /dev/null +++ b/packages/core/dist/waku/services/MessageService.d.ts @@ -0,0 +1,22 @@ +import { OpchanMessage } from '../../types/forum'; +import { ReliableMessaging, MessageStatusCallback } from '../core/ReliableMessaging'; +import { WakuNodeManager } from '../core/WakuNodeManager'; +export type MessageReceivedCallback = (message: OpchanMessage) => void; +export type { MessageStatusCallback }; +export declare class MessageService { + private reliableMessaging; + private nodeManager; + private messageReceivedCallbacks; + constructor(reliableMessaging: ReliableMessaging | null, nodeManager: WakuNodeManager); + private setupMessageHandling; + sendMessage(message: OpchanMessage, statusCallback?: MessageStatusCallback): Promise<{ + success: boolean; + message?: OpchanMessage; + error?: string; + }>; + onMessageReceived(callback: MessageReceivedCallback): () => void; + updateReliableMessaging(reliableMessaging: ReliableMessaging | null): void; + get messageCache(): import("../../database/LocalDatabase").LocalDatabaseCache; + cleanup(): void; +} +//# sourceMappingURL=MessageService.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/waku/services/MessageService.d.ts.map b/packages/core/dist/waku/services/MessageService.d.ts.map new file mode 100644 index 0000000..f7fd788 --- /dev/null +++ b/packages/core/dist/waku/services/MessageService.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"MessageService.d.ts","sourceRoot":"","sources":["../../../src/waku/services/MessageService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EACtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAG1D,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,CAAC;AACvE,YAAY,EAAE,qBAAqB,EAAE,CAAC;AAEtC,qBAAa,cAAc;IAIvB,OAAO,CAAC,iBAAiB;IACzB,OAAO,CAAC,WAAW;IAJrB,OAAO,CAAC,wBAAwB,CAA2C;gBAGjE,iBAAiB,EAAE,iBAAiB,GAAG,IAAI,EAC3C,WAAW,EAAE,eAAe;IAKtC,OAAO,CAAC,oBAAoB;IAaf,WAAW,CACtB,OAAO,EAAE,aAAa,EACtB,cAAc,CAAC,EAAE,qBAAqB,GACrC,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,aAAa,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IA8ClE,iBAAiB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,MAAM,IAAI;IAKhE,uBAAuB,CAC5B,iBAAiB,EAAE,iBAAiB,GAAG,IAAI,GAC1C,IAAI;IAKP,IAAW,YAAY,8DAEtB;IAEM,OAAO,IAAI,IAAI;CAIvB"} \ No newline at end of file diff --git a/packages/core/dist/waku/services/MessageService.js b/packages/core/dist/waku/services/MessageService.js new file mode 100644 index 0000000..ec77931 --- /dev/null +++ b/packages/core/dist/waku/services/MessageService.js @@ -0,0 +1,80 @@ +import { localDatabase } from '../../database/LocalDatabase'; +export class MessageService { + constructor(reliableMessaging, nodeManager) { + this.reliableMessaging = reliableMessaging; + this.nodeManager = nodeManager; + this.messageReceivedCallbacks = new Set(); + this.setupMessageHandling(); + } + setupMessageHandling() { + if (this.reliableMessaging) { + this.reliableMessaging.onMessage(async (message) => { + localDatabase.setSyncing(true); + const isNew = await localDatabase.updateCache(message); + // Defensive: clear pending on inbound message to avoid stuck state + localDatabase.clearPending(message.id); + localDatabase.setSyncing(false); + if (isNew) + this.messageReceivedCallbacks.forEach((cb) => cb(message)); + }); + } + } + async sendMessage(message, statusCallback) { + if (!this.reliableMessaging) { + return { success: false, error: 'Reliable messaging not initialized' }; + } + if (!this.nodeManager.isReady) { + return { success: false, error: 'Network not ready' }; + } + try { + // Update cache optimistically + await localDatabase.updateCache(message); + localDatabase.markPending(message.id); + // Send via reliable messaging with status tracking + localDatabase.setSyncing(true); + await this.reliableMessaging.sendMessage(message, { + onSent: (id) => { + console.log(`Message ${id} sent`); + statusCallback?.onSent?.(id); + }, + onAcknowledged: (id) => { + console.log(`Message ${id} acknowledged`); + statusCallback?.onAcknowledged?.(id); + localDatabase.clearPending(message.id); + localDatabase.updateLastSync(Date.now()); + localDatabase.setSyncing(false); + }, + onError: (id, error) => { + console.error(`Message ${id} failed:`, error); + statusCallback?.onError?.(id, error); + // Keep pending entry to allow retry logic later + localDatabase.setSyncing(false); + }, + }); + return { success: true, message }; + } + catch (error) { + console.error('Error sending message:', error); + return { + success: false, + error: error instanceof Error ? error.message : 'Unknown error', + }; + } + } + onMessageReceived(callback) { + this.messageReceivedCallbacks.add(callback); + return () => this.messageReceivedCallbacks.delete(callback); + } + updateReliableMessaging(reliableMessaging) { + this.reliableMessaging = reliableMessaging; + this.setupMessageHandling(); + } + get messageCache() { + return localDatabase.cache; + } + cleanup() { + this.messageReceivedCallbacks.clear(); + this.reliableMessaging?.cleanup(); + } +} +//# sourceMappingURL=MessageService.js.map \ No newline at end of file diff --git a/packages/core/dist/waku/services/MessageService.js.map b/packages/core/dist/waku/services/MessageService.js.map new file mode 100644 index 0000000..b23f83f --- /dev/null +++ b/packages/core/dist/waku/services/MessageService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MessageService.js","sourceRoot":"","sources":["../../../src/waku/services/MessageService.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAK7D,MAAM,OAAO,cAAc;IAGzB,YACU,iBAA2C,EAC3C,WAA4B;QAD5B,sBAAiB,GAAjB,iBAAiB,CAA0B;QAC3C,gBAAW,GAAX,WAAW,CAAiB;QAJ9B,6BAAwB,GAAiC,IAAI,GAAG,EAAE,CAAC;QAMzE,IAAI,CAAC,oBAAoB,EAAE,CAAC;IAC9B,CAAC;IAEO,oBAAoB;QAC1B,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC3B,IAAI,CAAC,iBAAiB,CAAC,SAAS,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;gBACjD,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;gBAC/B,MAAM,KAAK,GAAG,MAAM,aAAa,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;gBACvD,mEAAmE;gBACnE,aAAa,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;gBACvC,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;gBAChC,IAAI,KAAK;oBAAE,IAAI,CAAC,wBAAwB,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;YACxE,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,WAAW,CACtB,OAAsB,EACtB,cAAsC;QAEtC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC5B,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,oCAAoC,EAAE,CAAC;QACzE,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC;YAC9B,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,mBAAmB,EAAE,CAAC;QACxD,CAAC;QAED,IAAI,CAAC;YACH,8BAA8B;YAC9B,MAAM,aAAa,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YACzC,aAAa,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YAEtC,mDAAmD;YACnD,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,OAAO,EAAE;gBAChD,MAAM,EAAE,CAAC,EAAE,EAAE,EAAE;oBACb,OAAO,CAAC,GAAG,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;oBAClC,cAAc,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;gBAC/B,CAAC;gBACD,cAAc,EAAE,CAAC,EAAE,EAAE,EAAE;oBACrB,OAAO,CAAC,GAAG,CAAC,WAAW,EAAE,eAAe,CAAC,CAAC;oBAC1C,cAAc,EAAE,cAAc,EAAE,CAAC,EAAE,CAAC,CAAC;oBACrC,aAAa,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;oBACvC,aAAa,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;oBACzC,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;gBAClC,CAAC;gBACD,OAAO,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE;oBACrB,OAAO,CAAC,KAAK,CAAC,WAAW,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;oBAC9C,cAAc,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;oBACrC,gDAAgD;oBAChD,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;gBAClC,CAAC;aACF,CAAC,CAAC;YAEH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QACpC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,KAAK,CAAC,CAAC;YAC/C,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe;aAChE,CAAC;QACJ,CAAC;IACH,CAAC;IAEM,iBAAiB,CAAC,QAAiC;QACxD,IAAI,CAAC,wBAAwB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC5C,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC9D,CAAC;IAEM,uBAAuB,CAC5B,iBAA2C;QAE3C,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,CAAC,oBAAoB,EAAE,CAAC;IAC9B,CAAC;IAED,IAAW,YAAY;QACrB,OAAO,aAAa,CAAC,KAAK,CAAC;IAC7B,CAAC;IAEM,OAAO;QACZ,IAAI,CAAC,wBAAwB,CAAC,KAAK,EAAE,CAAC;QACtC,IAAI,CAAC,iBAAiB,EAAE,OAAO,EAAE,CAAC;IACpC,CAAC;CACF"} \ No newline at end of file diff --git a/packages/core/dist/wallet/config.d.ts b/packages/core/dist/wallet/config.d.ts new file mode 100644 index 0000000..39762ef --- /dev/null +++ b/packages/core/dist/wallet/config.d.ts @@ -0,0 +1,6 @@ +import { AppKitOptions } from '@reown/appkit'; +import { WagmiAdapter } from '@reown/appkit-adapter-wagmi'; +export declare const wagmiAdapter: WagmiAdapter; +export declare const config: import("wagmi").Config; +export declare const appkitConfig: AppKitOptions; +//# sourceMappingURL=config.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/wallet/config.d.ts.map b/packages/core/dist/wallet/config.d.ts.map new file mode 100644 index 0000000..18d6fa7 --- /dev/null +++ b/packages/core/dist/wallet/config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/wallet/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE9C,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAe3D,eAAO,MAAM,YAAY,cAKvB,CAAC;AAGH,eAAO,MAAM,MAAM,wBAA2B,CAAC;AAgB/C,eAAO,MAAM,YAAY,EAAE,aAW1B,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/wallet/config.js b/packages/core/dist/wallet/config.js new file mode 100644 index 0000000..db674da --- /dev/null +++ b/packages/core/dist/wallet/config.js @@ -0,0 +1,41 @@ +import { BitcoinAdapter } from '@reown/appkit-adapter-bitcoin'; +import { WagmiAdapter } from '@reown/appkit-adapter-wagmi'; +import { createStorage } from 'wagmi'; +import { mainnet, bitcoin } from '@reown/appkit/networks'; +const networks = [mainnet, bitcoin]; +const projectId = process.env.VITE_REOWN_SECRET || '2ead96ea166a03e5ab50e5c190532e72'; +if (!projectId) { + throw new Error('VITE_REOWN_SECRET is not defined. Please set it in your .env file'); +} +export const wagmiAdapter = new WagmiAdapter({ + storage: createStorage({ storage: localStorage }), + ssr: false, // Set to false for Vite/React apps + projectId, + networks, +}); +// Export the Wagmi config for the provider +export const config = wagmiAdapter.wagmiConfig; +const bitcoinAdapter = new BitcoinAdapter({ + projectId, +}); +const metadata = { + name: 'OpChan', + description: 'A Forum Library over Waku', + url: process.env.NODE_ENV === 'production' + ? 'https://opchan.app' + : 'http://localhost:8080', + icons: ['https://opchan.com/logo.png'], +}; +export const appkitConfig = { + adapters: [wagmiAdapter, bitcoinAdapter], + networks, + metadata, + projectId, + features: { + analytics: false, + socials: false, + allWallets: false, + }, + enableWalletConnect: false, +}; +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/packages/core/dist/wallet/config.js.map b/packages/core/dist/wallet/config.js.map new file mode 100644 index 0000000..86946e3 --- /dev/null +++ b/packages/core/dist/wallet/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/wallet/config.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAiB,MAAM,wBAAwB,CAAC;AAEzE,MAAM,QAAQ,GAAwC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAEzE,MAAM,SAAS,GACb,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,kCAAkC,CAAC;AAEtE,IAAI,CAAC,SAAS,EAAE,CAAC;IACf,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,YAAY,CAAC;IAC3C,OAAO,EAAE,aAAa,CAAC,EAAE,OAAO,EAAE,YAAY,EAAE,CAAC;IACjD,GAAG,EAAE,KAAK,EAAE,mCAAmC;IAC/C,SAAS;IACT,QAAQ;CACT,CAAC,CAAC;AAEH,2CAA2C;AAC3C,MAAM,CAAC,MAAM,MAAM,GAAG,YAAY,CAAC,WAAW,CAAC;AAE/C,MAAM,cAAc,GAAG,IAAI,cAAc,CAAC;IACxC,SAAS;CACV,CAAC,CAAC;AAEH,MAAM,QAAQ,GAAG;IACf,IAAI,EAAE,QAAQ;IACd,WAAW,EAAE,2BAA2B;IACxC,GAAG,EACD,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACnC,CAAC,CAAC,oBAAoB;QACtB,CAAC,CAAC,uBAAuB;IAC7B,KAAK,EAAE,CAAC,6BAA6B,CAAC;CACvC,CAAC;AAEF,MAAM,CAAC,MAAM,YAAY,GAAkB;IACzC,QAAQ,EAAE,CAAC,YAAY,EAAE,cAAc,CAAC;IACxC,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,QAAQ,EAAE;QACR,SAAS,EAAE,KAAK;QAChB,OAAO,EAAE,KAAK;QACd,UAAU,EAAE,KAAK;KAClB;IACD,mBAAmB,EAAE,KAAK;CAC3B,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/wallet/index.d.ts b/packages/core/dist/wallet/index.d.ts new file mode 100644 index 0000000..402a77d --- /dev/null +++ b/packages/core/dist/wallet/index.d.ts @@ -0,0 +1,75 @@ +import { UseAppKitAccountReturn } from '@reown/appkit/react'; +import { AppKit } from '@reown/appkit'; +import { WalletInfo, ActiveWallet } from './types'; +export declare class WalletManager { + private static instance; + private appKit; + private activeAccount; + private activeWalletType; + private namespace; + private constructor(); + /** + * Create or get the singleton instance + */ + static create(appKit: AppKit, bitcoinAccount: UseAppKitAccountReturn, ethereumAccount: UseAppKitAccountReturn): WalletManager; + /** + * Get the current instance (throws if not created) + */ + static getInstance(): WalletManager; + /** + * Check if instance exists + */ + static hasInstance(): boolean; + /** + * Clear the singleton instance + */ + static clear(): void; + /** + * Resolve ENS name for an Ethereum address + */ + static resolveENS(address: string): Promise; + /** + * Get the currently active wallet + */ + getActiveWallet(): ActiveWallet; + /** + * Check if wallet is connected + */ + isConnected(): boolean; + /** + * Get the active wallet type + */ + getWalletType(): 'bitcoin' | 'ethereum'; + /** + * Get address of the active wallet + */ + getAddress(): string; + /** + * Sign a message using the active wallet + */ + signMessage(message: string): Promise; + /** + * Verify a message signature against a wallet address + * @param message - The original message that was signed + * @param signature - The signature to verify + * @param walletAddress - The expected signer's address + * @param walletType - The type of wallet (bitcoin/ethereum) + * @returns Promise - True if signature is valid + */ + static verifySignature(message: string, signature: string, walletAddress: string, walletType: 'bitcoin' | 'ethereum'): Promise; + /** + * Get comprehensive wallet info including ENS resolution for Ethereum + */ + getWalletInfo(): Promise; +} +export declare const walletManager: { + create: typeof WalletManager.create; + getInstance: typeof WalletManager.getInstance; + hasInstance: typeof WalletManager.hasInstance; + clear: typeof WalletManager.clear; + resolveENS: typeof WalletManager.resolveENS; + verifySignature: typeof WalletManager.verifySignature; +}; +export * from './types'; +export * from './config'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/wallet/index.d.ts.map b/packages/core/dist/wallet/index.d.ts.map new file mode 100644 index 0000000..bd13f67 --- /dev/null +++ b/packages/core/dist/wallet/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/wallet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAQvC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAOnD,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAA8B;IAErD,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,aAAa,CAAyB;IAC9C,OAAO,CAAC,gBAAgB,CAAyB;IACjD,OAAO,CAAC,SAAS,CAAiB;IAElC,OAAO;IAqBP;;OAEG;IACH,MAAM,CAAC,MAAM,CACX,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,sBAAsB,EACtC,eAAe,EAAE,sBAAsB,GACtC,aAAa;IAUhB;;OAEG;IACH,MAAM,CAAC,WAAW,IAAI,aAAa;IASnC;;OAEG;IACH,MAAM,CAAC,WAAW,IAAI,OAAO;IAI7B;;OAEG;IACH,MAAM,CAAC,KAAK,IAAI,IAAI;IAIpB;;OAEG;WACU,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAYhE;;OAEG;IACH,eAAe,IAAI,YAAY;IAQ/B;;OAEG;IACH,WAAW,IAAI,OAAO;IAItB;;OAEG;IACH,aAAa,IAAI,SAAS,GAAG,UAAU;IAIvC;;OAEG;IACH,UAAU,IAAI,MAAM;IAIpB;;OAEG;IACG,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAuCnD;;;;;;;OAOG;WACU,eAAe,CAC1B,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,SAAS,GAAG,UAAU,GACjC,OAAO,CAAC,OAAO,CAAC;IAyCnB;;OAEG;IACG,aAAa,IAAI,OAAO,CAAC,UAAU,CAAC;CA6B3C;AAGD,eAAO,MAAM,aAAa;;;;;;;CAOzB,CAAC;AAEF,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/wallet/index.js b/packages/core/dist/wallet/index.js new file mode 100644 index 0000000..8f07b6d --- /dev/null +++ b/packages/core/dist/wallet/index.js @@ -0,0 +1,209 @@ +import { getEnsName, verifyMessage as verifyEthereumMessage, } from '@wagmi/core'; +import { config } from './config'; +let bitcoinMessagePromise = null; +const loadBitcoinMessage = () => (bitcoinMessagePromise ?? (bitcoinMessagePromise = import('bitcoinjs-message'))); +export class WalletManager { + constructor(appKit, bitcoinAccount, ethereumAccount) { + this.appKit = appKit; + // Determine active wallet (Bitcoin takes priority) + if (bitcoinAccount.isConnected && bitcoinAccount.address) { + this.activeAccount = bitcoinAccount; + this.activeWalletType = 'bitcoin'; + this.namespace = 'bip122'; + } + else if (ethereumAccount.isConnected && ethereumAccount.address) { + this.activeAccount = ethereumAccount; + this.activeWalletType = 'ethereum'; + this.namespace = 'eip155'; + } + else { + throw new Error('No wallet is connected'); + } + } + /** + * Create or get the singleton instance + */ + static create(appKit, bitcoinAccount, ethereumAccount) { + // Always create a new instance to reflect current wallet state + WalletManager.instance = new WalletManager(appKit, bitcoinAccount, ethereumAccount); + return WalletManager.instance; + } + /** + * Get the current instance (throws if not created) + */ + static getInstance() { + if (!WalletManager.instance) { + throw new Error('WalletManager not initialized. Call WalletManager.create() first.'); + } + return WalletManager.instance; + } + /** + * Check if instance exists + */ + static hasInstance() { + return WalletManager.instance !== null; + } + /** + * Clear the singleton instance + */ + static clear() { + WalletManager.instance = null; + } + /** + * Resolve ENS name for an Ethereum address + */ + static async resolveENS(address) { + try { + const ensName = await getEnsName(config, { + address: address, + }); + return ensName || null; + } + catch (error) { + console.warn('Failed to resolve ENS name:', error); + return null; + } + } + /** + * Get the currently active wallet + */ + getActiveWallet() { + return { + type: this.activeWalletType, + address: this.activeAccount.address, + isConnected: true, + }; + } + /** + * Check if wallet is connected + */ + isConnected() { + return this.activeAccount.isConnected; + } + /** + * Get the active wallet type + */ + getWalletType() { + return this.activeWalletType; + } + /** + * Get address of the active wallet + */ + getAddress() { + return this.activeAccount.address; + } + /** + * Sign a message using the active wallet + */ + async signMessage(message) { + try { + // Access the adapter through the appKit instance + const adapter = this.appKit.chainAdapters?.[this.namespace]; + if (!adapter) { + throw new Error(`No adapter found for namespace: ${this.namespace}`); + } + // Get the provider for the current connection + const provider = this.appKit.getProvider(this.namespace); + if (!provider) { + throw new Error(`No provider found for namespace: ${this.namespace}`); + } + if (!this.activeAccount.address) { + throw new Error('No address found for active account'); + } + // Call the adapter's signMessage method + const result = await adapter.signMessage({ + message, + address: this.activeAccount.address, + provider: provider, + }); + return result.signature; + } + catch (error) { + console.error(`Error signing message with ${this.activeWalletType} wallet:`, error); + throw new Error(`Failed to sign message with ${this.activeWalletType} wallet: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + /** + * Verify a message signature against a wallet address + * @param message - The original message that was signed + * @param signature - The signature to verify + * @param walletAddress - The expected signer's address + * @param walletType - The type of wallet (bitcoin/ethereum) + * @returns Promise - True if signature is valid + */ + static async verifySignature(message, signature, walletAddress, walletType) { + try { + if (process.env.NODE_ENV === 'development') { + // Keep this lightweight in dev; avoid logging full message/signature repeatedly + console.debug('WalletManager.verifySignature', { walletType }); + } + if (walletType === 'ethereum') { + return await verifyEthereumMessage(config, { + address: walletAddress, + message, + signature: signature, + }); + } + else if (walletType === 'bitcoin') { + if (process.env.NODE_ENV === 'development') { + console.debug('WalletManager.verifySignature (bitcoin)'); + } + const bitcoinMessage = await loadBitcoinMessage(); + const result = bitcoinMessage.verify(message, walletAddress, signature); + if (process.env.NODE_ENV === 'development') { + console.debug('WalletManager.verifySignature (bitcoin) result', result); + } + return result; + } + console.error('WalletManager.verifySignature - unknown wallet type:', walletType); + return false; + } + catch (error) { + console.error('WalletManager.verifySignature - error verifying signature:', error); + return false; + } + } + /** + * Get comprehensive wallet info including ENS resolution for Ethereum + */ + async getWalletInfo() { + const address = this.activeAccount.address; + if (this.activeWalletType === 'bitcoin') { + return { + address, + walletType: 'bitcoin', + isConnected: true, + }; + } + // For Ethereum, try to resolve ENS name + let ensName; + try { + const resolvedName = await getEnsName(config, { + address: address, + }); + ensName = resolvedName || undefined; + } + catch (error) { + console.warn('Failed to resolve ENS name:', error); + } + return { + address, + walletType: 'ethereum', + ensName, + isConnected: true, + }; + } +} +WalletManager.instance = null; +// Convenience exports for singleton access +export const walletManager = { + create: WalletManager.create, + getInstance: WalletManager.getInstance, + hasInstance: WalletManager.hasInstance, + clear: WalletManager.clear, + resolveENS: WalletManager.resolveENS, + verifySignature: WalletManager.verifySignature, +}; +export * from './types'; +export * from './config'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/core/dist/wallet/index.js.map b/packages/core/dist/wallet/index.js.map new file mode 100644 index 0000000..94354e2 --- /dev/null +++ b/packages/core/dist/wallet/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/wallet/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,UAAU,EACV,aAAa,IAAI,qBAAqB,GACvC,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAKlC,IAAI,qBAAqB,GAAyC,IAAI,CAAC;AACvE,MAAM,kBAAkB,GAAG,GAAG,EAAE,CAC9B,CAAC,qBAAqB,KAArB,qBAAqB,GAAK,MAAM,CAAC,mBAAmB,CAAC,EAAC,CAAC;AAE1D,MAAM,OAAO,aAAa;IAQxB,YACE,MAAc,EACd,cAAsC,EACtC,eAAuC;QAEvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAErB,mDAAmD;QACnD,IAAI,cAAc,CAAC,WAAW,IAAI,cAAc,CAAC,OAAO,EAAE,CAAC;YACzD,IAAI,CAAC,aAAa,GAAG,cAAc,CAAC;YACpC,IAAI,CAAC,gBAAgB,GAAG,SAAS,CAAC;YAClC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC5B,CAAC;aAAM,IAAI,eAAe,CAAC,WAAW,IAAI,eAAe,CAAC,OAAO,EAAE,CAAC;YAClE,IAAI,CAAC,aAAa,GAAG,eAAe,CAAC;YACrC,IAAI,CAAC,gBAAgB,GAAG,UAAU,CAAC;YACnC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC5B,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,MAAM,CACX,MAAc,EACd,cAAsC,EACtC,eAAuC;QAEvC,+DAA+D;QAC/D,aAAa,CAAC,QAAQ,GAAG,IAAI,aAAa,CACxC,MAAM,EACN,cAAc,EACd,eAAe,CAChB,CAAC;QACF,OAAO,aAAa,CAAC,QAAQ,CAAC;IAChC,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,WAAW;QAChB,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC;YAC5B,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;QACJ,CAAC;QACD,OAAO,aAAa,CAAC,QAAQ,CAAC;IAChC,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,WAAW;QAChB,OAAO,aAAa,CAAC,QAAQ,KAAK,IAAI,CAAC;IACzC,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,KAAK;QACV,aAAa,CAAC,QAAQ,GAAG,IAAI,CAAC;IAChC,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,OAAe;QACrC,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,MAAM,UAAU,CAAC,MAAM,EAAE;gBACvC,OAAO,EAAE,OAAwB;aAClC,CAAC,CAAC;YACH,OAAO,OAAO,IAAI,IAAI,CAAC;QACzB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,IAAI,CAAC,6BAA6B,EAAE,KAAK,CAAC,CAAC;YACnD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACH,eAAe;QACb,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,gBAAgB;YAC3B,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,OAAQ;YACpC,WAAW,EAAE,IAAI;SAClB,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC;IACxC,CAAC;IAED;;OAEG;IACH,aAAa;QACX,OAAO,IAAI,CAAC,gBAAgB,CAAC;IAC/B,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,aAAa,CAAC,OAAQ,CAAC;IACrC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,WAAW,CAAC,OAAe;QAC/B,IAAI,CAAC;YACH,iDAAiD;YACjD,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,aAAa,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAE5D,IAAI,CAAC,OAAO,EAAE,CAAC;gBACb,MAAM,IAAI,KAAK,CAAC,mCAAmC,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;YACvE,CAAC;YAED,8CAA8C;YAC9C,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAEzD,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,MAAM,IAAI,KAAK,CAAC,oCAAoC,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;YACxE,CAAC;YAED,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;gBAChC,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;YACzD,CAAC;YAED,wCAAwC;YACxC,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,WAAW,CAAC;gBACvC,OAAO;gBACP,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,OAAO;gBACnC,QAAQ,EAAE,QAAoB;aAC/B,CAAC,CAAC;YAEH,OAAO,MAAM,CAAC,SAAS,CAAC;QAC1B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CACX,8BAA8B,IAAI,CAAC,gBAAgB,UAAU,EAC7D,KAAK,CACN,CAAC;YACF,MAAM,IAAI,KAAK,CACb,+BAA+B,IAAI,CAAC,gBAAgB,YAAY,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,EAAE,CAC3H,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,KAAK,CAAC,eAAe,CAC1B,OAAe,EACf,SAAiB,EACjB,aAAqB,EACrB,UAAkC;QAElC,IAAI,CAAC;YACH,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;gBAC3C,gFAAgF;gBAChF,OAAO,CAAC,KAAK,CAAC,+BAA+B,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;YACjE,CAAC;YACD,IAAI,UAAU,KAAK,UAAU,EAAE,CAAC;gBAC9B,OAAO,MAAM,qBAAqB,CAAC,MAAM,EAAE;oBACzC,OAAO,EAAE,aAA8B;oBACvC,OAAO;oBACP,SAAS,EAAE,SAA0B;iBACtC,CAAC,CAAC;YACL,CAAC;iBAAM,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;gBACpC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;oBAC3C,OAAO,CAAC,KAAK,CAAC,yCAAyC,CAAC,CAAC;gBAC3D,CAAC;gBACD,MAAM,cAAc,GAAG,MAAM,kBAAkB,EAAE,CAAC;gBAClD,MAAM,MAAM,GAAG,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,aAAa,EAAE,SAAS,CAAC,CAAC;gBACxE,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;oBAC3C,OAAO,CAAC,KAAK,CACX,gDAAgD,EAChD,MAAM,CACP,CAAC;gBACJ,CAAC;gBACD,OAAO,MAAM,CAAC;YAChB,CAAC;YAED,OAAO,CAAC,KAAK,CACX,sDAAsD,EACtD,UAAU,CACX,CAAC;YACF,OAAO,KAAK,CAAC;QACf,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CACX,4DAA4D,EAC5D,KAAK,CACN,CAAC;YACF,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa;QACjB,MAAM,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC,OAAQ,CAAC;QAE5C,IAAI,IAAI,CAAC,gBAAgB,KAAK,SAAS,EAAE,CAAC;YACxC,OAAO;gBACL,OAAO;gBACP,UAAU,EAAE,SAAS;gBACrB,WAAW,EAAE,IAAI;aAClB,CAAC;QACJ,CAAC;QAED,wCAAwC;QACxC,IAAI,OAA2B,CAAC;QAChC,IAAI,CAAC;YACH,MAAM,YAAY,GAAG,MAAM,UAAU,CAAC,MAAM,EAAE;gBAC5C,OAAO,EAAE,OAAwB;aAClC,CAAC,CAAC;YACH,OAAO,GAAG,YAAY,IAAI,SAAS,CAAC;QACtC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,IAAI,CAAC,6BAA6B,EAAE,KAAK,CAAC,CAAC;QACrD,CAAC;QAED,OAAO;YACL,OAAO;YACP,UAAU,EAAE,UAAU;YACtB,OAAO;YACP,WAAW,EAAE,IAAI;SAClB,CAAC;IACJ,CAAC;;AArPc,sBAAQ,GAAyB,IAAI,CAAC;AAwPvD,2CAA2C;AAC3C,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,MAAM,EAAE,aAAa,CAAC,MAAM;IAC5B,WAAW,EAAE,aAAa,CAAC,WAAW;IACtC,WAAW,EAAE,aAAa,CAAC,WAAW;IACtC,KAAK,EAAE,aAAa,CAAC,KAAK;IAC1B,UAAU,EAAE,aAAa,CAAC,UAAU;IACpC,eAAe,EAAE,aAAa,CAAC,eAAe;CAC/C,CAAC;AAEF,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/wallet/types.d.ts b/packages/core/dist/wallet/types.d.ts new file mode 100644 index 0000000..4255535 --- /dev/null +++ b/packages/core/dist/wallet/types.d.ts @@ -0,0 +1,12 @@ +export interface WalletInfo { + address: string; + walletType: 'bitcoin' | 'ethereum'; + ensName?: string; + isConnected: boolean; +} +export interface ActiveWallet { + type: 'bitcoin' | 'ethereum'; + address: string; + isConnected: boolean; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/packages/core/dist/wallet/types.d.ts.map b/packages/core/dist/wallet/types.d.ts.map new file mode 100644 index 0000000..d51c15a --- /dev/null +++ b/packages/core/dist/wallet/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/wallet/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,SAAS,GAAG,UAAU,CAAC;IACnC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,OAAO,CAAC;CACtB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,SAAS,GAAG,UAAU,CAAC;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,OAAO,CAAC;CACtB"} \ No newline at end of file diff --git a/packages/core/dist/wallet/types.js b/packages/core/dist/wallet/types.js new file mode 100644 index 0000000..718fd38 --- /dev/null +++ b/packages/core/dist/wallet/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/packages/core/dist/wallet/types.js.map b/packages/core/dist/wallet/types.js.map new file mode 100644 index 0000000..0b0b326 --- /dev/null +++ b/packages/core/dist/wallet/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/wallet/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/react/dist/index.d.ts b/packages/react/dist/index.d.ts new file mode 100644 index 0000000..e26a57a --- /dev/null +++ b/packages/react/dist/index.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/react/dist/index.d.ts.map b/packages/react/dist/index.d.ts.map new file mode 100644 index 0000000..d1fa433 --- /dev/null +++ b/packages/react/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC"} \ No newline at end of file diff --git a/packages/react/dist/index.js b/packages/react/dist/index.js new file mode 100644 index 0000000..aa219d8 --- /dev/null +++ b/packages/react/dist/index.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/react/dist/index.js.map b/packages/react/dist/index.js.map new file mode 100644 index 0000000..89c8d74 --- /dev/null +++ b/packages/react/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":""} \ No newline at end of file