mango-v4-ui/components/BorrowForm.tsx

346 lines
12 KiB
TypeScript
Raw Normal View History

2022-11-27 04:36:12 -08:00
import { Bank, 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-09-06 21:36:35 -07:00
ChevronDownIcon,
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-28 14:46:38 -07:00
import Image from 'next/legacy/image'
2022-10-05 04:01:03 -07:00
import React, { useCallback, useMemo, useState } from 'react'
import NumberFormat, { NumberFormatValues } 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 { floorToDecimal, formatFixedDecimals } from './../utils/numbers'
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/SwapForm'
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-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-11-27 04:36:12 -08:00
import TokenVaultWarnings from '@components/shared/TokenVaultWarnings'
2022-12-18 04:30:49 -08:00
interface BorrowFormProps {
onSuccess: () => void
2022-07-24 19:55:10 -07:00
token?: string
}
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(
token || INPUT_TOKEN_DEFAULT
)
2022-07-24 19:55:10 -07:00
const [showTokenList, setShowTokenList] = useState(false)
const [sizePercentage, setSizePercentage] = useState('')
2022-11-18 11:11:06 -08:00
const { mangoTokens } = useJupiterMints()
2022-11-18 09:09:39 -08:00
const { mangoAccount } = useMangoAccount()
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 logoUri = useMemo(() => {
let logoURI
2022-11-18 11:11:06 -08:00
if (mangoTokens?.length) {
logoURI = mangoTokens.find(
(t) => t.address === bank?.mint.toString()
2022-12-19 16:08:46 -08:00
)?.logoURI
}
return logoURI
2022-11-18 11:11:06 -08:00
}, [mangoTokens, bank])
2022-08-15 15:18:23 -07:00
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)
2022-11-27 04:36:12 -08:00
? floorToDecimal(amount, bank.mintDecimals)
2022-11-21 21:00:26 -08:00
: new Decimal(0)
}, [mangoAccount, bank])
2022-08-15 15:18:23 -07:00
const setMax = useCallback(() => {
setInputAmount(tokenMax.toFixed())
2022-08-15 15:18:23 -07:00
}, [tokenMax])
const handleSizePercentage = useCallback(
(percentage: string) => {
if (!bank) return
2022-08-15 15:18:23 -07:00
setSizePercentage(percentage)
const amount = (Number(percentage) / 100) * (tokenMax.toNumber() || 0)
setInputAmount(floorToDecimal(amount, bank.mintDecimals).toFixed())
2022-08-15 15:18:23 -07:00
},
[tokenMax, bank]
2022-08-15 15:18:23 -07:00
)
2022-07-24 19:55:10 -07:00
const handleSelectToken = (token: string) => {
setSelectedToken(token)
setShowTokenList(false)
}
2022-08-15 15:18:23 -07:00
const handleWithdraw = async () => {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const mangoAccount = mangoStore.getState().mangoAccount.current
const actions = mangoStore.getState().actions
if (!mangoAccount || !group) return
setSubmitting(true)
try {
const tx = await client.tokenWithdraw(
group,
mangoAccount,
bank!.mint,
2022-10-07 15:27:36 -07:00
Number(inputAmount),
2022-08-15 15:18:23 -07:00
true
)
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx,
})
2022-12-18 04:30:49 -08:00
await actions.reloadMangoAccount()
setSubmitting(false)
onSuccess()
2022-08-15 15:18:23 -07:00
} catch (e: any) {
console.error(e)
2022-08-15 15:18:23 -07:00
notify({
title: 'Transaction failed',
description: e.message,
txid: e?.txid,
type: 'error',
})
setSubmitting(false)
}
}
const banks = useMemo(() => {
if (mangoAccount) {
return group?.banksMapByName
? Array.from(group?.banksMapByName, ([key, value]) => {
2022-11-27 04:36:12 -08:00
const bank: Bank = value[0]
const maxAmount = getMaxWithdrawForBank(
group,
bank,
mangoAccount,
true
)
2022-11-27 04:36:12 -08:00
return {
key,
value,
maxAmount: floorToDecimal(
maxAmount,
bank.mintDecimals
).toNumber(),
}
})
: []
}
return []
}, [mangoAccount, group])
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}
>
2022-12-18 18:08:49 -08:00
<button
onClick={() => setShowTokenList(false)}
className={`absolute left-4 top-4 z-40 w-6 text-th-fgd-4 focus:outline-none md:right-2 md:top-2 md:hover:text-th-active`}
>
<ArrowLeftIcon className={`h-6 w-6`} />
</button>
2022-12-18 04:30:49 -08:00
<h2 className="mb-4 text-center text-lg">{t('select-borrow-token')}</h2>
<div className="grid auto-cols-fr grid-flow-col px-4 pb-2">
<div className="">
<p className="text-xs">{t('token')}</p>
</div>
<div className="text-right">
<p className="text-xs">{t('borrow-rate')}</p>
</div>
<div className="text-right">
<p className="whitespace-nowrap text-xs">{t('max-borrow')}</p>
</div>
</div>
<ActionTokenList
banks={banks}
onSelect={handleSelectToken}
showBorrowRates
sortByKey="maxAmount"
valueKey="maxAmount"
/>
2022-07-24 19:55:10 -07:00
</EnterBottomExitBottom>
2022-12-18 04:30:49 -08:00
<FadeInFadeOut
className={`flex h-[${ACCOUNT_ACTION_MODAL_INNER_HEIGHT}] flex-col justify-between`}
show={!showTokenList}
>
2022-07-24 19:55:10 -07:00
<div>
{initHealth && initHealth <= 0 ? (
2022-08-25 20:46:23 -07:00
<div className="mb-4">
<InlineNotification
type="error"
desc="You have no available collateral to borrow against."
/>
</div>
) : null}
2022-10-07 15:27:36 -07:00
<div className="grid grid-cols-2">
2022-07-24 19:55:10 -07:00
<div className="col-span-2 flex justify-between">
2022-12-18 04:30:49 -08:00
<Label text={`${t('borrow')} ${t('token')}`} />
2022-10-05 16:03:10 -07:00
<MaxAmountButton
className="mb-2"
label={t('max')}
onClick={setMax}
value={tokenMax.toFixed()}
/>
2022-07-24 19:55:10 -07:00
</div>
2022-12-07 18:34:24 -08:00
<div className="col-span-1 rounded-lg rounded-r-none border border-r-0 border-th-input-border bg-th-input-bkg">
2022-07-24 19:55:10 -07:00
<button
onClick={() => setShowTokenList(true)}
className="default-transition flex h-full w-full items-center rounded-lg rounded-r-none py-2 px-3 text-th-fgd-2 hover:cursor-pointer hover:bg-th-bkg-2 hover:text-th-fgd-1"
>
<div className="mr-2.5 flex min-w-[24px] items-center">
<Image
alt=""
width="24"
height="24"
src={logoUri || `/icons/${selectedToken.toLowerCase()}.svg`}
2022-07-24 19:55:10 -07:00
/>
</div>
<div className="flex w-full items-center justify-between">
<div className="text-xl font-bold">{selectedToken}</div>
<ChevronDownIcon className="h-6 w-6" />
</div>
</button>
</div>
<div className="col-span-1">
<NumberFormat
name="amountIn"
id="amountIn"
inputMode="decimal"
thousandSeparator=","
allowNegative={false}
isNumericString={true}
decimalScale={bank?.mintDecimals || 6}
2022-12-07 18:34:24 -08:00
className="w-full rounded-lg rounded-l-none border border-th-input-border bg-th-input-bkg p-3 text-right font-mono text-xl tracking-wider text-th-fgd-1 focus:border-th-input-border-hover focus:outline-none md:hover:border-th-input-border-hover"
2022-07-24 19:55:10 -07:00
placeholder="0.00"
value={inputAmount}
onValueChange={(e: NumberFormatValues) =>
2022-10-31 09:39:43 -07:00
setInputAmount(!Number.isNaN(Number(e.value)) ? e.value : '')
2022-07-24 19:55:10 -07:00
}
isAllowed={withValueLimit}
2022-07-24 19:55:10 -07:00
/>
</div>
<div className="col-span-2 mt-2">
<ButtonGroup
activeValue={sizePercentage}
2022-10-05 16:14:11 -07:00
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> */}
2022-07-24 19:55:10 -07:00
</div>
2022-11-16 19:18:22 -08:00
{bank ? (
<div className="my-6 space-y-2 border-y border-th-bkg-3 px-2 py-4">
<HealthImpactTokenChange
mintPk={bank.mint}
uiAmount={Number(inputAmount)}
/>
<div className="flex justify-between">
<p>{t('borrow-value')}</p>
<p className="font-mono text-th-fgd-1">
{formatFixedDecimals(
bank.uiPrice * Number(inputAmount),
true
)}
</p>
</div>
<div className="flex justify-between">
<Tooltip content={t('loan-origination-fee-tooltip')}>
<p className="tooltip-underline">
{t('loan-origination-fee')}
</p>
</Tooltip>
<p className="font-mono text-th-fgd-1">
{formatFixedDecimals(
bank.loanOriginationFeeRate.toNumber() *
Number(inputAmount),
true
)}
</p>
</div>
2022-10-05 04:01:03 -07:00
</div>
2022-11-16 19:18:22 -08:00
) : null}
2022-07-24 19:55:10 -07:00
</div>
2022-12-18 04:30:49 -08:00
<div className="flex justify-center">
<Button
onClick={handleWithdraw}
className="flex w-full items-center justify-center"
disabled={!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>
) : (
<div className="flex items-center">
2022-12-18 14:57:57 -08:00
<ArrowUpLeftIcon className="mr-2 h-5 w-5" />
2022-12-18 04:30:49 -08:00
{t('borrow')}
</div>
)}
</Button>
</div>
2022-12-19 16:08:46 -08:00
{bank ? (
<div className="pt-4">
<TokenVaultWarnings bank={bank} />
</div>
) : null}
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