mango-v4-ui/components/swap/SwapFormTokenList.tsx

388 lines
12 KiB
TypeScript
Raw Normal View History

2023-07-19 20:19:03 -07:00
import { memo, useMemo, useEffect, useRef, useState, ChangeEvent } from 'react'
2022-07-16 04:22:59 -07:00
import { Token } from '../../types/jupiter'
2022-09-12 08:53:57 -07:00
import mangoStore from '@store/mangoStore'
2022-07-16 04:22:59 -07:00
import { IconButton } from '../shared/Button'
2023-07-19 20:19:03 -07:00
import { MagnifyingGlassIcon, XMarkIcon } from '@heroicons/react/20/solid'
2022-07-17 04:51:51 -07:00
import { useTranslation } from 'next-i18next'
2022-09-14 03:37:45 -07:00
import Decimal from 'decimal.js'
2022-09-14 17:02:16 -07:00
import { getTokenInMax } from './useTokenMax'
2022-11-18 09:09:39 -08:00
import useMangoAccount from 'hooks/useMangoAccount'
2022-11-18 11:11:06 -08:00
import useJupiterMints from 'hooks/useJupiterMints'
2022-11-20 12:32:38 -08:00
import useMangoGroup from 'hooks/useMangoGroup'
2022-12-19 14:41:22 -08:00
import { PublicKey } from '@solana/web3.js'
2023-01-24 17:12:13 -08:00
import FormatNumericValue from '@components/shared/FormatNumericValue'
2023-04-16 18:04:13 -07:00
import { formatTokenSymbol } from 'utils/tokens'
2023-07-04 21:40:47 -07:00
import TokenLogo from '@components/shared/TokenLogo'
2023-07-19 20:19:03 -07:00
import Input from '@components/forms/Input'
import { getInputTokenBalance } from './TriggerSwapForm'
2023-09-18 05:55:37 -07:00
import { walletBalanceForToken } from '@components/DepositForm'
import TokenReduceOnlyDesc from '@components/shared/TokenReduceOnlyDesc'
2022-07-16 04:22:59 -07:00
2023-09-06 06:06:57 -07:00
export type SwapFormTokenListType =
| 'input'
| 'output'
| 'reduce-input'
| 'reduce-output'
2023-09-18 05:55:37 -07:00
| 'wallet-input'
2023-09-06 06:06:57 -07:00
| undefined
2023-07-19 20:19:03 -07:00
const generateSearchTerm = (item: Token, searchValue: string) => {
const normalizedSearchValue = searchValue.toLowerCase()
const values = `${item.symbol} ${item.name}`.toLowerCase()
2022-07-16 04:22:59 -07:00
2023-07-19 20:19:03 -07:00
const isMatchingWithSymbol =
item.symbol.toLowerCase().indexOf(normalizedSearchValue) >= 0
const matchingSymbolPercent = isMatchingWithSymbol
? normalizedSearchValue.length / item.symbol.length
: 0
2022-07-16 04:22:59 -07:00
2023-07-19 20:19:03 -07:00
return {
token: item,
matchingIdx: values.indexOf(normalizedSearchValue),
matchingSymbolPercent,
}
}
2022-07-16 04:22:59 -07:00
2023-07-19 20:19:03 -07:00
const startSearch = (items: Token[], searchValue: string) => {
return items
.map((item) => generateSearchTerm(item, searchValue))
.filter((item) => item.matchingIdx >= 0)
.sort((i1, i2) => i1.matchingIdx - i2.matchingIdx)
.sort((i1, i2) => i2.matchingSymbolPercent - i1.matchingSymbolPercent)
.map((item) => item.token)
}
2022-07-16 04:22:59 -07:00
const TokenItem = ({
token,
onSubmit,
2022-09-14 03:37:45 -07:00
useMargin,
type,
2022-07-16 04:22:59 -07:00
}: {
token: TokenInfoWithAmounts
2022-07-16 04:22:59 -07:00
onSubmit: (x: string) => void
2022-09-14 03:37:45 -07:00
useMargin: boolean
2023-09-06 06:06:57 -07:00
type: SwapFormTokenListType
2022-07-16 04:22:59 -07:00
}) => {
2023-02-08 16:31:53 -08:00
const { t } = useTranslation('trade')
2023-07-04 21:40:47 -07:00
const { address, symbol, name } = token
2022-09-14 03:37:45 -07:00
2023-02-08 16:31:53 -08:00
const bank = useMemo(() => {
const group = mangoStore.getState().group
if (!group) return
2023-09-18 05:55:37 -07:00
// if we want to let users swap from tokens not listed on Mango.
// if (type === 'wallet-input') {
// const hasBank = Array.from(group.banksMapByName.values())
// .map((b) => b[0].mint.toString())
// .find((mint) => mint === address)
// if (hasBank) {
// return group.getFirstBankByMint(new PublicKey(address))
// }
// }
2023-02-08 16:31:53 -08:00
return group.getFirstBankByMint(new PublicKey(address))
2023-09-18 05:55:37 -07:00
}, [address, type])
2023-02-08 16:31:53 -08:00
// const isReduceOnly = useMemo(() => {
// if (!bank) return false
// const borrowsReduceOnly = bank.areBorrowsReduceOnly()
// const depositsReduceOnly = bank.areDepositsReduceOnly()
// return borrowsReduceOnly && depositsReduceOnly
// }, [bank])
2023-05-11 18:48:30 -07:00
2022-07-16 04:22:59 -07:00
return (
<div>
<button
key={address}
2023-04-19 18:12:45 -07:00
className={`flex w-full cursor-pointer items-center justify-between rounded-md p-2 font-normal focus:outline-none focus-visible:bg-th-bkg-3 md:hover:bg-th-bkg-2`}
2022-08-10 13:23:19 -07:00
onClick={() => onSubmit(address)}
2022-07-16 04:22:59 -07:00
>
<div className="flex items-center">
2023-09-18 05:55:37 -07:00
<TokenLogo bank={bank} logoUrl={!bank ? token.logoURI : ''} />
2022-07-16 04:22:59 -07:00
<div className="ml-2.5">
2023-02-08 16:31:53 -08:00
<p className="text-left text-th-fgd-2">
2023-04-16 18:04:13 -07:00
{bank?.name ? formatTokenSymbol(bank.name) : symbol || 'unknown'}
2023-09-06 20:51:57 -07:00
{type === 'reduce-input' && token.amount ? (
<span
className={`ml-1 rounded px-1 text-xxs uppercase ${
token.amount.gt(0) ? 'text-th-up' : 'text-th-down'
}`}
>
{t(`trade:${token.amount.gt(0) ? 'long' : 'short'}`)}
</span>
) : null}
<span className="ml-1">
<TokenReduceOnlyDesc bank={bank} />
</span>
2023-02-08 16:31:53 -08:00
</p>
<p className="text-left text-xs text-th-fgd-4">
2022-09-14 03:37:45 -07:00
{name || 'unknown'}
2023-02-08 16:31:53 -08:00
</p>
2022-07-16 04:22:59 -07:00
</div>
</div>
2023-09-18 05:55:37 -07:00
{type === 'input' || type === 'reduce-input' ? (
2023-01-09 18:18:47 -08:00
<p className="font-mono text-sm text-th-fgd-2">
2023-01-24 17:12:13 -08:00
{useMargin ? (
<FormatNumericValue
2023-09-18 05:55:37 -07:00
value={token.amountWithBorrow || 0}
2023-01-24 17:12:13 -08:00
decimals={token.decimals}
/>
) : (
<FormatNumericValue
2023-09-18 05:55:37 -07:00
value={token.amount || 0}
2023-01-24 17:12:13 -08:00
decimals={token.decimals}
/>
)}
2022-09-14 03:37:45 -07:00
</p>
2023-09-18 05:55:37 -07:00
) : type === 'wallet-input' ? (
<p className="font-mono text-sm text-th-fgd-2">
<FormatNumericValue
value={token.amount || 0}
decimals={token.decimals}
/>
</p>
2022-09-14 03:37:45 -07:00
) : null}
2022-07-16 04:22:59 -07:00
</button>
</div>
)
}
interface TokenInfoWithAmounts extends Token {
amount?: Decimal
amountWithBorrow?: Decimal
}
const SwapFormTokenList = ({
2022-07-16 04:22:59 -07:00
onClose,
onTokenSelect,
type,
2022-09-14 03:37:45 -07:00
useMargin,
2022-07-16 04:22:59 -07:00
}: {
onClose: () => void
onTokenSelect: (x: string) => void
2023-09-06 06:06:57 -07:00
type: SwapFormTokenListType
2022-09-14 03:37:45 -07:00
useMargin: boolean
2022-07-16 04:22:59 -07:00
}) => {
2023-07-19 20:19:03 -07:00
const { t } = useTranslation(['common', 'search', 'swap'])
const [search, setSearch] = useState('')
2023-09-18 05:55:37 -07:00
const { mangoTokens, jupiterTokens } = useJupiterMints()
const inputBank = mangoStore((s) => s.swap.inputBank)
const outputBank = mangoStore((s) => s.swap.outputBank)
2023-09-18 05:55:37 -07:00
const walletTokens = mangoStore((s) => s.wallet.tokens)
2022-11-20 12:32:38 -08:00
const { group } = useMangoGroup()
const { mangoAccount, mangoAccountAddress } = useMangoAccount()
2023-07-19 20:19:03 -07:00
const focusRef = useRef<HTMLInputElement>(null)
2022-07-16 04:22:59 -07:00
useEffect(() => {
2023-02-27 23:20:11 -08:00
function onEscape(e: KeyboardEvent) {
2022-07-16 04:22:59 -07:00
if (e.keyCode === 27) {
2022-08-02 11:04:00 -07:00
onClose()
2022-07-16 04:22:59 -07:00
}
}
window.addEventListener('keydown', onEscape)
return () => window.removeEventListener('keydown', onEscape)
}, [onClose])
const tokenInfos: TokenInfoWithAmounts[] = useMemo(() => {
2022-09-14 03:37:45 -07:00
if (
2023-09-18 05:55:37 -07:00
!mangoTokens.length ||
!group ||
!mangoAccount ||
!outputBank ||
!inputBank
)
return []
if (type === 'input') {
2022-11-18 11:11:06 -08:00
const filteredSortedTokens = mangoTokens
2022-09-14 03:37:45 -07:00
.map((token) => {
2023-09-18 05:55:37 -07:00
const tokenPk = new PublicKey(token.address)
const tokenBank = group.getFirstBankByMint(tokenPk)
const max = getTokenInMax(
mangoAccount,
2023-09-18 05:55:37 -07:00
tokenPk,
2022-12-12 21:38:12 -08:00
outputBank.mint,
group,
2023-07-21 11:47:53 -07:00
useMargin,
)
2023-09-18 05:55:37 -07:00
const price = tokenBank.uiPrice
return { ...token, ...max, price }
2022-09-14 03:37:45 -07:00
})
2023-09-18 05:55:37 -07:00
.filter((token) => (token.symbol === outputBank.name ? false : true))
2022-09-14 03:37:45 -07:00
.sort((a, b) =>
useMargin
2023-09-18 05:55:37 -07:00
? Number(b.amountWithBorrow.mul(b.price)) -
Number(a.amountWithBorrow.mul(a.price))
: Number(b.amount.mul(b.price)) - Number(a.amount.mul(a.price)),
2022-07-16 04:22:59 -07:00
)
2022-09-14 03:37:45 -07:00
2023-09-06 06:06:57 -07:00
return filteredSortedTokens
2023-09-18 05:55:37 -07:00
} else if (type === 'reduce-input') {
2023-09-06 06:06:57 -07:00
const filteredSortedTokens = mangoTokens
.map((token) => {
const tokenBank = group.getFirstBankByMint(
new PublicKey(token.address),
)
const uiAmount = mangoAccount.getTokenBalanceUi(tokenBank)
const uiDollarValue = uiAmount * tokenBank.uiPrice
return {
...token,
amount: new Decimal(uiAmount),
amountWithBorrow: new Decimal(uiAmount),
absDollarValue: Math.abs(uiDollarValue),
decimals: inputBank.mintDecimals,
}
})
.filter(
(token) =>
2023-09-18 05:55:37 -07:00
token.symbol !== outputBank.name && token.absDollarValue > 0.0001,
2023-09-06 06:06:57 -07:00
)
.sort((a, b) => b.absDollarValue - a.absDollarValue)
2022-09-14 03:37:45 -07:00
return filteredSortedTokens
2023-09-18 05:55:37 -07:00
} else if (type === 'wallet-input' && jupiterTokens.length) {
// if we want to let users swap from tokens not listed on Mango. Some other changes are need to pass the mint to the swap function
// const jupiterTokensWithAmount = []
// for (const token of jupiterTokens) {
// const hasToken = walletTokens.find(
// (t) => t.mint.toString() === token.address,
// )
// if (hasToken) {
// jupiterTokensWithAmount.push({
// ...token,
// amount: new Decimal(hasToken.uiAmount),
// })
// }
// }
// const filteredSortedTokens = jupiterTokensWithAmount
// .filter((token) =>
// token.symbol !== outputBank.name && token.amount.gt(0) ? true : false,
// )
// .sort((a, b) => Number(b.amount) - Number(a.amount))
const filteredSortedTokens = mangoTokens
.map((token) => {
const tokenBank = group.getFirstBankByMint(
new PublicKey(token.address),
)
const max = walletBalanceForToken(walletTokens, tokenBank.name)
const price = tokenBank.uiPrice
return {
...token,
amount: new Decimal(max.maxAmount),
decimals: max.maxDecimals,
price,
}
})
.filter((token) => (token.symbol === outputBank.name ? false : true))
.sort(
(a, b) =>
Number(b.amount.mul(b.price)) - Number(a.amount.mul(a.price)),
)
return filteredSortedTokens
} else if (mangoTokens.length) {
2022-11-18 11:11:06 -08:00
const filteredTokens = mangoTokens
2022-09-14 03:37:45 -07:00
.map((token) => ({
...token,
2022-09-14 17:02:16 -07:00
amount: new Decimal(0),
amountWithBorrow: new Decimal(0),
2022-09-14 03:37:45 -07:00
}))
2023-09-18 05:55:37 -07:00
.filter((token) => (token.symbol === inputBank.name ? false : true))
2023-01-05 20:46:36 -08:00
.sort((a, b) => a.symbol.localeCompare(b.symbol))
2022-09-14 03:37:45 -07:00
return filteredTokens
2023-09-18 05:55:37 -07:00
} else return []
}, [
mangoTokens,
jupiterTokens,
inputBank,
outputBank,
mangoAccount,
group,
useMargin,
type,
])
2022-07-16 04:22:59 -07:00
2023-07-19 20:19:03 -07:00
const handleUpdateSearch = (e: ChangeEvent<HTMLInputElement>) => {
setSearch(e.target.value)
}
2022-07-16 04:22:59 -07:00
2023-07-19 20:19:03 -07:00
const sortedTokens = search ? startSearch(tokenInfos, search) : tokenInfos
2022-07-16 04:22:59 -07:00
useEffect(() => {
if (focusRef?.current) {
focusRef.current.focus()
}
}, [focusRef])
2023-09-06 20:51:57 -07:00
const listTitle = useMemo(() => {
if (!type) return ''
2023-09-18 05:55:37 -07:00
if (type === 'input' || type === 'wallet-input') {
2023-09-06 20:51:57 -07:00
return t('swap:you-sell')
} else if (type === 'output') {
return t('swap:you-buy')
} else if (type === 'reduce-input') {
return t('swap:reduce-position')
} else {
if (!mangoAccountAddress || !inputBank) return ''
const uiPos = getInputTokenBalance(inputBank)
2023-09-06 20:51:57 -07:00
if (uiPos > 0) {
return t('swap:reduce-position-buy')
} else if (uiPos < 0) {
return t('swap:reduce-position-sell')
}
}
}, [inputBank, mangoAccountAddress, type])
2023-09-06 20:51:57 -07:00
2022-07-16 04:22:59 -07:00
return (
<>
2023-09-06 20:51:57 -07:00
<p className="mb-3">{listTitle}</p>
2022-10-08 03:15:03 -07:00
<IconButton
className="absolute right-2 top-2 text-th-fgd-3 hover:text-th-fgd-2"
2022-10-08 03:15:03 -07:00
onClick={onClose}
hideBg
>
2022-09-29 21:21:23 -07:00
<XMarkIcon className="h-6 w-6" />
2022-07-16 04:22:59 -07:00
</IconButton>
2023-07-19 20:19:03 -07:00
<div className="relative mb-4">
2022-07-16 04:22:59 -07:00
<Input
2023-07-19 20:19:03 -07:00
className="pl-10"
2022-07-16 04:22:59 -07:00
type="text"
placeholder="Search by token or paste address"
autoFocus
value={search}
onChange={handleUpdateSearch}
2023-07-19 20:19:03 -07:00
ref={focusRef}
2022-07-16 04:22:59 -07:00
/>
2023-07-19 20:19:03 -07:00
<MagnifyingGlassIcon className="absolute left-3 top-3.5 h-5 w-5" />
2022-07-16 04:22:59 -07:00
</div>
2023-07-19 20:19:03 -07:00
<div className="flex justify-between rounded bg-th-bkg-2 p-2">
2022-09-14 03:37:45 -07:00
<p className="text-xs text-th-fgd-4">{t('token')}</p>
2023-09-07 06:59:24 -07:00
{!type?.includes('output') ? (
2022-09-14 03:37:45 -07:00
<p className="text-xs text-th-fgd-4">{t('max')}</p>
) : null}
</div>
2023-07-19 20:19:03 -07:00
<div className="thin-scroll h-[calc(100%-128px)] overflow-auto py-2">
{sortedTokens?.length ? (
sortedTokens.map((token) => (
<TokenItem
key={token.address}
token={token}
onSubmit={onTokenSelect}
useMargin={useMargin}
type={type}
/>
))
) : (
<div className="mt-2 rounded-md border border-th-bkg-3 p-3">
<p className="text-center">{t('search:no-results')}</p>
</div>
)}
2022-07-16 04:22:59 -07:00
</div>
</>
)
}
export default memo(SwapFormTokenList)