import { useState } from 'react' import { Listbox } from '@headlessui/react' import { ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/solid' import { abbreviateAddress, getSymbolForTokenMintAddress } from '../utils' import useMarketList from '../hooks/useMarketList' import { nativeToUi } from '@blockworks-foundation/mango-client/lib/utils' import useMangoStore from '../stores/useMangoStore' import { SRM_DECIMALS } from '@project-serum/serum/lib/token-instructions' import { RefreshClockwiseIcon } from './icons' type AccountSelectProps = { accounts: any[] selectedAccount: any onSelectAccount: (x) => any getBalance?: (x) => any hideAddress?: boolean symbols?: { [key: string]: string } } const AccountSelect = ({ accounts, selectedAccount, onSelectAccount, getBalance, hideAddress = false, symbols, }: AccountSelectProps) => { const { getTokenIndex } = useMarketList() const mintDecimals = useMangoStore((s) => s.selectedMangoGroup.mintDecimals) const actions = useMangoStore((s) => s.actions) const [loading, setLoading] = useState(false) const handleChange = (value) => { const newAccount = accounts.find((a) => a.publicKey.toString() === value) onSelectAccount(newAccount) } const getBalanceForAccount = (account) => { const mintAddress = account?.account.mint.toString() const symbol = getSymbolForTokenMintAddress(mintAddress) const balance = nativeToUi( account?.account?.amount, symbol !== 'SRM' ? mintDecimals[getTokenIndex(mintAddress)] : SRM_DECIMALS ) return balance.toString() } const handleRefreshBalances = async () => { setLoading(true) await actions.fetchWalletBalances() setLoading(false) } const symbolsForAccounts = accounts.map((a) => getSymbolForTokenMintAddress(a.account.mint.toString()) ) const missingTokens = symbols ? Object.keys(symbols) .filter((sym) => !symbolsForAccounts.includes(sym)) .join(', ') : null return (
Token Account
{accounts.length < 3 ? ( ) : null}
{({ open }) => ( <>
{selectedAccount ? (
{getSymbolForTokenMintAddress( selectedAccount?.account?.mint.toString() )} {!hideAddress ? (
{abbreviateAddress(selectedAccount?.publicKey)}
) : null}
{hideAddress ? getBalance(selectedAccount) : getBalanceForAccount(selectedAccount)}
) : ( 'Select a token address' )} {open ? ( ) : ( )}
Accounts
{!hideAddress ? (
Balance
) : null}
{accounts.map((account) => { const symbolForAccount = getSymbolForTokenMintAddress( account?.account?.mint.toString() ) return ( {({ selected }) => (
{symbolForAccount} {!hideAddress ? (
{abbreviateAddress(account?.publicKey)}
) : null}
{!hideAddress ? (
{getBalanceForAccount(account)} {symbolForAccount}
) : null}
)}
) })} {missingTokens && accounts.length !== 3 ? (
Wallet token address not found for: {missingTokens}
) : null}
)}
) } export default AccountSelect