mango-v4-ui/components/modals/DepositModal.tsx

333 lines
11 KiB
TypeScript
Raw Normal View History

2022-08-24 16:25:59 -07:00
import { toUiDecimalsForQuote } from '@blockworks-foundation/mango-v4'
2022-08-25 17:27:05 -07:00
import { ChevronDownIcon, ExclamationCircleIcon } from '@heroicons/react/solid'
2022-08-02 11:04:00 -07:00
import { Wallet } from '@project-serum/anchor'
import { useWallet } from '@solana/wallet-adapter-react'
2022-07-22 23:15:51 -07:00
import { useTranslation } from 'next-i18next'
import Image from 'next/image'
2022-08-02 11:04:00 -07:00
import React, { ChangeEvent, useCallback, useMemo, useState } from 'react'
2022-08-20 11:17:57 -07:00
import mangoStore from '../../store/mangoStore'
2022-07-20 21:50:56 -07:00
import { ModalProps } from '../../types/modal'
2022-08-24 16:25:59 -07:00
import { ALPHA_DEPOSIT_LIMIT, INPUT_TOKEN_DEFAULT } from '../../utils/constants'
2022-07-14 22:20:20 -07:00
import { notify } from '../../utils/notifications'
2022-08-24 17:53:31 -07:00
import { floorToDecimal, formatFixedDecimals } from '../../utils/numbers'
2022-08-02 11:04:00 -07:00
import { TokenAccount } from '../../utils/tokens'
import ActionTokenList from '../account/ActionTokenList'
import ButtonGroup from '../forms/ButtonGroup'
2022-07-22 23:15:51 -07:00
import Input from '../forms/Input'
import Label from '../forms/Label'
import Button, { LinkButton } from '../shared/Button'
2022-08-17 16:54:56 -07:00
import HealthImpact from '../shared/HealthImpact'
2022-08-24 17:53:31 -07:00
import InfoTooltip from '../shared/InfoTooltip'
import InlineNotification from '../shared/InlineNotification'
2022-07-14 22:20:20 -07:00
import Loading from '../shared/Loading'
import Modal from '../shared/Modal'
2022-07-23 04:20:08 -07:00
import { EnterBottomExitBottom, FadeInFadeOut } from '../shared/Transitions'
2022-05-03 21:20:14 -07:00
2022-07-24 19:55:10 -07:00
interface DepositModalProps {
token?: string
}
type ModalCombinedProps = DepositModalProps & ModalProps
2022-08-11 22:48:00 -07:00
export const walletBalanceForToken = (
2022-08-02 11:04:00 -07:00
walletTokens: TokenAccount[],
token: string
2022-08-03 14:46:37 -07:00
): { maxAmount: number; maxDecimals: number } => {
2022-08-02 11:04:00 -07:00
const group = mangoStore.getState().group
const bank = group?.banksMapByName.get(token)![0]
2022-08-02 11:04:00 -07:00
2022-08-03 14:46:37 -07:00
let walletToken
if (bank) {
const tokenMint = bank?.mint
walletToken = tokenMint
? walletTokens.find((t) => t.mint.toString() === tokenMint.toString())
: null
}
2022-08-02 11:04:00 -07:00
2022-08-03 14:46:37 -07:00
return {
maxAmount: walletToken ? walletToken.uiAmount : 0,
maxDecimals: bank?.mintDecimals || 6,
}
2022-08-02 11:04:00 -07:00
}
2022-07-24 19:55:10 -07:00
function DepositModal({ isOpen, onClose, token }: ModalCombinedProps) {
2022-07-22 23:15:51 -07:00
const { t } = useTranslation('common')
const group = mangoStore((s) => s.group)
2022-05-03 21:20:14 -07:00
const [inputAmount, setInputAmount] = useState('')
const [submitting, setSubmitting] = useState(false)
2022-08-19 23:25:50 -07:00
const [selectedToken, setSelectedToken] = useState(
token || INPUT_TOKEN_DEFAULT
)
2022-07-22 23:15:51 -07:00
const [showTokenList, setShowTokenList] = useState(false)
const [sizePercentage, setSizePercentage] = useState('')
const jupiterTokens = mangoStore((s) => s.jupiterTokens)
const bank = useMemo(() => {
const group = mangoStore.getState().group
return group?.banksMapByName.get(selectedToken)![0]
}, [selectedToken])
const logoUri = useMemo(() => {
let logoURI
if (jupiterTokens.length) {
logoURI = jupiterTokens.find(
(t) => t.address === bank?.mint.toString()
)!.logoURI
}
return logoURI
}, [bank?.mint, jupiterTokens])
2022-08-02 11:04:00 -07:00
const { wallet } = useWallet()
const walletTokens = mangoStore((s) => s.wallet.tokens)
2022-08-02 11:04:00 -07:00
const tokenMax = useMemo(() => {
return walletBalanceForToken(walletTokens, selectedToken)
}, [walletTokens, selectedToken])
const setMax = useCallback(() => {
2022-08-03 14:46:37 -07:00
setInputAmount(tokenMax.maxAmount.toString())
setSizePercentage('100')
2022-08-02 11:04:00 -07:00
}, [tokenMax])
const handleSizePercentage = useCallback(
(percentage: string) => {
setSizePercentage(percentage)
2022-08-03 14:46:37 -07:00
let amount = (Number(percentage) / 100) * tokenMax.maxAmount
if (percentage !== '100') {
amount = floorToDecimal(amount, tokenMax.maxDecimals)
}
2022-08-02 11:04:00 -07:00
setInputAmount(amount.toString())
},
[tokenMax]
)
2022-07-22 23:15:51 -07:00
const handleSelectToken = (token: string) => {
setSelectedToken(token)
setShowTokenList(false)
}
2022-05-03 21:20:14 -07:00
const handleDeposit = async () => {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const actions = mangoStore.getState().actions
2022-07-27 23:35:18 -07:00
const mangoAccount = mangoStore.getState().mangoAccount.current
2022-05-03 21:20:14 -07:00
if (!mangoAccount || !group) return
try {
setSubmitting(true)
2022-06-10 11:10:03 -07:00
const tx = await client.tokenDeposit(
group,
mangoAccount,
bank!.mint,
parseFloat(inputAmount)
)
2022-07-05 20:37:49 -07:00
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx,
})
await actions.reloadAccount()
2022-08-02 11:04:00 -07:00
actions.fetchWalletTokens(wallet!.adapter as unknown as Wallet)
setSubmitting(false)
2022-07-05 20:37:49 -07:00
} catch (e: any) {
notify({
title: 'Transaction failed',
description: e.message,
2022-08-10 13:42:15 -07:00
txid: e?.signature,
2022-07-05 20:37:49 -07:00
type: 'error',
})
2022-08-02 11:04:00 -07:00
console.error('Error depositing:', e)
}
2022-05-03 21:20:14 -07:00
onClose()
}
// TODO extract into a shared hook for UserSetupModal.tsx
const banks = useMemo(() => {
const banks = group?.banksMapByName
? Array.from(group?.banksMapByName, ([key, value]) => {
const walletBalance = walletBalanceForToken(walletTokens, key)
return {
key,
value,
walletBalance: floorToDecimal(
walletBalance.maxAmount,
walletBalance.maxDecimals
),
walletBalanceValue: walletBalance.maxAmount * value[0]?.uiPrice,
}
})
: []
return banks.filter((b) => b.walletBalance > 0)
}, [group?.banksMapByName, walletTokens])
2022-08-24 16:25:59 -07:00
const exceedsAlphaMax = useMemo(() => {
const mangoAccount = mangoStore.getState().mangoAccount.current
if (!mangoAccount) return
const accountValue = toUiDecimalsForQuote(
mangoAccount.getEquity().toNumber()
)
return (
parseFloat(inputAmount) > ALPHA_DEPOSIT_LIMIT ||
accountValue > ALPHA_DEPOSIT_LIMIT
)
}, [inputAmount])
2022-08-25 17:27:05 -07:00
const showInsufficientBalance = tokenMax.maxAmount < Number(inputAmount)
2022-05-03 21:20:14 -07:00
return (
<Modal isOpen={isOpen} onClose={onClose}>
2022-08-24 17:53:31 -07:00
<EnterBottomExitBottom
className="absolute bottom-0 left-0 z-20 h-full w-full overflow-auto bg-th-bkg-1 p-6"
show={showTokenList}
>
<h2 className="mb-4 text-center">{t('select-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('deposit-rate')}</p>
</div>
<div className="text-right">
<p className="whitespace-nowrap text-xs">{t('wallet-balance')}</p>
</div>
</div>
<ActionTokenList
banks={banks}
onSelect={handleSelectToken}
showDepositRates
sortByKey="walletBalanceValue"
valueKey="walletBalance"
/>
</EnterBottomExitBottom>
<FadeInFadeOut
className="flex h-full flex-col justify-between"
show={isOpen}
>
<div>
<h2 className="mb-2 text-center">{t('deposit')}</h2>
<InlineNotification
type="info"
2022-08-24 19:59:38 -07:00
desc={`There is a $${ALPHA_DEPOSIT_LIMIT} deposit limit during alpha
testing.`}
/>
<div className="mt-4 grid grid-cols-2 pb-6">
2022-08-24 17:53:31 -07:00
<div className="col-span-2 flex justify-between">
<Label text={t('token')} />
<LinkButton className="mb-2 no-underline" onClick={setMax}>
<span className="mr-1 text-sm font-normal text-th-fgd-4">
{t('wallet-balance')}:
</span>
<span className="text-th-fgd-1 underline">
{floorToDecimal(tokenMax.maxAmount, tokenMax.maxDecimals)}
</span>
</LinkButton>
</div>
2022-08-24 17:53:31 -07:00
<div className="col-span-1 rounded-lg rounded-r-none border border-r-0 border-th-bkg-4 bg-th-bkg-1">
<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`}
/>
</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>
2022-08-24 17:53:31 -07:00
<div className="col-span-1">
<Input
type="text"
name="deposit"
id="deposit"
className="w-full rounded-lg rounded-l-none border border-th-bkg-4 bg-th-bkg-1 p-3 text-right text-xl font-bold tracking-wider text-th-fgd-1 focus:outline-none"
placeholder="0.00"
value={inputAmount}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setInputAmount(e.target.value)
}
/>
</div>
2022-08-24 17:53:31 -07:00
<div className="col-span-2 mt-2">
<ButtonGroup
activeValue={sizePercentage}
onChange={(p) => handleSizePercentage(p)}
values={['10', '25', '50', '75', '100']}
unit="%"
/>
</div>
2022-08-24 17:53:31 -07:00
</div>
<div className="space-y-2 border-y border-th-bkg-3 px-2 py-4">
2022-08-17 16:54:56 -07:00
<HealthImpact
mintPk={bank!.mint}
uiAmount={parseFloat(inputAmount)}
2022-08-17 16:54:56 -07:00
isDeposit
/>
2022-07-23 19:48:26 -07:00
<div className="flex justify-between">
<p>{t('deposit-value')}</p>
2022-08-24 17:53:31 -07:00
<p className="text-th-fgd-1">
{formatFixedDecimals(bank!.uiPrice * Number(inputAmount), true)}
</p>
2022-07-23 19:48:26 -07:00
</div>
<div className="flex justify-between">
<div className="flex items-center">
2022-08-24 17:53:31 -07:00
<p>{t('asset-weight')}</p>
<InfoTooltip content={t('asset-weight-desc')} />
2022-07-23 19:48:26 -07:00
</div>
2022-08-24 17:53:31 -07:00
<p className="text-th-fgd-1">
{bank!.initAssetWeight.toFixed(2)}x
</p>
2022-07-22 23:15:51 -07:00
</div>
<div className="flex justify-between">
<p>{t('collateral-value')}</p>
2022-08-24 17:53:31 -07:00
<p className="text-th-fgd-1">
{formatFixedDecimals(
bank!.uiPrice *
Number(inputAmount) *
Number(bank!.initAssetWeight),
true
)}
</p>
2022-07-22 23:15:51 -07:00
</div>
2022-08-11 22:48:00 -07:00
</div>
<Button
onClick={handleDeposit}
className="mt-6 flex w-full items-center justify-center"
disabled={
2022-08-25 17:27:05 -07:00
!inputAmount || exceedsAlphaMax || showInsufficientBalance
}
size="large"
>
2022-08-25 17:27:05 -07:00
{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('trade:insufficient-balance', {
symbol: selectedToken,
})}
2022-08-25 17:27:05 -07:00
</div>
) : (
t('deposit')
)}
</Button>
</div>
</FadeInFadeOut>
2022-05-03 21:20:14 -07:00
</Modal>
)
}
export default DepositModal