mango-ui-v3/components/WithdrawModal.tsx

267 lines
8.7 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-10 14:12:15 -07:00
const WithdrawModal = ({ isOpen, onClose }) => {
const [inputAmount, setInputAmount] = useState('')
const [submitting, setSubmitting] = 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-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
)
2021-04-20 07:09:25 -07:00
const assetsVal = assetsValBeforeTokenBal - getMaxForSelectedAccount()
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
console.log('selected token deposits', getMaxForSelectedAccount())
console.log('prices', prices)
console.log('assetsVal', assetsVal)
2021-04-19 09:52:19 -07:00
console.log('currentLiabs', currentLiabs)
console.log('liabsAvail', liabsAvail)
2021-04-20 07:09:25 -07:00
const amountToWithdraw =
liabsAvail / prices[tokenIndex] + getMaxForSelectedAccount()
const decimals = mintDecimals[getTokenIndex(mintAddress)]
setInputAmount(formatBalanceDisplay(amountToWithdraw, decimals).toString())
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
if (Number(inputAmount) <= getMaxForSelectedAccount()) {
console.log('=withdraw without borrow=')
2021-04-10 14:12:15 -07:00
withdraw(
connection,
programId,
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 {
console.log('-withdraw with borrow-')
borrowAndWithdraw(
connection,
programId,
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-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">
<div className="text-th-fgd-1 pb-2">Token Account</div>
<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}
/>
<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"
onClick={setMaxForSelectedAccount}
>
Max
</div>
<div
className="text-th-fgd-1 underline cursor-pointer default-transition hover:text-th-primary hover:no-underline"
onClick={setMaxBorrowForSelectedAccount}
>
Max With Borrow
</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>
<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>
{/* <div className={`pb-6 px-8`}>
2021-04-16 14:09:17 -07:00
<div className={`mt-3 sm:mt-5`}>
<div className="text-right text-th-fgd-2">
Balance: {getMaxForSelectedAccount()}
</div>
<div className={`mt-1 bg-th-bkg-3 rounded-md flex items-center`}>
2021-04-10 14:12:15 -07:00
<img
alt=""
width="20"
height="20"
src={`/assets/icons/${getSymbolForTokenMintAddress(
selectedAccount?.account?.mint.toString()
).toLowerCase()}.svg`}
className={`ml-3`}
2021-04-10 14:12:15 -07:00
/>
<input
type="number"
min="0"
2021-04-12 20:39:08 -07:00
className={`outline-none bg-th-bkg-3 w-full py-4 mx-3 text-2xl text-th-fgd-2 flex-grow`}
2021-04-10 14:12:15 -07:00
placeholder="0.00"
value={inputAmount}
onChange={(e) => setInputAmount(e.target.value)}
></input>
<Button
onClick={setMaxForSelectedAccount}
className={`m-2 rounded py-1`}
2021-04-10 14:12:15 -07:00
>
Max
</Button>
</div>
</div>
<div className={`mt-5 sm:mt-6 flex justify-center`}>
2021-04-10 14:12:15 -07:00
<Button onClick={handleWithdraw} disabled={withdrawDisabled}>
<div className={`flex items-center`}>
2021-04-10 14:12:15 -07:00
{submitting && <Loading />}
Withdraw
</div>
</Button>
</div>
</div> */}
2021-04-10 14:12:15 -07:00
</Modal>
)
}
export default React.memo(WithdrawModal)