mango-v4-ui/components/trade/UnsettledTrades.tsx

287 lines
10 KiB
TypeScript
Raw Normal View History

import mangoStore from '@store/mangoStore'
import { useTranslation } from 'next-i18next'
2022-10-03 19:26:50 -07:00
import { useCallback, useState } from 'react'
2022-09-28 18:50:02 -07:00
import { PublicKey } from '@solana/web3.js'
2022-10-02 22:42:28 -07:00
import { IconButton } from '@components/shared/Button'
2022-09-28 18:50:02 -07:00
import { notify } from 'utils/notifications'
2023-01-03 03:06:37 -08:00
import { CheckIcon, NoSymbolIcon } from '@heroicons/react/20/solid'
2022-10-02 22:42:28 -07:00
import Tooltip from '@components/shared/Tooltip'
2022-10-03 17:59:25 -07:00
import Loading from '@components/shared/Loading'
2022-10-03 20:42:05 -07:00
import { useViewport } from 'hooks/useViewport'
import { breakpoints } from 'utils/theme'
2022-11-20 02:44:14 -08:00
import { Table, Td, Th, TrBody, TrHead } from '@components/shared/TableElements'
2022-11-20 12:32:38 -08:00
import useMangoGroup from 'hooks/useMangoGroup'
2022-12-07 21:06:06 -08:00
import { PerpMarket, PerpPosition } from '@blockworks-foundation/mango-v4'
2022-12-11 18:43:16 -08:00
import TableMarketName from './TableMarketName'
import useMangoAccount from 'hooks/useMangoAccount'
import { useWallet } from '@solana/wallet-adapter-react'
2023-01-06 11:41:18 -08:00
import { formatDecimal } from 'utils/numbers'
2022-10-02 22:42:28 -07:00
const UnsettledTrades = ({
unsettledSpotBalances,
2022-11-20 18:29:51 -08:00
unsettledPerpPositions,
2022-10-02 22:42:28 -07:00
}: {
unsettledSpotBalances: any
2022-11-20 18:29:51 -08:00
unsettledPerpPositions: PerpPosition[]
2022-10-02 22:42:28 -07:00
}) => {
2022-10-03 03:38:05 -07:00
const { t } = useTranslation(['common', 'trade'])
2022-11-20 12:32:38 -08:00
const { group } = useMangoGroup()
2022-10-03 17:59:25 -07:00
const [settleMktAddress, setSettleMktAddress] = useState<string>('')
2022-10-03 20:42:05 -07:00
const { width } = useViewport()
const showTableView = width ? width > breakpoints.md : false
const { mangoAccount } = useMangoAccount()
const { connected } = useWallet()
2022-12-07 21:06:06 -08:00
const handleSettleSerumFunds = useCallback(async (mktAddress: string) => {
2022-09-28 18:50:02 -07:00
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const mangoAccount = mangoStore.getState().mangoAccount.current
const actions = mangoStore.getState().actions
if (!group || !mangoAccount) return
2022-10-03 17:59:25 -07:00
setSettleMktAddress(mktAddress)
2022-12-07 21:06:06 -08:00
2022-09-28 18:50:02 -07:00
try {
const txid = await client.serum3SettleFunds(
group,
mangoAccount,
new PublicKey(mktAddress)
)
2022-10-31 11:26:17 -07:00
actions.fetchOpenOrders()
2022-09-28 18:50:02 -07:00
notify({
type: 'success',
title: 'Successfully settled funds',
txid,
})
} catch (e: any) {
notify({
type: 'error',
2022-10-03 17:59:25 -07:00
title: t('trade:settle-funds-error'),
2022-09-28 18:50:02 -07:00
description: e?.message,
txid: e?.txid,
})
console.error('Settle funds error:', e)
2022-10-03 17:59:25 -07:00
} finally {
setSettleMktAddress('')
}
2022-09-28 18:50:02 -07:00
}, [])
2022-12-07 21:06:06 -08:00
const handleSettlePerpFunds = useCallback(async (market: PerpMarket) => {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const mangoAccount = mangoStore.getState().mangoAccount.current
const actions = mangoStore.getState().actions
if (!group || !mangoAccount) return
setSettleMktAddress(market.publicKey.toString())
try {
const mangoAccounts = await client.getAllMangoAccounts(group)
const perpPosition = mangoAccount.getPerpPosition(market.perpMarketIndex)
2022-12-08 11:58:54 -08:00
const mangoAccountPnl = perpPosition?.getEquityUi(group, market)
2022-12-07 21:06:06 -08:00
if (mangoAccountPnl === undefined)
throw new Error('Unable to get account P&L')
const sign = Math.sign(mangoAccountPnl)
const filteredAccounts = mangoAccounts
.map((m) => ({
mangoAccount: m,
pnl:
2022-12-08 11:58:54 -08:00
m
?.getPerpPosition(market.perpMarketIndex)
?.getEquityUi(group, market) || 0,
2022-12-07 21:06:06 -08:00
}))
.sort((a, b) => sign * (a.pnl - b.pnl))
const profitableAccount =
mangoAccountPnl >= 0 ? mangoAccount : filteredAccounts[0].mangoAccount
const unprofitableAccount =
mangoAccountPnl < 0 ? mangoAccount : filteredAccounts[0].mangoAccount
// const profitableAccount = mangoAccount
// const unprofitableAccount =
// filteredAccounts[filteredAccounts.length - 1].mangoAccount
// console.log('unprofitableAccount', unprofitableAccount)
const txid = await client.perpSettlePnl(
group,
profitableAccount,
unprofitableAccount,
mangoAccount,
market.perpMarketIndex
)
actions.reloadMangoAccount()
notify({
type: 'success',
title: 'Successfully settled P&L',
txid,
})
} catch (e: any) {
notify({
type: 'error',
title: 'Settle P&L error',
description: e?.message,
txid: e?.txid,
})
console.error('Settle P&L error:', e)
} finally {
setSettleMktAddress('')
}
}, [])
2022-09-28 18:50:02 -07:00
if (!group) return null
return mangoAccount &&
2022-11-20 18:29:51 -08:00
Object.values(unsettledSpotBalances).flat().concat(unsettledPerpPositions)
.length ? (
showTableView ? (
<Table>
<thead>
<TrHead>
<Th className="bg-th-bkg-1 text-left">{t('market')}</Th>
<Th className="bg-th-bkg-1 text-right">{t('trade:amount')}</Th>
{connected ? <Th className="bg-th-bkg-1 text-right" /> : null}
</TrHead>
</thead>
<tbody>
2022-11-19 11:20:36 -08:00
{Object.entries(unsettledSpotBalances).map(([mktAddress]) => {
const market = group.getSerum3MarketByExternalMarket(
new PublicKey(mktAddress)
)
const base = market?.name.split('/')[0]
const quote = market?.name.split('/')[1]
return (
<TrBody key={mktAddress} className="text-sm">
<Td>
<TableMarketName market={market} />
</Td>
<Td className="text-right font-mono">
<div className="flex justify-end">
{unsettledSpotBalances[mktAddress].base ? (
<div>
{unsettledSpotBalances[mktAddress].base}{' '}
<span className="font-body text-th-fgd-4">{base}</span>
</div>
) : null}
{unsettledSpotBalances[mktAddress].quote ? (
<div className="ml-4">
{unsettledSpotBalances[mktAddress].quote}{' '}
<span className="font-body text-th-fgd-4">{quote}</span>
</div>
) : null}
</div>
</Td>
{connected ? (
<Td>
<div className="flex justify-end">
<Tooltip content={t('trade:settle-funds')}>
<IconButton
onClick={() => handleSettleSerumFunds(mktAddress)}
size="small"
>
{settleMktAddress === mktAddress ? (
<Loading className="h-4 w-4" />
) : (
<CheckIcon className="h-4 w-4" />
)}
</IconButton>
</Tooltip>
</div>
</Td>
) : null}
</TrBody>
2022-11-19 11:20:36 -08:00
)
})}
{unsettledPerpPositions.map((position) => {
const market = group.getPerpMarketByMarketIndex(
position.marketIndex
)
return (
<TrBody key={position.marketIndex} className="text-sm">
<Td>
<TableMarketName market={market} />
</Td>
<Td className="text-right font-mono">
2023-01-06 11:41:18 -08:00
{formatDecimal(
position.getUnsettledPnlUi(group, market),
2023-01-06 11:41:18 -08:00
market.baseDecimals
)}
</Td>
<Td>
<div className="flex justify-end">
<Tooltip content={t('trade:settle-funds')}>
<IconButton
onClick={() => handleSettlePerpFunds(market)}
size="small"
>
{settleMktAddress === market.publicKey.toString() ? (
<Loading className="h-4 w-4" />
) : (
<CheckIcon className="h-4 w-4" />
)}
</IconButton>
</Tooltip>
</div>
</Td>
</TrBody>
)
})}
</tbody>
</Table>
2022-10-02 22:42:28 -07:00
) : (
<div className="pb-20">
{Object.entries(unsettledSpotBalances).map(([mktAddress]) => {
const market = group.getSerum3MarketByExternalMarket(
new PublicKey(mktAddress)
)
const base = market?.name.split('/')[0]
const quote = market?.name.split('/')[1]
return (
<div
key={mktAddress}
className="flex items-center justify-between border-b border-th-bkg-3 p-4"
>
<TableMarketName market={market} />
<div className="flex items-center space-x-3">
{unsettledSpotBalances[mktAddress].base ? (
<span className="font-mono text-sm">
{unsettledSpotBalances[mktAddress].base}{' '}
<span className="font-body text-th-fgd-4">{base}</span>
</span>
) : null}
{unsettledSpotBalances[mktAddress].quote ? (
<span className="font-mono text-sm">
{unsettledSpotBalances[mktAddress].quote}{' '}
<span className="font-body text-th-fgd-4">{quote}</span>
</span>
) : null}
{connected ? (
<IconButton
onClick={() => handleSettleSerumFunds(mktAddress)}
2023-01-19 15:49:49 -08:00
size="medium"
>
{settleMktAddress === mktAddress ? (
<Loading className="h-4 w-4" />
) : (
<CheckIcon className="h-4 w-4" />
)}
</IconButton>
) : null}
</div>
</div>
)
})}
2022-10-02 22:42:28 -07:00
</div>
)
) : (
<div className="flex flex-col items-center p-8">
<NoSymbolIcon className="mb-2 h-6 w-6 text-th-fgd-4" />
<p>{t('trade:no-unsettled')}</p>
2022-10-02 22:42:28 -07:00
</div>
)
}
export default UnsettledTrades