mango-v4-ui/components/BorrowForm.tsx

381 lines
14 KiB
TypeScript
Raw Normal View History

2023-01-29 20:13:38 -08:00
import { HealthType } from '@blockworks-foundation/mango-v4'
2022-09-06 21:36:35 -07:00
import {
2022-12-18 18:08:49 -08:00
ArrowLeftIcon,
2022-12-18 14:57:57 -08:00
ArrowUpLeftIcon,
2022-12-28 16:45:09 -08:00
ArrowUpTrayIcon,
2022-09-06 21:36:35 -07:00
ExclamationCircleIcon,
} from '@heroicons/react/20/solid'
import Decimal from 'decimal.js'
2022-07-24 19:55:10 -07:00
import { useTranslation } from 'next-i18next'
2022-10-05 04:01:03 -07:00
import React, { useCallback, useMemo, useState } from 'react'
2022-12-27 14:24:58 -08:00
import NumberFormat, {
NumberFormatValues,
SourceInfo,
} from 'react-number-format'
2022-09-12 08:53:57 -07:00
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'
2022-12-18 04:30:49 -08:00
import { getMaxWithdrawForBank } from './swap/useTokenMax'
2022-10-05 16:03:10 -07:00
import MaxAmountButton from '@components/shared/MaxAmountButton'
2022-11-04 11:55:21 -07:00
import HealthImpactTokenChange from '@components/HealthImpactTokenChange'
2022-11-16 19:18:22 -08:00
import Tooltip from '@components/shared/Tooltip'
2022-11-18 09:09:39 -08:00
import useMangoAccount from 'hooks/useMangoAccount'
2022-11-20 12:32:38 -08:00
import useMangoGroup from 'hooks/useMangoGroup'
2022-11-27 04:36:12 -08:00
import TokenVaultWarnings from '@components/shared/TokenVaultWarnings'
import { useWallet } from '@solana/wallet-adapter-react'
2023-01-24 17:12:13 -08:00
import FormatNumericValue from './shared/FormatNumericValue'
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-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'
2022-12-18 04:30:49 -08:00
interface BorrowFormProps {
onSuccess: () => void
2022-07-24 19:55:10 -07:00
token?: string
}
2023-04-05 20:24:29 -07:00
export const ACCOUNT_ACTIONS_NUMBER_FORMAT_CLASSES =
2023-04-19 18:12:45 -07:00
'w-full rounded-lg rounded-l-none border border-th-input-border bg-th-input-bkg p-3 text-right font-mono text-xl text-th-fgd-1 focus-visible:border-th-fgd-4 focus:outline-none md:hover:border-th-input-border-hover md:hover:focus-visible:border-th-fgd-4'
2023-04-05 20:24:29 -07:00
2022-12-18 04:30:49 -08:00
function BorrowForm({ onSuccess, token }: BorrowFormProps) {
2022-07-24 19:55:10 -07:00
const { t } = useTranslation('common')
2022-11-20 12:32:38 -08:00
const { group } = useMangoGroup()
2022-07-24 19:55:10 -07:00
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,
)
2022-07-24 19:55:10 -07:00
const [showTokenList, setShowTokenList] = useState(false)
const [sizePercentage, setSizePercentage] = useState('')
2022-11-18 09:09:39 -08:00
const { mangoAccount } = useMangoAccount()
2023-08-15 05:29:10 -07:00
const { connected, publicKey } = useWallet()
2023-01-29 20:13:38 -08:00
const banks = useBanksWithBalances('maxBorrow')
2022-08-15 15:18:23 -07:00
const bank = useMemo(() => {
const group = mangoStore.getState().group
2022-12-19 16:08:46 -08:00
return group?.banksMapByName.get(selectedToken)?.[0]
2022-08-15 15:18:23 -07:00
}, [selectedToken])
const tokenMax = useMemo(() => {
const group = mangoStore.getState().group
if (!group || !bank || !mangoAccount) return new Decimal(0)
2022-11-21 21:00:26 -08:00
const amount = getMaxWithdrawForBank(group, bank, mangoAccount, true)
return amount && amount.gt(0) ? new Decimal(amount) : new Decimal(0)
}, [mangoAccount, bank])
2022-08-15 15:18:23 -07:00
2022-12-28 16:45:09 -08:00
const tokenBalance = useMemo(() => {
if (!bank || !mangoAccount) return new Decimal(0)
const balance = new Decimal(mangoAccount.getTokenBalanceUi(bank))
2023-01-08 15:08:23 -08:00
return balance.gt(0) ? balance : new Decimal(0)
2022-12-28 16:45:09 -08:00
}, [bank, mangoAccount])
const isBorrow = parseFloat(inputAmount) > tokenBalance.toNumber()
2022-08-15 15:18:23 -07:00
const handleSizePercentage = useCallback(
(percentage: string) => {
if (!bank) return
2022-08-15 15:18:23 -07:00
setSizePercentage(percentage)
const amount = floorToDecimal(
new Decimal(percentage).div(100).mul(tokenMax),
2023-07-21 11:47:53 -07:00
bank.mintDecimals,
)
2023-02-10 01:41:06 -08:00
setInputAmount(amount.toFixed())
2022-08-15 15:18:23 -07:00
},
2023-07-21 11:47:53 -07:00
[tokenMax, bank],
2022-08-15 15:18:23 -07:00
)
2022-07-24 19:55:10 -07:00
2022-12-27 14:24:58 -08:00
const setMax = useCallback(() => {
2023-01-05 20:10:25 -08:00
if (!bank) return
const max = floorToDecimal(tokenMax, bank.mintDecimals)
2023-02-10 01:41:06 -08:00
setInputAmount(max.toFixed())
2022-12-27 14:24:58 -08:00
handleSizePercentage('100')
2023-01-05 20:10:25 -08:00
}, [bank, tokenMax, handleSizePercentage])
2022-12-27 14:24:58 -08:00
2022-07-24 19:55:10 -07:00
const handleSelectToken = (token: string) => {
setSelectedToken(token)
setShowTokenList(false)
}
2023-01-11 15:02:30 -08:00
const handleBorrow = useCallback(async () => {
2022-08-15 15:18:23 -07:00
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const mangoAccount = mangoStore.getState().mangoAccount.current
const actions = mangoStore.getState().actions
if (!mangoAccount || !group || !publicKey) return
2022-08-15 15:18:23 -07:00
setSubmitting(true)
try {
const { signature: tx, slot } = await client.tokenWithdraw(
2022-08-15 15:18:23 -07:00
group,
mangoAccount,
bank!.mint,
2022-10-07 15:27:36 -07:00
Number(inputAmount),
2023-07-21 11:47:53 -07:00
true,
2022-08-15 15:18:23 -07:00
)
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx,
})
await actions.reloadMangoAccount(slot)
actions.fetchWalletTokens(publicKey)
2022-12-18 04:30:49 -08:00
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
2022-08-15 15:18:23 -07:00
notify({
title: 'Transaction failed',
description: e.message,
2023-02-27 23:20:11 -08:00
txid: e.txid,
2022-08-15 15:18:23 -07:00
type: 'error',
})
}
}, [bank, inputAmount, onSuccess, publicKey])
2022-08-15 15:18:23 -07:00
2022-12-27 14:24:58 -08:00
const handleInputChange = (e: NumberFormatValues, info: SourceInfo) => {
if (info.source === 'event') {
setSizePercentage('')
}
setInputAmount(!Number.isNaN(Number(e.value)) ? e.value : '')
}
2022-08-25 20:46:23 -07:00
const initHealth = useMemo(() => {
return group && mangoAccount
? mangoAccount.getHealthRatioUi(group, HealthType.init)
: 100
2022-12-19 16:08:46 -08:00
}, [mangoAccount, group])
2022-08-25 20:46:23 -07:00
const showInsufficientBalance = Number(inputAmount)
? tokenMax.lt(inputAmount)
: false
2022-08-25 17:27:05 -07:00
2022-07-24 19:55:10 -07:00
return (
2022-12-18 04:30:49 -08:00
<>
2022-07-24 19:55:10 -07:00
<EnterBottomExitBottom
2022-10-28 03:01:49 -07:00
className="absolute bottom-0 left-0 z-20 h-full w-full overflow-auto rounded-lg bg-th-bkg-1 p-6"
2022-07-24 19:55:10 -07:00
show={showTokenList}
>
2023-03-26 20:11:10 -07:00
<BackButton onClick={() => setShowTokenList(false)} />
2022-12-18 04:30:49 -08:00
<h2 className="mb-4 text-center text-lg">{t('select-borrow-token')}</h2>
<div className="flex items-center px-4 pb-2">
<div className="w-1/4">
<p className="text-xs">{t('token')}</p>
</div>
<div className="w-1/4 text-right">
<p className="text-xs">{t('borrow-rate')}</p>
</div>
<div className="w-1/2 text-right">
<p className="whitespace-nowrap text-xs">{t('max-borrow')}</p>
</div>
</div>
<ActionTokenList
banks={banks}
onSelect={handleSelectToken}
showBorrowRates
2023-01-29 20:13:38 -08:00
valueKey="maxBorrow"
/>
2022-07-24 19:55:10 -07:00
</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 borrow against."
/>
</div>
) : null}
2023-01-09 15:47:18 -08:00
{bank ? <TokenVaultWarnings bank={bank} type="borrow" /> : null}
<div className="grid grid-cols-2">
<div className="col-span-2 flex justify-between">
<Label text={`${t('borrow')} ${t('token')}`} />
2023-01-05 20:10:25 -08:00
{bank ? (
<MaxAmountButton
className="mb-2"
2023-01-23 19:04:05 -08:00
decimals={bank.mintDecimals}
2023-01-05 20:10:25 -08:00
label={t('max')}
onClick={setMax}
2023-01-23 19:04:05 -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}
decimalScale={bank?.mintDecimals || 6}
2023-04-05 20:24:29 -07:00
className={ACCOUNT_ACTIONS_NUMBER_FORMAT_CLASSES}
placeholder="0.00"
value={inputAmount}
2022-12-27 14:24:58 -08:00
onValueChange={handleInputChange}
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 className="col-span-2 mt-4">
<div className="mb-2 flex items-center justify-between">
<p className="text-th-fgd-3">{t('leverage')}</p>
<p className="text-th-fgd-3">0.00x</p>
</div>
2022-08-15 15:18:23 -07:00
<BorrowLeverageSlider
2022-10-07 15:27:36 -07:00
amount={Number(inputAmount) || 0}
2022-08-15 15:18:23 -07:00
tokenMax={tokenMax}
onChange={(x) => setInputAmount(x)}
/>
</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)}
/>
2023-01-08 15:08:23 -08:00
<div className="flex justify-between">
<p>{t('withdraw-amount')}</p>
2023-01-09 15:58:09 -08:00
{isBorrow ? (
2023-01-28 17:13:36 -08:00
<BankAmountWithValue amount={tokenBalance} bank={bank} />
) : (
<BankAmountWithValue
2023-01-23 18:09:14 -08:00
amount={inputAmount}
2023-01-28 17:13:36 -08:00
bank={bank}
fixDecimals={!!inputAmount}
2023-01-09 15:58:09 -08:00
/>
)}
2023-01-08 15:08:23 -08:00
</div>
<div className="flex justify-between">
<p>{t('borrow-amount')}</p>
2023-01-28 17:13:36 -08:00
<BankAmountWithValue
amount={
isBorrow
? Number(inputAmount) - tokenBalance.toNumber()
: 0
}
bank={bank}
fixDecimals={isBorrow}
/>
</div>
<div className="flex justify-between">
2023-03-17 05:48:38 -07:00
<Tooltip
content={t('loan-origination-fee-tooltip', {
fee: `${(
bank.loanOriginationFeeRate.toNumber() * 100
).toFixed(3)}%`,
})}
>
<p className="tooltip-underline">
{t('loan-origination-fee')}
</p>
</Tooltip>
<p className="font-mono text-th-fgd-2">
2023-01-06 00:49:15 -08:00
{isBorrow ? (
<>
2023-01-24 17:12:13 -08:00
<FormatNumericValue
value={
bank.loanOriginationFeeRate.toNumber() *
(parseFloat(inputAmount) - tokenBalance.toNumber())
}
decimals={bank.mintDecimals}
/>{' '}
<span className="font-body text-th-fgd-4">
2023-01-06 00:49:15 -08:00
{bank.name}
</span>
</>
) : (
'N/A'
)}
</p>
</div>
2022-11-16 19:18:22 -08:00
</div>
) : null}
</div>
2023-08-15 05:29:10 -07:00
{connected ? (
<Button
onClick={handleBorrow}
className="flex w-full items-center justify-center"
disabled={connected && (!inputAmount || showInsufficientBalance)}
size="large"
>
{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-collateral')}
</div>
) : isBorrow || !inputAmount ? (
<div className="flex items-center">
<ArrowUpLeftIcon className="mr-2 h-5 w-5" />
{tokenBalance.toNumber()
? `${t('withdraw')} & ${t('borrow')}`
: t('borrow')}
</div>
) : (
<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
/>
)}
2022-12-18 04:30:49 -08:00
</div>
2022-07-24 19:55:10 -07:00
</FadeInFadeOut>
2022-12-18 04:30:49 -08:00
</>
2022-07-24 19:55:10 -07:00
)
}
2022-12-18 04:30:49 -08:00
export default BorrowForm
2023-03-26 20:11:10 -07:00
export const BackButton = ({ onClick }: { onClick: (x: boolean) => void }) => {
return (
<button
onClick={() => onClick(false)}
className="absolute left-4 top-4 z-40 w-6 text-th-fgd-4 focus:outline-none focus-visible:text-th-active md:right-2 md:top-2 md:hover:text-th-active"
2023-03-26 20:11:10 -07:00
>
<ArrowLeftIcon className={`h-6 w-6`} />
</button>
)
}