mango-v4-ui/components/WithdrawForm.tsx

315 lines
11 KiB
TypeScript
Raw Normal View History

2023-01-29 20:13:38 -08:00
import { HealthType } from '@blockworks-foundation/mango-v4'
import {
ArrowUpTrayIcon,
ExclamationCircleIcon,
2023-08-03 21:02:26 -07:00
// ExclamationCircleIcon,
} from '@heroicons/react/20/solid'
import Decimal from 'decimal.js'
import { useTranslation } from 'next-i18next'
import { useCallback, useMemo, useState } from 'react'
import NumberFormat, { NumberFormatValues } from 'react-number-format'
import mangoStore from '@store/mangoStore'
2022-12-18 04:30:49 -08:00
import {
ACCOUNT_ACTION_MODAL_INNER_HEIGHT,
INPUT_TOKEN_DEFAULT,
} from './../utils/constants'
import { notify } from './../utils/notifications'
import ActionTokenList from './account/ActionTokenList'
import ButtonGroup from './forms/ButtonGroup'
import Label from './forms/Label'
import Button from './shared/Button'
import InlineNotification from './shared/InlineNotification'
import Loading from './shared/Loading'
import { EnterBottomExitBottom, FadeInFadeOut } from './shared/Transitions'
import { withValueLimit } from './swap/MarketSwapForm'
import { getMaxWithdrawForBank } from './swap/useTokenMax'
import MaxAmountButton from '@components/shared/MaxAmountButton'
import HealthImpactTokenChange from '@components/HealthImpactTokenChange'
import useMangoAccount from 'hooks/useMangoAccount'
import useMangoGroup from 'hooks/useMangoGroup'
import TokenVaultWarnings from '@components/shared/TokenVaultWarnings'
import { useWallet } from '@solana/wallet-adapter-react'
import { floorToDecimal } from 'utils/numbers'
2023-01-28 17:13:36 -08:00
import BankAmountWithValue from './shared/BankAmountWithValue'
2023-01-29 20:13:38 -08:00
import useBanksWithBalances from 'hooks/useBanksWithBalances'
2023-02-27 23:20:11 -08:00
import { isMangoError } from 'types'
import TokenListButton from './shared/TokenListButton'
2023-04-05 20:24:29 -07:00
import { ACCOUNT_ACTIONS_NUMBER_FORMAT_CLASSES, BackButton } from './BorrowForm'
2023-07-04 21:40:47 -07:00
import TokenLogo from './shared/TokenLogo'
2023-08-15 05:29:10 -07:00
import SecondaryConnectButton from './shared/SecondaryConnectButton'
interface WithdrawFormProps {
onSuccess: () => void
token?: string
}
function WithdrawForm({ onSuccess, token }: WithdrawFormProps) {
const { t } = useTranslation(['common', 'trade'])
const { group } = useMangoGroup()
const [inputAmount, setInputAmount] = useState('')
const [submitting, setSubmitting] = useState(false)
const [selectedToken, setSelectedToken] = useState(
2023-07-21 11:47:53 -07:00
token || INPUT_TOKEN_DEFAULT,
)
const [showTokenList, setShowTokenList] = useState(false)
const [sizePercentage, setSizePercentage] = useState('')
const { mangoAccount } = useMangoAccount()
2023-08-15 05:29:10 -07:00
const { connected } = useWallet()
2023-01-29 20:13:38 -08:00
const banks = useBanksWithBalances('maxWithdraw')
const bank = useMemo(() => {
const group = mangoStore.getState().group
return group?.banksMapByName.get(selectedToken)?.[0]
}, [selectedToken])
2023-11-27 03:33:33 -08:00
const [tokenMax, decimals] = useMemo(() => {
if (!bank || !mangoAccount || !group) return [new Decimal(0), undefined]
const tokenMax = getMaxWithdrawForBank(group, bank, mangoAccount).toNumber()
2023-11-27 03:33:33 -08:00
const decimals = floorToDecimal(tokenMax, bank.mintDecimals).toNumber()
? bank.mintDecimals
: undefined
const roundedMax = decimals ? floorToDecimal(tokenMax, decimals) : tokenMax
// Note: Disable for now, not sure why this was added, we can re-renable with specific conditions when
// need is realized
// const balance = mangoAccount.getTokenBalanceUi(bank)
// if (tokenMax < balance) {
// adjustedTokenMax = tokenMax * 0.998
// }
2023-11-27 03:33:33 -08:00
return [new Decimal(roundedMax), decimals]
}, [mangoAccount, bank, group])
const handleSizePercentage = useCallback(
(percentage: string) => {
2023-01-05 20:10:25 -08:00
if (!bank) return
setSizePercentage(percentage)
let amount: Decimal
if (percentage !== '100') {
2023-11-27 03:33:33 -08:00
amount = new Decimal(tokenMax).mul(percentage).div(100)
} else {
2023-11-27 03:33:33 -08:00
amount = new Decimal(tokenMax)
}
setInputAmount(amount.toFixed())
},
2023-11-27 03:33:33 -08:00
[bank, decimals, tokenMax],
)
const setMax = useCallback(() => {
if (!bank) return
2023-11-27 03:33:33 -08:00
setInputAmount(tokenMax.toFixed())
setSizePercentage('100')
2023-11-27 03:33:33 -08:00
}, [bank, tokenMax])
const handleWithdraw = useCallback(async () => {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const mangoAccount = mangoStore.getState().mangoAccount.current
const actions = mangoStore.getState().actions
const withdrawAmount = parseFloat(inputAmount)
if (!mangoAccount || !group || !bank) return
setSubmitting(true)
const withdrawAll =
2023-11-27 03:33:33 -08:00
floorToDecimal(tokenMax, bank.mintDecimals).eq(
new Decimal(inputAmount),
) || sizePercentage === '100'
try {
const { signature: tx, slot } = withdrawAll
? await client.tokenWithdrawAllDepositForMint(
group,
mangoAccount,
bank.mint,
)
: await client.tokenWithdraw(
group,
mangoAccount,
bank.mint,
withdrawAmount,
false,
)
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx,
})
await actions.reloadMangoAccount(slot)
setSubmitting(false)
onSuccess()
2023-02-27 23:20:11 -08:00
} catch (e) {
console.error(e)
2023-02-27 23:20:11 -08:00
setSubmitting(false)
if (!isMangoError(e)) return
notify({
title: 'Transaction failed',
description: e.message,
txid: e?.txid,
type: 'error',
})
}
2023-11-27 03:33:33 -08:00
}, [tokenMax, bank, inputAmount, sizePercentage])
const handleSelectToken = useCallback((token: string) => {
setSelectedToken(token)
setShowTokenList(false)
}, [])
const initHealth = useMemo(() => {
return group && mangoAccount
? mangoAccount.getHealthRatioUi(group, HealthType.init)
: 100
}, [mangoAccount])
const showInsufficientBalance = inputAmount
? tokenMax.lt(new Decimal(inputAmount))
: false
return (
<>
<EnterBottomExitBottom
className="absolute bottom-0 left-0 z-20 h-full w-full overflow-auto rounded-lg bg-th-bkg-1 p-6"
show={showTokenList}
>
2023-03-26 20:11:10 -07:00
<BackButton onClick={() => setShowTokenList(false)} />
<h2 className="mb-4 text-center text-lg">
{t('select-withdraw-token')}
</h2>
<div className="flex items-center px-4 pb-2">
<div className="w-1/2 text-left">
<p className="text-xs">{t('token')}</p>
</div>
<div className="w-1/2 text-right">
<p className="text-xs">{t('available-balance')}</p>
</div>
</div>
<ActionTokenList
2023-01-29 20:13:38 -08:00
banks={banks}
onSelect={handleSelectToken}
2023-01-29 20:13:38 -08:00
valueKey="maxWithdraw"
/>
</EnterBottomExitBottom>
<FadeInFadeOut show={!showTokenList}>
<div
className="flex flex-col justify-between"
style={{ height: ACCOUNT_ACTION_MODAL_INNER_HEIGHT }}
>
<div>
{initHealth <= 0 ? (
<div className="mb-4">
<InlineNotification
type="error"
desc="You have no available collateral to withdraw."
/>
</div>
) : null}
2023-01-09 15:47:18 -08:00
{bank ? <TokenVaultWarnings bank={bank} type="withdraw" /> : null}
<div className="grid grid-cols-2">
<div className="col-span-2 flex justify-between">
<Label text={`${t('withdraw')} ${t('token')}`} />
2023-01-05 20:10:25 -08:00
{bank ? (
<MaxAmountButton
className="mb-2"
2023-11-27 03:33:33 -08:00
decimals={decimals}
2023-01-05 20:10:25 -08:00
label={t('max')}
onClick={setMax}
2023-11-27 03:33:33 -08:00
value={tokenMax}
2023-01-05 20:10:25 -08:00
/>
) : null}
</div>
<div className="col-span-1">
<TokenListButton
token={selectedToken}
2023-07-04 21:40:47 -07:00
logo={<TokenLogo bank={bank} />}
setShowList={setShowTokenList}
/>
</div>
<div className="col-span-1">
<NumberFormat
name="amountIn"
id="amountIn"
inputMode="decimal"
thousandSeparator=","
allowNegative={false}
isNumericString={true}
2023-12-04 15:36:02 -08:00
decimalScale={decimals}
2023-04-05 20:24:29 -07:00
className={ACCOUNT_ACTIONS_NUMBER_FORMAT_CLASSES}
placeholder="0.00"
value={inputAmount}
onValueChange={(e: NumberFormatValues) =>
setInputAmount(
2023-07-21 11:47:53 -07:00
!Number.isNaN(Number(e.value)) ? e.value : '',
)
}
isAllowed={withValueLimit}
/>
</div>
<div className="col-span-2 mt-2">
<ButtonGroup
activeValue={sizePercentage}
className="font-mono"
onChange={(p) => handleSizePercentage(p)}
values={['10', '25', '50', '75', '100']}
unit="%"
/>
</div>
</div>
{bank ? (
2023-01-09 19:57:56 -08:00
<div className="my-6 space-y-1.5 border-y border-th-bkg-3 px-2 py-4">
<HealthImpactTokenChange
mintPk={bank.mint}
uiAmount={Number(inputAmount)}
/>
<div className="flex justify-between">
<p>{t('withdraw-amount')}</p>
2023-11-27 03:33:33 -08:00
<BankAmountWithValue
amount={inputAmount}
bank={bank}
decimals={decimals}
fixDecimals={false}
/>
</div>
</div>
) : null}
</div>
2023-08-15 05:29:10 -07:00
{connected ? (
<Button
onClick={handleWithdraw}
className="flex w-full items-center justify-center"
size="large"
disabled={
connected &&
(!inputAmount || showInsufficientBalance || initHealth <= 0)
2023-08-15 05:29:10 -07:00
}
>
{submitting ? (
<Loading className="mr-2 h-5 w-5" />
) : showInsufficientBalance ? (
<div className="flex items-center">
<ExclamationCircleIcon className="mr-2 h-5 w-5 flex-shrink-0" />
{t('swap:insufficient-balance', {
symbol: selectedToken,
})}
</div>
2023-08-15 05:29:10 -07:00
) : (
<div className="flex items-center">
<ArrowUpTrayIcon className="mr-2 h-5 w-5" />
{t('withdraw')}
</div>
)}
</Button>
) : (
<SecondaryConnectButton
className="flex w-full items-center justify-center"
isLarge
/>
)}
</div>
</FadeInFadeOut>
</>
)
}
export default WithdrawForm