mango-ui-v3/components/WithdrawModal.tsx

283 lines
9.3 KiB
TypeScript
Raw Normal View History

2021-04-10 14:12:15 -07:00
import React, { useMemo, useState } from 'react'
import Modal from './Modal'
import Input from './Input'
2021-04-10 14:12:15 -07:00
import AccountSelect from './AccountSelect'
import { ElementTitle } from './styles'
2021-04-10 14:12:15 -07:00
import useMangoStore from '../stores/useMangoStore'
import useMarketList from '../hooks/useMarketList'
2021-04-20 07:09:25 -07:00
import {
getSymbolForTokenMintAddress,
formatBalanceDisplay,
} from '../utils/index'
2021-04-10 14:12:15 -07:00
import useConnection from '../hooks/useConnection'
2021-04-20 07:09:25 -07:00
import { borrowAndWithdraw, withdraw } from '../utils/mango'
2021-04-10 14:12:15 -07:00
import Loading from './Loading'
import Button from './Button'
2021-04-12 20:39:08 -07:00
import { notify } from '../utils/notifications'
2021-04-20 17:39:19 -07:00
import Switch from './Switch'
2021-04-22 03:31:55 -07:00
import Tooltip from './Tooltip'
import { InformationCircleIcon } from '@heroicons/react/outline'
import { Transition } from '@headlessui/react'
import { PublicKey } from '@solana/web3.js'
2021-04-10 14:12:15 -07:00
const WithdrawModal = ({ isOpen, onClose }) => {
const [inputAmount, setInputAmount] = useState('')
const [submitting, setSubmitting] = useState(false)
2021-04-20 17:39:19 -07:00
const [includeBorrow, setIncludeBorrow] = useState(false)
2021-04-12 20:39:08 -07:00
const { getTokenIndex, symbols } = useMarketList()
2021-04-10 14:12:15 -07:00
const { connection, programId } = useConnection()
const walletAccounts = useMangoStore((s) => s.wallet.balances)
2021-04-19 09:52:19 -07:00
const selectedMangoGroup = useMangoStore((s) => s.selectedMangoGroup.current)
2021-04-20 07:09:25 -07:00
const mintDecimals = useMangoStore((s) => s.selectedMangoGroup.mintDecimals)
2021-04-19 09:52:19 -07:00
const selectedMarginAccount = useMangoStore(
(s) => s.selectedMarginAccount.current
)
2021-04-10 14:12:15 -07:00
const actions = useMangoStore((s) => s.actions)
const withdrawAccounts = useMemo(
() =>
walletAccounts.filter((acc) =>
2021-04-10 14:12:15 -07:00
Object.values(symbols).includes(acc.account.mint.toString())
),
[symbols, walletAccounts]
)
2021-04-12 20:39:08 -07:00
const [selectedAccount, setSelectedAccount] = useState(withdrawAccounts[0])
const mintAddress = useMemo(() => selectedAccount?.account.mint.toString(), [
2021-04-13 16:41:04 -07:00
selectedAccount,
2021-04-12 20:39:08 -07:00
])
const tokenIndex = useMemo(() => getTokenIndex(mintAddress), [
mintAddress,
getTokenIndex,
])
2021-04-10 14:12:15 -07:00
2021-04-20 07:09:25 -07:00
const handleSetSelectedAccount = (val) => {
setInputAmount('')
setSelectedAccount(val)
}
2021-04-10 14:12:15 -07:00
const withdrawDisabled = Number(inputAmount) <= 0
2021-04-16 14:09:17 -07:00
const getMaxForSelectedAccount = () => {
2021-04-10 14:12:15 -07:00
const marginAccount = useMangoStore.getState().selectedMarginAccount.current
const mangoGroup = useMangoStore.getState().selectedMangoGroup.current
2021-04-16 14:09:17 -07:00
return marginAccount.getUiDeposit(mangoGroup, tokenIndex)
}
2021-04-10 14:12:15 -07:00
2021-04-16 14:09:17 -07:00
const setMaxForSelectedAccount = () => {
setInputAmount(getMaxForSelectedAccount().toString())
2021-04-10 14:12:15 -07:00
}
2021-04-22 03:31:55 -07:00
const handleIncludeBorrowSwitch = (checked) => {
setIncludeBorrow(checked)
setInputAmount('')
}
2021-04-19 09:52:19 -07:00
const setMaxBorrowForSelectedAccount = async () => {
const prices = await selectedMangoGroup.getPrices(connection)
2021-04-20 07:09:25 -07:00
const assetsValBeforeTokenBal = selectedMarginAccount.getAssetsVal(
2021-04-19 09:52:19 -07:00
selectedMangoGroup,
prices
)
const assetsVal =
assetsValBeforeTokenBal - getMaxForSelectedAccount() * prices[tokenIndex]
2021-04-19 09:52:19 -07:00
const currentLiabs = selectedMarginAccount.getLiabsVal(
selectedMangoGroup,
prices
)
2021-04-20 07:09:25 -07:00
const liabsAvail = (assetsVal / 1.2 - currentLiabs) * 0.99 - 0.01
2021-04-19 09:52:19 -07:00
2021-04-20 07:09:25 -07:00
const amountToWithdraw =
liabsAvail / prices[tokenIndex] + getMaxForSelectedAccount()
const decimals = mintDecimals[getTokenIndex(mintAddress)]
if (amountToWithdraw > 0) {
setInputAmount(
formatBalanceDisplay(amountToWithdraw, decimals).toString()
)
} else {
setInputAmount('0')
}
2021-04-19 09:52:19 -07:00
}
2021-04-10 14:12:15 -07:00
const handleWithdraw = () => {
setSubmitting(true)
const marginAccount = useMangoStore.getState().selectedMarginAccount.current
const mangoGroup = useMangoStore.getState().selectedMangoGroup.current
const wallet = useMangoStore.getState().wallet.current
2021-04-20 07:09:25 -07:00
if (!marginAccount || !mangoGroup) return
2021-04-22 10:31:09 -07:00
if (!includeBorrow) {
2021-04-10 14:12:15 -07:00
withdraw(
connection,
new PublicKey(programId),
2021-04-10 14:12:15 -07:00
mangoGroup,
marginAccount,
wallet,
selectedAccount.account.mint,
selectedAccount.publicKey,
Number(inputAmount)
)
.then((_transSig: string) => {
2021-04-10 14:12:15 -07:00
setSubmitting(false)
2021-04-14 15:46:36 -07:00
actions.fetchMangoGroup()
actions.fetchMarginAccounts()
2021-04-20 07:09:25 -07:00
actions.fetchWalletBalances()
2021-04-10 14:12:15 -07:00
onClose()
})
.catch((err) => {
setSubmitting(false)
console.warn('Error withdrawing:', err)
2021-04-12 20:39:08 -07:00
notify({
2021-04-20 07:09:25 -07:00
message: 'Could not perform withdraw',
description: `${err}`,
type: 'error',
})
onClose()
})
} else {
borrowAndWithdraw(
connection,
new PublicKey(programId),
2021-04-20 07:09:25 -07:00
mangoGroup,
marginAccount,
wallet,
selectedAccount.account.mint,
selectedAccount.publicKey,
Number(inputAmount)
)
.then((_transSig: string) => {
setSubmitting(false)
actions.fetchMangoGroup()
actions.fetchMarginAccounts()
actions.fetchWalletBalances()
onClose()
})
.catch((err) => {
setSubmitting(false)
console.warn('Error borrowing and withdrawing:', err)
notify({
message: 'Could not perform borrow and withdraw',
2021-04-14 15:46:36 -07:00
description: `${err}`,
2021-04-12 20:39:08 -07:00
type: 'error',
})
2021-04-10 14:12:15 -07:00
onClose()
})
}
}
2021-04-22 03:31:55 -07:00
const getBorrowAmount = () => {
const tokenBalance = getMaxForSelectedAccount()
const borrowAmount = parseFloat(inputAmount) - tokenBalance
return borrowAmount > 0 ? borrowAmount : 0
}
2021-04-13 16:41:04 -07:00
if (!selectedAccount) return null
2021-04-10 14:12:15 -07:00
return (
<Modal isOpen={isOpen} onClose={onClose}>
<Modal.Header>
<ElementTitle noMarignBottom>Withdraw Funds</ElementTitle>
2021-04-10 14:12:15 -07:00
</Modal.Header>
2021-04-20 07:09:25 -07:00
<div className="pb-6 px-8">
<AccountSelect
2021-04-19 09:15:49 -07:00
hideAddress
accounts={withdrawAccounts}
selectedAccount={selectedAccount}
2021-04-20 07:09:25 -07:00
onSelectAccount={handleSetSelectedAccount}
2021-04-19 09:15:49 -07:00
getBalance={getMaxForSelectedAccount}
/>
2021-04-22 03:31:55 -07:00
<div className="flex items-center jusitfy-between text-th-fgd-1 mt-4 p-2 rounded-md bg-th-bkg-3">
<div className="flex items-center text-fgd-1 pr-4">
<span>Borrow Funds</span>
<Tooltip content="Interest is charged on your borrowed balance and is subject to change.">
2021-04-22 03:31:55 -07:00
<InformationCircleIcon
className={`h-5 w-5 ml-2 text-th-primary cursor-help`}
/>
</Tooltip>
</div>
2021-04-20 17:39:19 -07:00
<Switch
checked={includeBorrow}
className="ml-auto"
2021-04-22 03:31:55 -07:00
onChange={(checked) => handleIncludeBorrowSwitch(checked)}
2021-04-20 17:39:19 -07:00
/>
</div>
<div className="flex justify-between pb-2 pt-4">
2021-04-20 07:09:25 -07:00
<div className="text-th-fgd-1">Amount</div>
<div className="flex space-x-4">
2021-04-19 09:52:19 -07:00
<div
className="text-th-fgd-1 underline cursor-pointer default-transition hover:text-th-primary hover:no-underline"
2021-04-20 17:39:19 -07:00
onClick={
includeBorrow
? setMaxBorrowForSelectedAccount
: setMaxForSelectedAccount
}
2021-04-19 09:52:19 -07:00
>
{includeBorrow ? 'Max with Borrow' : 'Max'}
2021-04-19 09:52:19 -07:00
</div>
</div>
</div>
<div className="flex items-center">
<Input
type="number"
min="0"
className={`border border-th-fgd-4 flex-grow pr-11`}
placeholder="0.00"
value={inputAmount}
onChange={(e) => setInputAmount(e.target.value)}
suffix={getSymbolForTokenMintAddress(
selectedAccount?.account?.mint.toString()
)}
/>
</div>
2021-04-22 03:31:55 -07:00
{includeBorrow ? (
<Transition
appear={true}
className="p-2 bg-th-bkg-1 rounded-md mt-4"
show={includeBorrow}
enter="transition-opacity duration-500"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity duration-500"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
2021-04-22 03:31:55 -07:00
<div className="flex justify-between pb-2">
<div className="text-th-fgd-3">Borrow Amount</div>
<div className="text-th-fgd-1">{`${getBorrowAmount()} ${getSymbolForTokenMintAddress(
2021-04-22 03:31:55 -07:00
selectedAccount?.account?.mint.toString()
)}`}</div>
</div>
<div className="flex justify-between">
<div className="text-th-fgd-3">Current APR</div>
2021-04-22 03:31:55 -07:00
<div className="text-th-fgd-1">
{(selectedMangoGroup.getBorrowRate(tokenIndex) * 100).toFixed(
2
)}
%
</div>
</div>
</Transition>
2021-04-22 03:31:55 -07:00
) : null}
<div className={`mt-5 flex justify-center`}>
<Button
onClick={handleWithdraw}
disabled={withdrawDisabled}
className="w-full"
>
<div className={`flex items-center justify-center`}>
{submitting && <Loading />}
{`Withdraw ${
inputAmount ? inputAmount : ''
} ${getSymbolForTokenMintAddress(
selectedAccount?.account?.mint.toString()
)}
`}
</div>
</Button>
</div>
</div>
2021-04-10 14:12:15 -07:00
</Modal>
)
}
export default React.memo(WithdrawModal)