mango-v4-ui/components/TokenList.tsx

864 lines
29 KiB
TypeScript
Raw Normal View History

2023-10-03 22:05:16 -07:00
import { Bank } from '@blockworks-foundation/mango-v4'
import { Disclosure, Popover, Transition } from '@headlessui/react'
2022-08-15 18:59:15 -07:00
import {
ChevronDownIcon,
2022-09-06 21:36:35 -07:00
EllipsisHorizontalIcon,
XMarkIcon,
2022-09-06 21:36:35 -07:00
} from '@heroicons/react/20/solid'
2022-07-19 22:49:09 -07:00
import { useTranslation } from 'next-i18next'
2022-07-25 22:27:53 -07:00
import { useRouter } from 'next/router'
import { Fragment, useCallback, useMemo, useState } from 'react'
2022-07-19 22:49:09 -07:00
import { useViewport } from '../hooks/useViewport'
2022-09-12 08:53:57 -07:00
import mangoStore from '@store/mangoStore'
2022-07-19 22:49:09 -07:00
import { breakpoints } from '../utils/theme'
2022-07-25 20:59:46 -07:00
import Switch from './forms/Switch'
2022-06-21 03:58:57 -07:00
import ContentBox from './shared/ContentBox'
2022-09-19 23:16:03 -07:00
import Tooltip from './shared/Tooltip'
import { formatTokenSymbol } from 'utils/tokens'
2022-11-18 09:09:39 -08:00
import useMangoAccount from 'hooks/useMangoAccount'
import {
SortableColumnHeader,
Table,
Td,
Th,
TrBody,
TrHead,
} from './shared/TableElements'
import DepositWithdrawModal from './modals/DepositWithdrawModal'
2022-12-18 04:30:49 -08:00
import BorrowRepayModal from './modals/BorrowRepayModal'
2023-01-04 18:50:36 -08:00
import { WRAPPED_SOL_MINT } from '@project-serum/serum/lib/token-instructions'
import {
2023-10-22 04:07:43 -07:00
MANGO_DATA_API_URL,
SHOW_ZERO_BALANCES_KEY,
TOKEN_REDUCE_ONLY_OPTIONS,
USDC_MINT,
} from 'utils/constants'
2023-01-04 18:50:36 -08:00
import { PublicKey } from '@solana/web3.js'
2023-01-05 01:04:09 -08:00
import ActionsLinkButton from './account/ActionsLinkButton'
2023-01-23 17:26:14 -08:00
import FormatNumericValue from './shared/FormatNumericValue'
2023-01-28 17:13:36 -08:00
import BankAmountWithValue from './shared/BankAmountWithValue'
2023-01-29 20:13:38 -08:00
import useBanksWithBalances, {
BankWithBalance,
} from 'hooks/useBanksWithBalances'
import useUnownedAccount from 'hooks/useUnownedAccount'
2023-04-13 05:35:23 -07:00
import useLocalStorageState from 'hooks/useLocalStorageState'
2023-07-04 21:40:47 -07:00
import TokenLogo from './shared/TokenLogo'
2023-07-17 19:58:20 -07:00
import useHealthContributions from 'hooks/useHealthContributions'
import { useSortableData } from 'hooks/useSortableData'
import TableTokenName from './shared/TableTokenName'
2023-10-12 04:51:02 -07:00
import CloseBorrowModal from './modals/CloseBorrowModal'
import { floorToDecimal } from 'utils/numbers'
2023-10-22 04:07:43 -07:00
import { useQuery } from '@tanstack/react-query'
import { TotalInterestDataItem } from 'types'
import SheenLoader from './shared/SheenLoader'
2023-11-08 15:47:05 -08:00
export const handleOpenCloseBorrowModal = (borrowBank: Bank) => {
const group = mangoStore.getState().group
const mangoAccount = mangoStore.getState().mangoAccount.current
let repayBank: Bank | undefined
if (borrowBank.name === 'USDC') {
const solBank = group?.getFirstBankByMint(WRAPPED_SOL_MINT)
repayBank = solBank
} else {
const usdcBank = group?.getFirstBankByMint(new PublicKey(USDC_MINT))
repayBank = usdcBank
}
if (mangoAccount && repayBank) {
const borrowBalance = mangoAccount.getTokenBalanceUi(borrowBank)
const roundedBorrowBalance = floorToDecimal(
borrowBalance,
borrowBank.mintDecimals,
).toNumber()
const repayBalance = mangoAccount.getTokenBalanceUi(repayBank)
const roundedRepayBalance = floorToDecimal(
repayBalance,
repayBank.mintDecimals,
).toNumber()
const hasSufficientRepayBalance =
Math.abs(roundedRepayBalance) * repayBank.uiPrice >
Math.abs(roundedBorrowBalance) * borrowBank.uiPrice
set((state) => {
state.swap.swapMode = hasSufficientRepayBalance ? 'ExactOut' : 'ExactIn'
state.swap.inputBank = repayBank
state.swap.outputBank = borrowBank
if (hasSufficientRepayBalance) {
state.swap.amountOut = Math.abs(roundedBorrowBalance).toString()
} else {
state.swap.amountIn = Math.abs(roundedRepayBalance).toString()
}
})
}
}
export const handleCloseBorrowModal = () => {
set((state) => {
state.swap.inputBank = undefined
state.swap.outputBank = undefined
state.swap.amountIn = ''
state.swap.amountOut = ''
state.swap.swapMode = 'ExactIn'
})
}
2023-10-22 04:07:43 -07:00
export const fetchInterestData = async (mangoAccountPk: string) => {
try {
const response = await fetch(
`${MANGO_DATA_API_URL}/stats/interest-account-total?mango-account=${mangoAccountPk}`,
)
const parsedResponse: Omit<TotalInterestDataItem, 'symbol'>[] | null =
await response.json()
if (parsedResponse) {
const entries: [string, Omit<TotalInterestDataItem, 'symbol'>][] =
Object.entries(parsedResponse).sort((a, b) => b[0].localeCompare(a[0]))
const stats: TotalInterestDataItem[] = entries
.map(([key, value]) => {
return { ...value, symbol: key }
})
.filter((x) => x)
return stats
} else return []
} catch (e) {
console.log('Failed to fetch account funding', e)
return []
}
}
type TableData = {
bank: Bank
balance: number
symbol: string
interestAmount: number
interestValue: number
inOrders: number
unsettled: number
collateralValue: number
assetWeight: string
liabWeight: string
depositRate: number
borrowRate: number
}
2022-05-03 21:20:14 -07:00
2023-10-12 04:51:02 -07:00
const set = mangoStore.getState().set
2022-07-10 19:01:16 -07:00
const TokenList = () => {
2022-10-29 04:38:40 -07:00
const { t } = useTranslation(['common', 'token', 'trade'])
2023-10-12 04:51:02 -07:00
const [showCloseBorrowModal, setCloseBorrowModal] = useState(false)
const [closeBorrowBank, setCloseBorrowBank] = useState<Bank | undefined>()
2023-04-13 05:35:23 -07:00
const [showZeroBalances, setShowZeroBalances] = useLocalStorageState(
SHOW_ZERO_BALANCES_KEY,
2023-07-21 11:47:53 -07:00
true,
2023-04-13 05:35:23 -07:00
)
2023-10-03 22:05:16 -07:00
const { mangoAccountAddress } = useMangoAccount()
2023-07-17 19:58:20 -07:00
const { initContributions } = useHealthContributions()
2022-10-06 18:57:47 -07:00
const spotBalances = mangoStore((s) => s.mangoAccount.spotBalances)
2022-07-19 22:49:09 -07:00
const { width } = useViewport()
const showTableView = width ? width > breakpoints.md : false
2023-01-29 20:13:38 -08:00
const banks = useBanksWithBalances('balance')
2022-05-03 21:20:14 -07:00
2023-10-22 04:07:43 -07:00
const {
data: totalInterestData,
isInitialLoading: loadingTotalInterestData,
} = useQuery(
['account-interest-data', mangoAccountAddress],
() => fetchInterestData(mangoAccountAddress),
{
cacheTime: 1000 * 60 * 10,
staleTime: 1000 * 60,
retry: 3,
refetchOnWindowFocus: false,
enabled: !!mangoAccountAddress,
},
)
2023-07-27 22:04:38 -07:00
const formattedTableData = useCallback(
2023-07-27 04:24:04 -07:00
(banks: BankWithBalance[]) => {
const formatted = []
for (const b of banks) {
const bank = b.bank
2023-10-12 04:51:02 -07:00
const balance = floorToDecimal(b.balance, bank.mintDecimals).toNumber()
2023-07-31 19:26:08 -07:00
const balanceValue = balance * bank.uiPrice
2023-07-27 04:24:04 -07:00
const symbol = bank.name === 'MSOL' ? 'mSOL' : bank.name
2023-10-22 04:07:43 -07:00
const hasInterestEarned = totalInterestData?.find(
2023-07-27 04:24:04 -07:00
(d) =>
d.symbol.toLowerCase() === symbol.toLowerCase() ||
(symbol === 'ETH (Portal)' && d.symbol === 'ETH'),
)
2023-07-27 04:24:04 -07:00
const interestAmount = hasInterestEarned
? hasInterestEarned.borrow_interest * -1 +
hasInterestEarned.deposit_interest
: 0
2023-07-27 04:24:04 -07:00
const interestValue = hasInterestEarned
? hasInterestEarned.borrow_interest_usd * -1 +
hasInterestEarned.deposit_interest_usd
: 0.0
2023-07-27 04:24:04 -07:00
const inOrders = spotBalances[bank.mint.toString()]?.inOrders || 0
2023-07-27 04:24:04 -07:00
const unsettled = spotBalances[bank.mint.toString()]?.unsettled || 0
2023-07-27 04:24:04 -07:00
const collateralValue =
initContributions.find((val) => val.asset === bank.name)
?.contribution || 0
2023-07-27 04:24:04 -07:00
const assetWeight = bank.scaledInitAssetWeight(bank.price).toFixed(2)
const liabWeight = bank.scaledInitLiabWeight(bank.price).toFixed(2)
2023-07-27 04:24:04 -07:00
const depositRate = bank.getDepositRateUi()
const borrowRate = bank.getBorrowRateUi()
2023-07-27 04:24:04 -07:00
const data = {
balance,
2023-07-31 19:26:08 -07:00
balanceValue,
2023-07-27 04:24:04 -07:00
bank,
symbol,
interestAmount,
interestValue,
inOrders,
unsettled,
collateralValue,
assetWeight,
liabWeight,
depositRate,
borrowRate,
}
formatted.push(data)
}
2023-07-27 04:24:04 -07:00
return formatted
},
[initContributions, spotBalances, totalInterestData],
)
2023-07-21 14:34:19 -07:00
const unsortedTableData = useMemo(() => {
if (!banks.length) return []
if (showZeroBalances || !mangoAccountAddress) {
2023-07-27 22:04:38 -07:00
return formattedTableData(banks)
} else {
const filtered = banks.filter((b) => Math.abs(b.balance) > 0)
2023-07-27 22:04:38 -07:00
return formattedTableData(filtered)
}
}, [banks, mangoAccountAddress, showZeroBalances, totalInterestData])
const {
items: tableData,
requestSort,
sortConfig,
} = useSortableData(unsortedTableData)
2022-05-03 21:20:14 -07:00
2023-11-08 15:47:05 -08:00
const openCloseBorrowModal = (borrowBank: Bank) => {
2023-10-12 04:51:02 -07:00
setCloseBorrowModal(true)
setCloseBorrowBank(borrowBank)
2023-11-08 15:47:05 -08:00
handleOpenCloseBorrowModal(borrowBank)
2023-10-12 04:51:02 -07:00
}
2023-11-08 15:47:05 -08:00
const closeBorrowModal = () => {
2023-10-12 04:51:02 -07:00
setCloseBorrowModal(false)
2023-11-08 15:47:05 -08:00
handleCloseBorrowModal()
2023-10-12 04:51:02 -07:00
}
2023-10-17 04:28:43 -07:00
const balancesNumber = useMemo(() => {
if (!banks.length) return 0
const activeBalancesNumber = banks.filter(
(bank) => Math.abs(bank.balance) > 0,
).length
return activeBalancesNumber
}, [banks])
2022-05-03 21:20:14 -07:00
return (
2023-02-03 02:36:44 -08:00
<ContentBox hideBorder hidePadding>
2023-04-13 05:35:23 -07:00
{mangoAccountAddress ? (
2023-10-17 04:28:43 -07:00
<div className="flex w-full items-center justify-between border-b border-th-bkg-3 px-6 py-3">
<p className="text-xs text-th-fgd-2">{`${balancesNumber} ${t(
'balances',
)}`}</p>
2023-04-13 05:35:23 -07:00
<Switch
checked={showZeroBalances}
2023-10-03 22:05:16 -07:00
disabled={!mangoAccountAddress}
2023-04-13 05:35:23 -07:00
onChange={() => setShowZeroBalances(!showZeroBalances)}
>
2023-07-21 14:34:19 -07:00
{t('account:zero-balances')}
2023-04-13 05:35:23 -07:00
</Switch>
</div>
) : null}
2022-07-19 22:49:09 -07:00
{showTableView ? (
2023-07-22 15:53:59 -07:00
<>
2023-07-17 19:58:20 -07:00
<Table>
<thead>
<TrHead>
<Th className="text-left">
<SortableColumnHeader
sortKey="symbol"
sort={() => requestSort('symbol')}
sortConfig={sortConfig}
title={t('token')}
/>
</Th>
2023-07-17 19:58:20 -07:00
<Th>
<div className="flex justify-end">
<Tooltip content="A negative balance represents a borrow">
<SortableColumnHeader
2023-07-31 19:26:08 -07:00
sortKey="balanceValue"
sort={() => requestSort('balanceValue')}
sortConfig={sortConfig}
title={t('balance')}
titleClass="tooltip-underline"
/>
2023-07-17 19:58:20 -07:00
</Tooltip>
</div>
</Th>
<Th>
<div className="flex justify-end">
<Tooltip content={t('tooltip-collateral-value')}>
<SortableColumnHeader
sortKey="collateralValue"
sort={() => requestSort('collateralValue')}
sortConfig={sortConfig}
title={t('collateral-value')}
titleClass="tooltip-underline"
/>
2023-07-17 19:58:20 -07:00
</Tooltip>
</div>
</Th>
<Th>
<div className="flex justify-end">
<SortableColumnHeader
sortKey="inOrders"
sort={() => requestSort('inOrders')}
sortConfig={sortConfig}
title={t('trade:in-orders')}
/>
</div>
2023-07-17 19:58:20 -07:00
</Th>
<Th>
<div className="flex justify-end">
<Tooltip content="The sum of interest earned and interest paid for each token">
<SortableColumnHeader
sortKey="interestValue"
sort={() => requestSort('interestValue')}
sortConfig={sortConfig}
title={t('interest-earned-paid')}
titleClass="tooltip-underline"
/>
</Tooltip>
</div>
</Th>
2023-10-13 03:10:40 -07:00
<Th>
<div className="flex justify-end">
<Tooltip content={t('tooltip-interest-rates')}>
<SortableColumnHeader
sortKey="depositRate"
sort={() => requestSort('depositRate')}
sortConfig={sortConfig}
title={t('rates')}
titleClass="tooltip-underline"
/>
</Tooltip>
</div>
</Th>
2023-07-17 19:58:20 -07:00
<Th className="text-right">
<span>{t('actions')}</span>
</Th>
</TrHead>
</thead>
<tbody>
{tableData.map((data) => {
const {
balance,
bank,
symbol,
interestValue,
inOrders,
collateralValue,
assetWeight,
liabWeight,
depositRate,
borrowRate,
} = data
2023-07-17 19:58:20 -07:00
return (
<TrBody key={symbol}>
2023-07-17 19:58:20 -07:00
<Td>
<TableTokenName bank={bank} symbol={symbol} />
2023-07-17 19:58:20 -07:00
</Td>
<Td className="text-right">
2023-01-28 17:13:36 -08:00
<BankAmountWithValue
amount={balance}
2023-01-28 17:13:36 -08:00
bank={bank}
2023-01-08 19:38:09 -08:00
stacked
2023-11-02 17:27:20 -07:00
isPrivate
2023-01-08 19:38:09 -08:00
/>
2023-07-17 19:58:20 -07:00
</Td>
<Td className="text-right">
<p>
2023-07-17 20:09:57 -07:00
<FormatNumericValue
value={collateralValue}
decimals={2}
isUsd
2023-11-02 17:27:20 -07:00
isPrivate
2023-07-17 20:09:57 -07:00
/>
2022-09-07 05:00:21 -07:00
</p>
2023-07-17 19:58:20 -07:00
<p className="text-sm text-th-fgd-4">
2023-01-23 17:26:14 -08:00
<FormatNumericValue
2023-07-17 19:58:20 -07:00
value={
2023-07-17 20:09:57 -07:00
collateralValue <= -0.01 ? liabWeight : assetWeight
2023-07-17 19:58:20 -07:00
}
2023-01-23 17:26:14 -08:00
/>
2023-07-17 19:58:20 -07:00
x
2022-09-07 05:00:21 -07:00
</p>
2023-07-17 19:58:20 -07:00
</Td>
<Td className="text-right">
2023-10-12 21:21:35 -07:00
{inOrders ? (
2023-07-17 19:58:20 -07:00
<BankAmountWithValue
2023-10-12 21:21:35 -07:00
amount={inOrders}
2023-07-17 19:58:20 -07:00
bank={bank}
stacked
2023-11-02 17:27:20 -07:00
isPrivate
2023-07-17 19:58:20 -07:00
/>
2023-10-12 21:21:35 -07:00
) : (
<p className="text-th-fgd-4"></p>
)}
2023-07-17 19:58:20 -07:00
</Td>
<Td>
2023-10-13 03:10:40 -07:00
<div className="flex justify-end">
2023-10-22 04:07:43 -07:00
{loadingTotalInterestData ? (
<SheenLoader>
<div className="h-4 w-12 bg-th-bkg-2" />
</SheenLoader>
) : Math.abs(interestValue) > 0 ? (
2023-10-13 03:10:40 -07:00
<p>
<FormatNumericValue
value={interestValue}
isUsd
decimals={2}
2023-11-02 17:27:20 -07:00
isPrivate
2023-10-13 03:10:40 -07:00
/>
</p>
2023-10-12 21:21:35 -07:00
) : (
2023-10-13 03:10:40 -07:00
<p className="text-th-fgd-4"></p>
2023-10-12 21:21:35 -07:00
)}
2023-07-17 19:58:20 -07:00
</div>
</Td>
2023-10-13 03:10:40 -07:00
<Td>
<div className="flex justify-end space-x-1.5">
<Tooltip content={t('deposit-rate')}>
<p className="cursor-help text-th-up">
<FormatNumericValue
value={depositRate}
decimals={2}
/>
%
</p>
</Tooltip>
<span className="text-th-fgd-4">|</span>
<Tooltip content={t('borrow-rate')}>
<p className="cursor-help text-th-down">
<FormatNumericValue
value={borrowRate}
decimals={2}
/>
%
</p>
</Tooltip>
</div>
</Td>
2023-07-17 19:58:20 -07:00
<Td>
2023-10-12 04:51:02 -07:00
<div className="flex items-center justify-end space-x-2">
{balance < 0 ? (
<button
className="rounded-md border border-th-fgd-4 px-2 py-1.5 text-xs font-bold text-th-fgd-2 focus:outline-none md:hover:border-th-fgd-3"
2023-11-08 15:47:05 -08:00
onClick={() => openCloseBorrowModal(bank)}
2023-10-12 04:51:02 -07:00
>
{t('close-borrow', { token: '' })}
</button>
) : null}
2023-10-03 22:05:16 -07:00
<ActionsMenu bank={bank} />
2023-07-17 19:58:20 -07:00
</div>
</Td>
</TrBody>
)
})}
</tbody>
</Table>
2023-07-22 15:53:59 -07:00
</>
2022-07-19 22:49:09 -07:00
) : (
<div className="border-b border-th-bkg-3">
{tableData.map((data) => {
return <MobileTokenListItem key={data.bank.name} data={data} />
2022-07-14 18:46:34 -07:00
})}
2022-07-19 22:49:09 -07:00
</div>
)}
2023-10-12 04:51:02 -07:00
{showCloseBorrowModal ? (
<CloseBorrowModal
borrowBank={closeBorrowBank}
isOpen={showCloseBorrowModal}
2023-11-08 15:47:05 -08:00
onClose={closeBorrowModal}
2023-10-12 04:51:02 -07:00
/>
) : null}
</ContentBox>
)
}
export default TokenList
const MobileTokenListItem = ({ data }: { data: TableData }) => {
2022-10-11 04:59:01 -07:00
const { t } = useTranslation(['common', 'token'])
2022-11-18 09:09:39 -08:00
const { mangoAccount } = useMangoAccount()
const {
bank,
balance,
symbol,
interestAmount,
interestValue,
inOrders,
unsettled,
collateralValue,
assetWeight,
liabWeight,
depositRate,
borrowRate,
} = data
2023-07-17 19:58:20 -07:00
return (
<Disclosure>
{({ open }) => (
<>
<Disclosure.Button
2023-03-19 03:28:13 -07:00
className={`w-full border-t border-th-bkg-3 p-4 text-left first:border-t-0 focus:outline-none`}
>
<div className="flex items-center justify-between">
<TableTokenName bank={bank} symbol={symbol} />
<div className="flex items-center space-x-2">
<div className="text-right">
<p className="font-mono text-sm text-th-fgd-2">
<FormatNumericValue
value={balance}
decimals={bank.mintDecimals}
/>
</p>
<span className="font-mono text-xs text-th-fgd-3">
<FormatNumericValue
value={mangoAccount ? balance * bank.uiPrice : 0}
decimals={2}
isUsd
2023-11-02 17:27:20 -07:00
isPrivate
/>
</span>
</div>
<ChevronDownIcon
className={`${
open ? 'rotate-180' : 'rotate-360'
2023-03-19 03:28:13 -07:00
} h-6 w-6 flex-shrink-0 text-th-fgd-3`}
2023-01-24 02:56:04 -08:00
/>
</div>
</div>
</Disclosure.Button>
<Transition
enter="transition ease-in duration-200"
enterFrom="opacity-0"
enterTo="opacity-100"
>
<Disclosure.Panel>
<div className="mx-4 grid grid-cols-2 gap-4 border-t border-th-bkg-3 pb-4 pt-4">
2023-07-17 19:58:20 -07:00
<div className="col-span-1">
<Tooltip content={t('tooltip-collateral-value')}>
2023-07-17 19:58:20 -07:00
<p className="tooltip-underline text-xs text-th-fgd-3">
{t('collateral-value')}
2023-07-17 19:58:20 -07:00
</p>
</Tooltip>
<p className="font-mono text-th-fgd-2">
2023-07-17 20:09:57 -07:00
<FormatNumericValue
value={collateralValue}
decimals={2}
isUsd
2023-11-02 17:27:20 -07:00
isPrivate
2023-07-17 20:09:57 -07:00
/>
2023-07-17 19:58:20 -07:00
<span className="text-th-fgd-3">
{' '}
<FormatNumericValue
2023-07-17 20:09:57 -07:00
value={
collateralValue <= -0.01 ? liabWeight : assetWeight
}
2023-07-17 19:58:20 -07:00
/>
x
</span>
</p>
</div>
2023-07-22 15:59:39 -07:00
<div className="col-span-1">
<p className="text-xs text-th-fgd-3">
{t('trade:in-orders')}
</p>
2023-11-02 17:27:20 -07:00
<BankAmountWithValue
amount={inOrders}
bank={bank}
isPrivate
/>
2023-07-22 15:59:39 -07:00
</div>
<div className="col-span-1">
<p className="text-xs text-th-fgd-3">
{t('trade:unsettled')}
</p>
2023-11-02 17:27:20 -07:00
<BankAmountWithValue
amount={unsettled}
bank={bank}
isPrivate
/>
</div>
<div className="col-span-1">
<p className="text-xs text-th-fgd-3">
{t('interest-earned-paid')}
</p>
<BankAmountWithValue
amount={interestAmount}
bank={bank}
value={interestValue}
2023-11-02 17:27:20 -07:00
isPrivate
/>
</div>
<div className="col-span-1">
<p className="text-xs text-th-fgd-3">{t('rates')}</p>
<p className="space-x-2 font-mono">
<span className="text-th-up">
<FormatNumericValue value={depositRate} decimals={2} />%
</span>
<span className="font-normal text-th-fgd-4">|</span>
<span className="text-th-down">
<FormatNumericValue value={borrowRate} decimals={2} />%
</span>
</p>
</div>
<div className="col-span-1">
2023-10-03 22:05:16 -07:00
<ActionsMenu bank={bank} />
</div>
</div>
</Disclosure.Panel>
</Transition>
</>
)}
</Disclosure>
)
}
2023-10-03 22:05:16 -07:00
export const ActionsMenu = ({
bank,
2023-10-03 22:05:16 -07:00
showText,
}: {
bank: Bank
2023-10-03 22:05:16 -07:00
showText?: boolean
}) => {
const { t } = useTranslation('common')
2023-10-03 22:05:16 -07:00
const { mangoAccountAddress } = useMangoAccount()
const [showDepositModal, setShowDepositModal] = useState(false)
const [showWithdrawModal, setShowWithdrawModal] = useState(false)
const [showBorrowModal, setShowBorrowModal] = useState(false)
2022-11-16 04:14:53 -08:00
const [showRepayModal, setShowRepayModal] = useState(false)
const [selectedToken, setSelectedToken] = useState('')
2023-01-04 18:50:36 -08:00
const set = mangoStore.getState().set
const router = useRouter()
2023-01-04 20:06:19 -08:00
const spotMarkets = mangoStore((s) => s.serumMarkets)
const { isUnownedAccount } = useUnownedAccount()
2023-10-03 22:05:16 -07:00
const { isDesktop } = useViewport()
2023-01-04 20:06:19 -08:00
const spotMarket = useMemo(() => {
return spotMarkets.find((m) => {
const base = m.name.split('/')[0]
return base.toUpperCase() === bank.name.toUpperCase()
})
}, [spotMarkets])
const handleShowActionModals = useCallback(
2022-11-16 04:14:53 -08:00
(token: string, action: 'borrow' | 'deposit' | 'withdraw' | 'repay') => {
setSelectedToken(token)
action === 'borrow'
? setShowBorrowModal(true)
: action === 'deposit'
? setShowDepositModal(true)
2022-11-16 04:14:53 -08:00
: action === 'withdraw'
? setShowWithdrawModal(true)
: setShowRepayModal(true)
},
2023-07-21 11:47:53 -07:00
[],
)
2023-01-04 18:50:36 -08:00
const balance = useMemo(() => {
2023-10-03 22:05:16 -07:00
if (!mangoAccountAddress || !bank) return 0
const mangoAccount = mangoStore.getState().mangoAccount.current
if (mangoAccount) {
return mangoAccount.getTokenBalanceUi(bank)
} else return 0
}, [bank, mangoAccountAddress])
2023-01-04 18:50:36 -08:00
const handleSwap = useCallback(() => {
const group = mangoStore.getState().group
2023-10-11 04:11:29 -07:00
if (balance > 0) {
if (bank.name === 'USDC') {
const solBank = group?.getFirstBankByMint(WRAPPED_SOL_MINT)
set((s) => {
s.swap.inputBank = bank
s.swap.outputBank = solBank
})
} else {
2023-01-04 18:50:36 -08:00
const usdcBank = group?.getFirstBankByMint(new PublicKey(USDC_MINT))
set((s) => {
2023-10-11 04:11:29 -07:00
s.swap.inputBank = bank
s.swap.outputBank = usdcBank
2023-01-04 18:50:36 -08:00
})
}
} else {
2023-10-11 04:11:29 -07:00
if (bank.name === 'USDC') {
2023-01-04 18:50:36 -08:00
const solBank = group?.getFirstBankByMint(WRAPPED_SOL_MINT)
set((s) => {
s.swap.inputBank = solBank
2023-10-11 04:11:29 -07:00
s.swap.outputBank = bank
})
} else {
const usdcBank = group?.getFirstBankByMint(new PublicKey(USDC_MINT))
set((s) => {
s.swap.inputBank = usdcBank
s.swap.outputBank = bank
2023-01-04 18:50:36 -08:00
})
}
}
router.push('/swap', undefined, { shallow: true })
2023-10-11 04:11:29 -07:00
}, [bank, router, set])
2022-07-25 22:27:53 -07:00
2023-01-04 20:06:19 -08:00
const handleTrade = useCallback(() => {
router.push(`/trade?name=${spotMarket?.name}`, undefined, { shallow: true })
}, [spotMarket, router])
return (
<>
{isUnownedAccount ? null : (
<Popover>
{({ open }) => (
<div className="relative">
<Popover.Button
2023-10-03 22:05:16 -07:00
className={`flex items-center justify-center border border-th-button text-th-fgd-1 md:hover:border-th-button-hover md:hover:text-th-fgd-1 ${
showText || !isDesktop
? 'h-10 w-full rounded-md'
: 'h-8 w-8 rounded-full'
}`}
>
2023-10-03 22:05:16 -07:00
{showText || !isDesktop ? (
<span className="mr-2 font-display">{t('actions')}</span>
) : null}
{open ? (
<XMarkIcon className="h-5 w-5" />
) : (
<EllipsisHorizontalIcon className="h-5 w-5" />
)}
</Popover.Button>
<Transition
appear={true}
show={open}
as={Fragment}
enter="transition ease-in duration-100"
enterFrom="scale-90"
enterTo="scale-100"
leave="transition ease-out duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Popover.Panel
2023-10-03 22:05:16 -07:00
className={`thin-scroll absolute z-20 max-h-60 w-32 space-y-2 overflow-auto rounded-md bg-th-bkg-2 p-4 ${
isDesktop && !showText
? 'bottom-0 left-auto right-12 pt-2'
: 'bottom-12 left-0'
}`}
>
2023-10-03 22:05:16 -07:00
{!showText && isDesktop ? (
<div className="flex items-center justify-center border-b border-th-bkg-3 pb-2">
<div className="mr-2 flex flex-shrink-0 items-center">
<TokenLogo bank={bank} size={20} />
</div>
<p className="font-body">
{formatTokenSymbol(bank.name)}
</p>
</div>
2023-10-03 22:05:16 -07:00
) : null}
{bank.reduceOnly !== TOKEN_REDUCE_ONLY_OPTIONS.ENABLED ? (
<ActionsLinkButton
onClick={() =>
handleShowActionModals(bank.name, 'deposit')
}
>
{t('deposit')}
</ActionsLinkButton>
) : null}
{balance < 0 ? (
<ActionsLinkButton
onClick={() => handleShowActionModals(bank.name, 'repay')}
>
{t('repay')}
</ActionsLinkButton>
) : null}
{balance && balance > 0 ? (
<ActionsLinkButton
onClick={() =>
handleShowActionModals(bank.name, 'withdraw')
}
>
{t('withdraw')}
</ActionsLinkButton>
) : null}
{bank.reduceOnly === TOKEN_REDUCE_ONLY_OPTIONS.DISABLED ? (
<ActionsLinkButton
onClick={() =>
handleShowActionModals(bank.name, 'borrow')
}
>
{t('borrow')}
</ActionsLinkButton>
) : null}
2023-10-03 22:05:16 -07:00
<ActionsLinkButton onClick={handleSwap}>
{t('swap')}
</ActionsLinkButton>
{spotMarket ? (
2023-10-03 22:05:16 -07:00
<ActionsLinkButton onClick={handleTrade}>
{t('trade')}
</ActionsLinkButton>
) : null}
</Popover.Panel>
</Transition>
</div>
)}
</Popover>
)}
2022-07-24 19:55:10 -07:00
{showDepositModal ? (
<DepositWithdrawModal
action="deposit"
2022-07-24 19:55:10 -07:00
isOpen={showDepositModal}
onClose={() => setShowDepositModal(false)}
token={selectedToken}
/>
) : null}
{showWithdrawModal ? (
<DepositWithdrawModal
action="withdraw"
2022-07-24 19:55:10 -07:00
isOpen={showWithdrawModal}
onClose={() => setShowWithdrawModal(false)}
token={selectedToken}
/>
) : null}
{showBorrowModal ? (
2022-12-18 04:30:49 -08:00
<BorrowRepayModal
action="borrow"
2022-07-24 19:55:10 -07:00
isOpen={showBorrowModal}
onClose={() => setShowBorrowModal(false)}
token={selectedToken}
/>
) : null}
2022-11-16 04:14:53 -08:00
{showRepayModal ? (
2022-12-18 04:30:49 -08:00
<BorrowRepayModal
action="repay"
2022-11-16 04:14:53 -08:00
isOpen={showRepayModal}
onClose={() => setShowRepayModal(false)}
token={selectedToken}
/>
) : null}
</>
2022-05-03 21:20:14 -07:00
)
}