mango-ui-v3/components/WithdrawModal.tsx

595 lines
21 KiB
TypeScript
Raw Normal View History

import React, { FunctionComponent, useEffect, useMemo, useState } from 'react'
2021-04-10 14:12:15 -07:00
import Modal from './Modal'
import Input from './Input'
import { ElementTitle } from './styles'
2021-04-10 14:12:15 -07:00
import useMangoStore from '../stores/useMangoStore'
2021-08-15 15:36:06 -07:00
import { DECIMALS, floorToDecimal, tokenPrecision } from '../utils/index'
2021-04-10 14:12:15 -07:00
import Loading from './Loading'
import Slider from './Slider'
import Button, { LinkButton } from './Button'
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 {
ExclamationCircleIcon,
InformationCircleIcon,
} from '@heroicons/react/outline'
import {
ChevronLeftIcon,
ChevronDownIcon,
ChevronUpIcon,
} from '@heroicons/react/solid'
import { Disclosure } from '@headlessui/react'
2021-07-01 07:12:42 -07:00
import Select from './Select'
import { withdraw } from '../utils/mango'
2021-06-23 08:32:33 -07:00
import {
2021-07-01 07:12:42 -07:00
ZERO_I80F48,
I80F48,
MangoAccount,
2021-06-23 08:32:33 -07:00
} from '@blockworks-foundation/mango-client'
2021-07-06 17:13:17 -07:00
import { notify } from '../utils/notifications'
2021-04-10 14:12:15 -07:00
interface WithdrawModalProps {
onClose: () => void
isOpen: boolean
2021-07-05 11:21:57 -07:00
title?: string
tokenSymbol?: string
2021-07-05 11:21:57 -07:00
borrow?: boolean
}
const WithdrawModal: FunctionComponent<WithdrawModalProps> = ({
isOpen,
onClose,
tokenSymbol = '',
2021-07-05 11:21:57 -07:00
borrow = false,
title,
}) => {
const [withdrawTokenSymbol, setWithdrawTokenSymbol] = useState(
tokenSymbol || 'USDC'
)
2021-07-01 07:12:42 -07:00
const [inputAmount, setInputAmount] = useState('')
const [invalidAmountMessage, setInvalidAmountMessage] = useState('')
const [maxAmount, setMaxAmount] = useState(0)
2021-04-10 14:12:15 -07:00
const [submitting, setSubmitting] = useState(false)
2021-07-05 11:21:57 -07:00
const [includeBorrow, setIncludeBorrow] = useState(borrow)
const [simulation, setSimulation] = useState(null)
const [showSimulation, setShowSimulation] = useState(false)
const [sliderPercentage, setSliderPercentage] = useState(0)
const [maxButtonTransition, setMaxButtonTransition] = useState(false)
2021-07-01 07:12:42 -07:00
const actions = useMangoStore((s) => s.actions)
2021-07-27 10:05:05 -07:00
const mangoGroup = useMangoStore((s) => s.selectedMangoGroup.current)
2021-08-15 15:36:06 -07:00
const mangoAccount = useMangoStore((s) => s.selectedMangoAccount.current)
2021-07-01 07:12:42 -07:00
const mangoCache = useMangoStore((s) => s.selectedMangoGroup.cache)
const mangoGroupConfig = useMangoStore((s) => s.selectedMangoGroup.config)
const tokens = useMemo(() => mangoGroupConfig.tokens, [mangoGroupConfig])
const token = useMemo(
() => tokens.find((t) => t.symbol === withdrawTokenSymbol),
[withdrawTokenSymbol, tokens]
)
2021-07-27 10:05:05 -07:00
const tokenIndex = mangoGroup.getTokenIndex(token.mintKey)
2021-07-01 07:12:42 -07:00
useEffect(() => {
2021-08-15 15:36:06 -07:00
if (!mangoGroup || !mangoAccount || !withdrawTokenSymbol) return
2021-04-10 14:12:15 -07:00
2021-07-27 10:05:05 -07:00
const mintDecimals = mangoGroup.tokens[tokenIndex].decimals
2021-08-15 15:36:06 -07:00
const tokenDeposits = mangoAccount.getUiDeposit(
2021-07-01 07:12:42 -07:00
mangoCache.rootBankCache[tokenIndex],
2021-07-27 10:05:05 -07:00
mangoGroup,
tokenIndex
)
2021-08-15 15:36:06 -07:00
const tokenBorrows = mangoAccount.getUiBorrow(
2021-07-01 07:12:42 -07:00
mangoCache.rootBankCache[tokenIndex],
2021-07-27 10:05:05 -07:00
mangoGroup,
tokenIndex
)
2021-04-22 03:31:55 -07:00
2021-08-15 15:36:06 -07:00
// get max withdraw amount
const maxWithdraw = includeBorrow
? mangoAccount.getMaxWithBorrowForToken(
mangoGroup,
mangoCache,
tokenIndex
)
2021-07-01 07:12:42 -07:00
: getDepositsForSelectedAsset()
2021-08-15 15:36:06 -07:00
if (maxWithdraw.gt(I80F48.fromNumber(0))) {
setMaxAmount(
floorToDecimal(parseFloat(maxWithdraw.toFixed()), token.decimals)
)
} else {
setMaxAmount(0)
}
// simulate change to deposits & borrow based on input amount
2021-07-01 07:12:42 -07:00
const parsedInputAmount = inputAmount
? I80F48.fromString(inputAmount)
: ZERO_I80F48
2021-08-15 15:36:06 -07:00
let newDeposit = tokenDeposits.sub(parsedInputAmount)
2021-07-01 07:12:42 -07:00
newDeposit = newDeposit.gt(ZERO_I80F48) ? newDeposit : ZERO_I80F48
2021-08-15 15:36:06 -07:00
let newBorrow = parsedInputAmount.sub(tokenDeposits)
newBorrow = newBorrow.gt(ZERO_I80F48) ? newBorrow : ZERO_I80F48
newBorrow = newBorrow.add(tokenBorrows)
2021-06-23 08:32:33 -07:00
// clone MangoAccount and arrays to not modify selectedMangoAccount
2021-08-15 15:36:06 -07:00
const simulation = new MangoAccount(null, mangoAccount)
simulation.deposits = [...mangoAccount.deposits]
simulation.borrows = [...mangoAccount.borrows]
// update with simulated values
2021-07-01 07:12:42 -07:00
simulation.deposits[tokenIndex] = newDeposit
2021-08-15 15:36:06 -07:00
.mul(I80F48.fromNumber(Math.pow(10, mintDecimals)))
2021-07-01 07:12:42 -07:00
.div(mangoCache.rootBankCache[tokenIndex].depositIndex)
2021-08-15 15:36:06 -07:00
simulation.borrows[tokenIndex] = newBorrow
.mul(I80F48.fromNumber(Math.pow(10, mintDecimals)))
2021-07-01 07:12:42 -07:00
.div(mangoCache.rootBankCache[tokenIndex].borrowIndex)
2021-08-15 15:36:06 -07:00
const liabsVal = simulation
.getLiabsVal(mangoGroup, mangoCache, 'Init')
.toNumber()
const leverage = simulation.getLeverage(mangoGroup, mangoCache).toNumber()
const equity = simulation.computeValue(mangoGroup, mangoCache).toNumber()
const initHealthRatio = simulation
.getHealthRatio(mangoGroup, mangoCache, 'Init')
.toNumber()
setSimulation({
2021-08-15 15:36:06 -07:00
initHealthRatio,
liabsVal,
2021-08-15 15:36:06 -07:00
leverage,
equity,
})
}, [
includeBorrow,
inputAmount,
tokenIndex,
2021-08-15 15:36:06 -07:00
mangoAccount,
2021-07-27 10:05:05 -07:00
mangoGroup,
2021-07-01 07:12:42 -07:00
mangoCache,
])
2021-04-19 09:52:19 -07:00
2021-04-10 14:12:15 -07:00
const handleWithdraw = () => {
setSubmitting(true)
2021-07-01 07:12:42 -07:00
withdraw({
amount: Number(inputAmount),
2021-07-27 10:05:05 -07:00
token: mangoGroup.tokens[tokenIndex].mint,
2021-07-01 07:12:42 -07:00
allowBorrow: includeBorrow,
})
2021-07-06 17:13:17 -07:00
.then((txid: string) => {
2021-07-01 07:12:42 -07:00
setSubmitting(false)
2021-07-06 17:13:17 -07:00
actions.fetchMangoGroup()
2021-07-01 07:12:42 -07:00
actions.fetchMangoAccounts()
2021-07-06 17:13:17 -07:00
actions.fetchWalletTokens()
notify({
title: 'Withdraw successful',
type: 'success',
txid,
})
2021-07-01 07:12:42 -07:00
onClose()
})
.catch((err) => {
setSubmitting(false)
2021-07-06 17:13:17 -07:00
console.error('Error withdrawing:', err)
notify({
title: 'Could not perform withdraw',
2021-07-27 10:05:05 -07:00
description: err.message,
2021-07-06 17:13:17 -07:00
txid: err.txid,
type: 'error',
})
2021-07-01 07:12:42 -07:00
onClose()
})
2021-04-10 14:12:15 -07:00
}
const handleSetSelectedAsset = (symbol) => {
2021-07-01 07:12:42 -07:00
setInputAmount('')
setSliderPercentage(0)
setWithdrawTokenSymbol(symbol)
}
2021-07-01 07:12:42 -07:00
const getDepositsForSelectedAsset = (): I80F48 => {
2021-08-15 15:36:06 -07:00
return mangoAccount.getUiDeposit(
2021-07-01 07:12:42 -07:00
mangoCache.rootBankCache[tokenIndex],
2021-07-27 10:05:05 -07:00
mangoGroup,
tokenIndex
)
}
2021-04-22 03:31:55 -07:00
const getBorrowAmount = () => {
2021-07-01 07:12:42 -07:00
const tokenBalance = getDepositsForSelectedAsset()
const borrowAmount = I80F48.fromString(inputAmount).sub(tokenBalance)
return borrowAmount.gt(ZERO_I80F48) ? borrowAmount : 0
2021-04-22 03:31:55 -07:00
}
const getAccountStatusColor = (
2021-08-15 15:36:06 -07:00
initHealthRatio: number,
isRisk?: boolean,
isStatus?: boolean
) => {
2021-08-15 15:36:06 -07:00
if (initHealthRatio < 1) {
return isRisk ? (
<div className="text-th-red">High</div>
) : isStatus ? (
'bg-th-red'
) : (
'border-th-red text-th-red'
)
2021-08-15 15:36:06 -07:00
} else if (initHealthRatio > 1 && initHealthRatio < 10) {
return isRisk ? (
<div className="text-th-orange">Moderate</div>
) : isStatus ? (
'bg-th-orange'
) : (
'border-th-orange text-th-orange'
)
} else {
return isRisk ? (
<div className="text-th-green">Low</div>
) : isStatus ? (
'bg-th-green'
) : (
'border-th-green text-th-green'
)
}
}
const handleIncludeBorrowSwitch = (checked) => {
setIncludeBorrow(checked)
2021-07-06 21:34:21 -07:00
setInputAmount('')
setSliderPercentage(0)
setInvalidAmountMessage('')
}
2021-08-17 12:52:33 -07:00
const setMaxForSelectedAsset = async () => {
2021-07-01 07:12:42 -07:00
console.log('setting max borrow for selected', maxAmount)
2021-07-05 11:21:57 -07:00
setInputAmount(maxAmount.toString())
setSliderPercentage(100)
setInvalidAmountMessage('')
setMaxButtonTransition(true)
}
2021-07-01 07:12:42 -07:00
const onChangeAmountInput = (amount: string) => {
setInputAmount(amount)
2021-07-06 21:34:21 -07:00
setSliderPercentage((Number(amount) / maxAmount) * 100)
setInvalidAmountMessage('')
}
const onChangeSlider = async (percentage) => {
const amount = (percentage / 100) * maxAmount
if (percentage === 100) {
2021-07-05 11:21:57 -07:00
setInputAmount(maxAmount.toString())
} else {
2021-08-15 15:36:06 -07:00
setInputAmount(floorToDecimal(amount, token.decimals).toString())
}
setSliderPercentage(percentage)
setInvalidAmountMessage('')
validateAmountInput(amount)
}
const validateAmountInput = (amount) => {
2021-07-06 21:34:21 -07:00
const parsedAmount = Number(amount)
if (
2021-07-05 11:21:57 -07:00
(getDepositsForSelectedAsset() === ZERO_I80F48 ||
2021-07-06 21:34:21 -07:00
getDepositsForSelectedAsset().lt(I80F48.fromNumber(parsedAmount))) &&
!includeBorrow
) {
setInvalidAmountMessage('Insufficient balance. Borrow funds to withdraw')
}
}
useEffect(() => {
2021-08-15 15:36:06 -07:00
if (simulation && simulation.initHealthRatio < 0 && includeBorrow) {
setInvalidAmountMessage(
'Leverage too high. Reduce the amount to withdraw'
)
}
}, [simulation])
2021-07-01 07:12:42 -07:00
const getTokenBalances = () => {
const mangoCache = useMangoStore.getState().selectedMangoGroup.cache
const mangoGroup = useMangoStore.getState().selectedMangoGroup.current
return tokens.map((token) => {
const tokenIndex = mangoGroup.getTokenIndex(token.mintKey)
return {
2021-07-01 07:12:42 -07:00
symbol: token.symbol,
2021-08-15 15:36:06 -07:00
balance: mangoAccount
2021-07-01 07:12:42 -07:00
.getUiDeposit(
mangoCache.rootBankCache[tokenIndex],
mangoGroup,
tokenIndex
)
.toFixed(tokenPrecision[token.symbol]),
}
})
2021-07-01 07:12:42 -07:00
}
// turn off slider transition for dragging slider handle interaction
useEffect(() => {
if (maxButtonTransition) {
setMaxButtonTransition(false)
}
}, [maxButtonTransition])
if (!withdrawTokenSymbol) return null
2021-04-13 16:41:04 -07:00
2021-04-10 14:12:15 -07:00
return (
2021-08-16 10:59:44 -07:00
<Modal isOpen={isOpen} onClose={onClose}>
<>
{!showSimulation ? (
<>
<Modal.Header>
2021-07-05 11:21:57 -07:00
<ElementTitle noMarignBottom>
{title ? title : 'Withdraw Funds'}
</ElementTitle>
</Modal.Header>
<div className="pb-2 text-th-fgd-1">Asset</div>
<Select
value={
2021-08-15 15:36:06 -07:00
withdrawTokenSymbol && mangoAccount ? (
<div className="flex items-center justify-between w-full">
<div className="flex items-center">
<img
alt=""
width="20"
height="20"
src={`/assets/icons/${withdrawTokenSymbol.toLowerCase()}.svg`}
className={`mr-2.5`}
/>
{withdrawTokenSymbol}
</div>
2021-08-15 15:36:06 -07:00
{mangoAccount
2021-07-01 07:12:42 -07:00
.getUiDeposit(
mangoCache.rootBankCache[tokenIndex],
2021-07-27 10:05:05 -07:00
mangoGroup,
tokenIndex
2021-07-01 07:12:42 -07:00
)
.toFixed(tokenPrecision[withdrawTokenSymbol])}
</div>
) : (
<span className="text-th-fgd-4">Select an asset</span>
)
}
onChange={(asset) => handleSetSelectedAsset(asset)}
>
{getTokenBalances().map(({ symbol, balance }) => (
<Select.Option key={symbol} value={symbol}>
<div className="flex items-center justify-between">
<div className="flex items-center">
<img
alt=""
width="20"
height="20"
src={`/assets/icons/${symbol.toLowerCase()}.svg`}
className={`mr-2.5`}
/>
<span>{symbol}</span>
</div>
{balance}
</div>
</Select.Option>
))}
</Select>
<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.">
<InformationCircleIcon
className={`h-5 w-5 ml-2 text-th-fgd-3 cursor-help`}
/>
</Tooltip>
</div>
<Switch
checked={includeBorrow}
className="ml-auto"
onChange={(checked) => handleIncludeBorrowSwitch(checked)}
/>
</div>
<div className="flex justify-between pb-2 pt-4">
<div className="text-th-fgd-1">Amount</div>
<div className="flex space-x-4">
<button
className="font-normal text-th-fgd-1 underline cursor-pointer default-transition hover:text-th-primary hover:no-underline focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
2021-07-01 07:12:42 -07:00
disabled={
!includeBorrow &&
getDepositsForSelectedAsset().eq(ZERO_I80F48)
}
2021-08-17 12:52:33 -07:00
onClick={setMaxForSelectedAsset}
>
Max
</button>
</div>
</div>
<div className="flex">
<Input
disabled={!withdrawTokenSymbol}
type="number"
min="0"
className={`border border-th-fgd-4 flex-grow pr-11`}
error={!!invalidAmountMessage}
placeholder="0.00"
value={inputAmount}
onBlur={(e) => validateAmountInput(e.target.value)}
onChange={(e) => onChangeAmountInput(e.target.value)}
suffix={withdrawTokenSymbol}
/>
2021-08-15 15:36:06 -07:00
{simulation ? (
2021-05-31 04:41:48 -07:00
<Tooltip content="Projected Leverage" className="py-1">
<span
className={`${getAccountStatusColor(
2021-08-15 15:36:06 -07:00
simulation.initHealthRatio
)} bg-th-bkg-1 border flex font-semibold h-10 items-center justify-center ml-2 rounded text-th-fgd-1 w-14`}
>
2021-08-15 15:36:06 -07:00
{simulation.leverage.toFixed(2)}x
</span>
</Tooltip>
2021-08-15 15:36:06 -07:00
) : null}
</div>
{invalidAmountMessage ? (
<div className="flex items-center pt-1.5 text-th-red">
<ExclamationCircleIcon className="h-4 w-4 mr-1.5" />
{invalidAmountMessage}
</div>
) : null}
<div className="pt-3 pb-4">
<Slider
disabled={!withdrawTokenSymbol}
value={sliderPercentage}
onChange={(v) => onChangeSlider(v)}
step={1}
maxButtonTransition={maxButtonTransition}
/>
</div>
<div className={`pt-8 flex justify-center`}>
<Button
onClick={() => setShowSimulation(true)}
disabled={
2021-08-15 15:36:06 -07:00
Number(inputAmount) <= 0 || simulation?.initHealthRatio < 0
}
className="w-full"
>
Next
</Button>
</div>
</>
) : null}
{showSimulation && simulation ? (
<>
<Modal.Header>
<ElementTitle noMarignBottom>Confirm Withdraw</ElementTitle>
</Modal.Header>
2021-08-15 15:36:06 -07:00
{simulation.initHealthRatio < 0 ? (
<div className="border border-th-red mb-4 p-2 rounded">
<div className="flex items-center text-th-red">
<ExclamationCircleIcon className="h-4 w-4 mr-1.5 flex-shrink-0" />
Prices have changed and increased your leverage. Reduce the
withdrawal amount.
</div>
</div>
) : null}
<div className="bg-th-bkg-1 p-4 rounded-lg text-th-fgd-1 text-center">
<div className="text-th-fgd-3 pb-1">{`You're about to withdraw`}</div>
<div className="flex items-center justify-center">
<div className="font-semibold relative text-xl">
{inputAmount}
<span className="absolute bottom-0.5 font-normal ml-1.5 text-xs text-th-fgd-4">
{withdrawTokenSymbol}
</span>
</div>
</div>
{getBorrowAmount() > 0 ? (
<div className="pt-2 text-th-fgd-4">{`Includes borrow of ~${getBorrowAmount().toFixed(
DECIMALS[withdrawTokenSymbol]
)} ${withdrawTokenSymbol}`}</div>
) : null}
</div>
<Disclosure>
{({ open }) => (
<>
<Disclosure.Button
className={`border border-th-fgd-4 default-transition font-normal mt-4 pl-3 pr-2 py-2.5 ${
open ? 'rounded-b-none' : 'rounded-md'
} text-th-fgd-1 w-full hover:bg-th-bkg-3 focus:outline-none`}
>
<div className="flex items-center justify-between">
<div className="flex items-center">
<span className="flex h-2 w-2 mr-2.5 relative">
2021-08-15 15:36:06 -07:00
<span
className={`animate-ping absolute inline-flex h-full w-full rounded-full ${getAccountStatusColor(
2021-08-15 15:36:06 -07:00
simulation.initHealthRatio,
false,
true
)} opacity-75`}
2021-08-15 15:36:06 -07:00
></span>
<span
className={`relative inline-flex rounded-full h-2 w-2 ${getAccountStatusColor(
2021-08-15 15:36:06 -07:00
simulation.initHealthRatio,
false,
true
)}`}
2021-08-15 15:36:06 -07:00
></span>
</span>
Account Health Check
<Tooltip content="The details of your account after this withdrawal.">
<InformationCircleIcon
className={`h-5 w-5 ml-2 text-th-fgd-3 cursor-help`}
/>
</Tooltip>
</div>
{open ? (
<ChevronUpIcon className="h-5 w-5 mr-1" />
) : (
<ChevronDownIcon className="h-5 w-5 mr-1" />
)}
</div>
</Disclosure.Button>
<Disclosure.Panel
className={`border border-th-fgd-4 border-t-0 p-4 rounded-b-md`}
>
2021-08-15 15:36:06 -07:00
{simulation ? (
<div>
<div className="flex justify-between pb-2">
<div className="text-th-fgd-4">Account Value</div>
<div className="text-th-fgd-1">
${simulation.equity.toFixed(2)}
</div>
</div>
2021-08-15 15:36:06 -07:00
<div className="flex justify-between pb-2">
<div className="text-th-fgd-4">Account Risk</div>
<div className="text-th-fgd-1">
{getAccountStatusColor(
simulation.initHealthRatio,
true
)}
</div>
</div>
2021-08-15 15:36:06 -07:00
<div className="flex justify-between pb-2">
<div className="text-th-fgd-4">Leverage</div>
<div className="text-th-fgd-1">
{simulation.leverage.toFixed(2)}x
</div>
2021-07-24 13:15:27 -07:00
</div>
2021-08-15 15:36:06 -07:00
<div className="flex justify-between">
<div className="text-th-fgd-4">Borrow Value</div>
<div className="text-th-fgd-1">
${simulation.liabsVal.toFixed(2)}
</div>
</div>
2021-08-15 15:36:06 -07:00
</div>
) : null}
</Disclosure.Panel>
</>
)}
</Disclosure>
<div className={`mt-5 flex justify-center`}>
<Button
onClick={handleWithdraw}
disabled={
2021-08-15 15:36:06 -07:00
Number(inputAmount) <= 0 || simulation.initHealthRatio < 0
}
className="w-full"
>
<div className={`flex items-center justify-center`}>
{submitting && <Loading className="-ml-1 mr-3" />}
2021-08-15 15:36:06 -07:00
Withdraw
</div>
</Button>
</div>
<LinkButton
className="flex items-center mt-4 text-th-fgd-3"
onClick={() => setShowSimulation(false)}
>
<ChevronLeftIcon className="h-5 w-5 mr-1" />
Back
</LinkButton>
</>
) : null}
</>
2021-04-10 14:12:15 -07:00
</Modal>
)
}
export default React.memo(WithdrawModal)