import React, { Fragment, useCallback, useState, useMemo, useEffect, } from 'react' import { Menu, Transition } from '@headlessui/react' import { useWallet, Wallet } from '@solana/wallet-adapter-react' import { WalletReadyState } from '@solana/wallet-adapter-base' import { CurrencyDollarIcon, DuplicateIcon, LogoutIcon, } from '@heroicons/react/outline' import { notify } from 'utils/notifications' import { abbreviateAddress, copyToClipboard } from 'utils' import useMangoStore from 'stores/useMangoStore' import { ProfileIcon, WalletIcon } from './icons' import { useTranslation } from 'next-i18next' import { WalletSelect } from 'components/WalletSelect' import AccountsModal from './AccountsModal' import uniqBy from 'lodash/uniqBy' export const handleWalletConnect = (wallet: Wallet) => { if (!wallet) { return } if (wallet.readyState === WalletReadyState.NotDetected) { window.open(wallet.adapter.url, '_blank') } else { wallet?.adapter?.connect().catch((e) => { if (e.name.includes('WalletLoadError')) { notify({ title: `${wallet.adapter.name} Error`, type: 'error', description: `Please install ${wallet.adapter.name} and then reload this page.`, }) } }) } } export const ConnectWalletButton: React.FC = () => { const { connected, publicKey, wallet, wallets, select } = useWallet() const { t } = useTranslation('common') const pfp = useMangoStore((s) => s.wallet.pfp) const set = useMangoStore((s) => s.set) const mangoGroup = useMangoStore((s) => s.selectedMangoGroup.current) const [showAccountsModal, setShowAccountsModal] = useState(false) const installedWallets = useMemo(() => { const installed: Wallet[] = [] for (const wallet of wallets) { if (wallet.readyState === WalletReadyState.Installed) { installed.push(wallet) } } return installed }, [wallets]) const displayedWallets = useMemo(() => { return uniqBy([...installedWallets, ...wallets], (w) => { return w.adapter.name }) }, [wallets, installedWallets]) const handleConnect = useCallback(() => { if (wallet) { handleWalletConnect(wallet) } }, [wallet]) const handleCloseAccounts = useCallback(() => { setShowAccountsModal(false) }, []) const handleDisconnect = useCallback(() => { wallet?.adapter?.disconnect() set((state) => { state.mangoAccounts = [] state.selectedMangoAccount.current = null state.tradeHistory = { spot: [], perp: [], parsed: [], initialLoad: false, } }) notify({ type: 'info', title: t('wallet-disconnected'), }) }, [wallet, set, t]) useEffect(() => { if (!wallet && displayedWallets?.length) { select(displayedWallets[0].adapter.name) } }, [wallet, displayedWallets, select]) return ( <> {connected && publicKey ? (
) : (