import React, { FunctionComponent, useEffect, useState } from 'react' import { Disclosure } from '@headlessui/react' import { ExclamationCircleIcon, InformationCircleIcon, } from '@heroicons/react/outline' import { ChevronLeftIcon, ChevronDownIcon, ChevronUpIcon, } from '@heroicons/react/solid' import Modal from './Modal' import Input from './Input' import AccountSelect from './AccountSelect' import { ElementTitle } from './styles' import useMangoStore from '../stores/useMangoStore' import Loading from './Loading' import Button, { LinkButton } from './Button' import Tooltip from './Tooltip' import Slider from './Slider' import InlineNotification from './InlineNotification' import { deposit } from '../utils/mango' import { notify } from '../utils/notifications' interface DepositModalProps { onClose: () => void isOpen: boolean settleDeficit?: string tokenSymbol?: string } const DepositModal: FunctionComponent = ({ isOpen, onClose, settleDeficit, tokenSymbol = '', }) => { // const groupConfig = useMangoGroupConfig() // const tokenSymbols = useMemo(() => groupConfig.tokens.map(t => t.symbol), [groupConfig]); const [inputAmount, setInputAmount] = useState(settleDeficit || '') const [submitting, setSubmitting] = useState(false) const [simulation /*setSimulation*/] = useState(null) const [showSimulation, setShowSimulation] = useState(false) const [invalidAmountMessage, setInvalidAmountMessage] = useState('') const [sliderPercentage, setSliderPercentage] = useState(0) const [maxButtonTransition, setMaxButtonTransition] = useState(false) const walletTokens = useMangoStore((s) => s.wallet.tokens) const actions = useMangoStore((s) => s.actions) const [selectedAccount, setSelectedAccount] = useState(walletTokens[0]) // const prices = [] //useMangoStore((s) => s.selectedMangoGroup.prices) // const selectedMangoGroup = useMangoStore((s) => s.selectedMangoGroup.current) useEffect(() => { if (tokenSymbol) { const symbolAccount = walletTokens.find( (a) => a.config.symbol === tokenSymbol ) if (symbolAccount) { setSelectedAccount(symbolAccount) } else { setSelectedAccount(null) } } }, [tokenSymbol, walletTokens]) /* TODO: simulation useEffect(() => { if (!selectedMangoGroup || !selectedMangoAccount || !selectedAccount) return const mintDecimals = selectedMangoGroup.mintDecimals[tokenIndex] const groupIndex = selectedMangoGroup.indexes[tokenIndex] const deposits = selectedMangoAccount.getUiDeposit( selectedMangoGroup, tokenIndex ) // simulate change to deposits based on input amount const newDeposit = Math.max(0, +inputAmount + +deposits) // clone MangoAccount and arrays to not modify selectedMangoAccount const simulation = new MangoAccount(null, selectedMangoAccount) simulation.deposits = [...selectedMangoAccount.deposits] simulation.borrows = [...selectedMangoAccount.borrows] // update with simulated values simulation.deposits[tokenIndex] = uiToNative(newDeposit, mintDecimals).toNumber() / groupIndex.deposit const equity = simulation.computeValue(selectedMangoGroup, prices) const assetsVal = simulation.getAssetsVal(selectedMangoGroup, prices) const liabsVal = simulation.getLiabsVal(selectedMangoGroup, prices) const collateralRatio = simulation.getCollateralRatio( selectedMangoGroup, prices ) const leverage = 1 / Math.max(0, collateralRatio - 1) setSimulation({ equity, assetsVal, liabsVal, collateralRatio, leverage, }) }, [ inputAmount, prices, tokenIndex, selectedMangoAccount, selectedMangoGroup, ]) */ const handleAccountSelect = (account) => { setInputAmount('') setSliderPercentage(0) setInvalidAmountMessage('') setSelectedAccount(account) } const setMaxForSelectedAccount = () => { setInputAmount(selectedAccount.uiBalance.toString()) setSliderPercentage(100) setInvalidAmountMessage('') setMaxButtonTransition(true) } const handleDeposit = () => { const mangoAccount = useMangoStore.getState().selectedMangoAccount.current setSubmitting(true) deposit({ amount: parseFloat(inputAmount), fromTokenAcc: selectedAccount.account, mangoAccount, }) .then((response) => { notify({ title: 'Deposit successful', type: 'success', txid: response[1], }) console.log('deposit response', response) setSubmitting(false) onClose() actions.fetchMangoAccounts() }) .catch((err) => { notify({ title: 'Deposit failed', description: err.message, type: 'error', }) }) } const renderAccountRiskStatus = ( collateralRatio: number, isRiskLevel?: boolean, isStatusIcon?: boolean ) => { if (collateralRatio < 1.25) { return isRiskLevel ? (
High
) : isStatusIcon ? ( 'bg-th-red' ) : ( 'border-th-red text-th-red' ) } else if (collateralRatio > 1.25 && collateralRatio < 1.5) { return isRiskLevel ? (
Moderate
) : isStatusIcon ? ( 'bg-th-orange' ) : ( 'border-th-orange text-th-orange' ) } else { return isRiskLevel ? (
Low
) : isStatusIcon ? ( 'bg-th-green' ) : ( 'border-th-green text-th-green' ) } } const validateAmountInput = (amount) => { if (Number(amount) <= 0) { setInvalidAmountMessage('Enter an amount to deposit') } if (selectedAccount && Number(amount) > selectedAccount.uiBalance) { setInvalidAmountMessage( 'Insufficient balance. Reduce the amount to deposit' ) } } const onChangeAmountInput = (amount) => { setInputAmount(amount) if (!selectedAccount) { setInvalidAmountMessage( 'Please fund wallet with one of the supported assets.' ) return } const max = selectedAccount.uiBalance setSliderPercentage((amount / max) * 100) setInvalidAmountMessage('') } const onChangeSlider = async (percentage) => { setSliderPercentage(percentage) if (!selectedAccount) { setInvalidAmountMessage( 'Please fund wallet with one of the supported assets.' ) return } const max = selectedAccount.uiBalance const amount = (percentage / 100) * max if (percentage === 100) { setInputAmount(amount.toString()) } else { setInputAmount(amount.toString()) } setInvalidAmountMessage('') validateAmountInput(amount) } // turn off slider transition for dragging slider handle interaction useEffect(() => { if (maxButtonTransition) { setMaxButtonTransition(false) } }, [maxButtonTransition]) return ( {!showSimulation ? ( <> Deposit Funds {tokenSymbol && !selectedAccount ? ( ) : null} {settleDeficit ? ( ) : null}
Amount
Max
validateAmountInput(e.target.value)} value={inputAmount} onChange={(e) => onChangeAmountInput(e.target.value)} suffix={selectedAccount?.config.symbol} /> {/* {simulation ? ( {simulation?.leverage < 5 ? simulation?.leverage.toFixed(2) : '>5'} x ) : null} */}
{invalidAmountMessage ? (
{invalidAmountMessage}
) : null}
onChangeSlider(v)} step={1} maxButtonTransition={maxButtonTransition} />
) : ( <> Confirm Deposit
{`You're about to deposit`}
{inputAmount} {selectedAccount?.config.symbol}
{simulation ? ( {({ open }) => ( <>
Account Health Check
{open ? ( ) : ( )}
Account Value
${simulation?.assetsVal.toFixed(2)}
Account Risk
{renderAccountRiskStatus( simulation?.collateralRatio, true )}
Leverage
{simulation?.leverage.toFixed(2)}x
Collateral Ratio
{simulation?.collateralRatio * 100 < 200 ? Math.floor(simulation?.collateralRatio * 100) : '>200'} %
{simulation?.liabsVal > 0.05 ? (
Borrow Value
${simulation?.liabsVal.toFixed(2)}
) : null}
)}
) : null}
setShowSimulation(false)} > Back )}
) } export default React.memo(DepositModal)