mango-v4-ui/components/DepositForm.tsx

415 lines
14 KiB
TypeScript
Raw Normal View History

2023-01-02 11:49:50 -08:00
import { Bank, toUiDecimalsForQuote } from '@blockworks-foundation/mango-v4'
2022-09-06 21:36:35 -07:00
import {
2022-09-07 17:47:59 -07:00
ArrowDownTrayIcon,
2022-12-18 18:08:49 -08:00
ArrowLeftIcon,
2022-09-06 21:36:35 -07:00
ChevronDownIcon,
ExclamationCircleIcon,
LinkIcon,
2022-09-06 21:36:35 -07:00
} from '@heroicons/react/20/solid'
2022-08-02 11:04:00 -07:00
import { useWallet } from '@solana/wallet-adapter-react'
import Decimal from 'decimal.js'
2022-07-22 23:15:51 -07:00
import { useTranslation } from 'next-i18next'
2022-10-28 14:46:38 -07:00
import Image from 'next/legacy/image'
2022-11-17 20:43:23 -08:00
import React, { useCallback, useMemo, useState } from 'react'
import NumberFormat, { NumberFormatValues } from 'react-number-format'
2022-09-12 08:53:57 -07:00
import mangoStore from '@store/mangoStore'
2022-12-18 04:30:49 -08:00
import {
ACCOUNT_ACTION_MODAL_INNER_HEIGHT,
ALPHA_DEPOSIT_LIMIT,
INPUT_TOKEN_DEFAULT,
} from './../utils/constants'
import { notify } from './../utils/notifications'
2023-01-06 00:56:34 -08:00
import {
floorToDecimal,
formatDecimal,
formatFixedDecimals,
} from './../utils/numbers'
import { TokenAccount } from './../utils/tokens'
import ActionTokenList from './account/ActionTokenList'
import ButtonGroup from './forms/ButtonGroup'
import Label from './forms/Label'
import Button from './shared/Button'
import InlineNotification from './shared/InlineNotification'
import Loading from './shared/Loading'
import { EnterBottomExitBottom, FadeInFadeOut } from './shared/Transitions'
import { withValueLimit } from './swap/SwapForm'
2022-10-05 16:03:10 -07:00
import MaxAmountButton from '@components/shared/MaxAmountButton'
2022-10-05 16:14:11 -07:00
import Tooltip from '@components/shared/Tooltip'
2022-11-04 11:55:21 -07:00
import HealthImpactTokenChange from '@components/HealthImpactTokenChange'
2022-11-17 20:43:23 -08:00
import SolBalanceWarnings from '@components/shared/SolBalanceWarnings'
2022-11-18 11:11:06 -08:00
import useJupiterMints from 'hooks/useJupiterMints'
2022-11-20 12:32:38 -08:00
import useMangoGroup from 'hooks/useMangoGroup'
2023-01-03 03:06:37 -08:00
import { useEnhancedWallet } from './wallet/EnhancedWalletProvider'
import useSolBalance from 'hooks/useSolBalance'
2023-01-08 19:38:09 -08:00
import AmountWithValue from './shared/AmountWithValue'
2022-05-03 21:20:14 -07:00
interface DepositFormProps {
onSuccess: () => void
2022-07-24 19:55:10 -07:00
token?: string
}
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
2022-12-08 10:23:26 -08:00
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
}
2023-01-02 11:49:50 -08:00
export const useAlphaMax = (inputAmount: string, bank: Bank | undefined) => {
const exceedsAlphaMax = useMemo(() => {
const mangoAccount = mangoStore.getState().mangoAccount.current
const group = mangoStore.getState().group
if (!group || !mangoAccount) return
if (
mangoAccount.owner.toString() ===
'8SSLjXBEVk9nesbhi9UMCA32uijbVBUqWoKPPQPTekzt'
)
return false
const accountValue = toUiDecimalsForQuote(
mangoAccount.getEquity(group).toNumber()
)
return (
parseFloat(inputAmount) * (bank?.uiPrice || 1) + accountValue >
ALPHA_DEPOSIT_LIMIT || accountValue > ALPHA_DEPOSIT_LIMIT
)
}, [inputAmount, bank])
return exceedsAlphaMax
}
function DepositForm({ onSuccess, token }: DepositFormProps) {
2022-07-22 23:15:51 -07:00
const { t } = useTranslation('common')
2022-11-20 12:32:38 -08:00
const { group } = useMangoGroup()
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('')
2022-11-18 11:11:06 -08:00
const { mangoTokens } = useJupiterMints()
2023-01-03 03:06:37 -08:00
const { handleConnect } = useEnhancedWallet()
const { maxSolDeposit } = useSolBalance()
const bank = useMemo(() => {
const group = mangoStore.getState().group
2022-11-19 11:20:36 -08:00
return group?.banksMapByName.get(selectedToken)?.[0]
}, [selectedToken])
2023-01-02 11:49:50 -08:00
const exceedsAlphaMax = useAlphaMax(inputAmount, bank)
const logoUri = useMemo(() => {
let logoURI
2022-11-19 11:20:36 -08:00
if (mangoTokens?.length) {
2022-11-18 11:11:06 -08:00
logoURI = mangoTokens.find(
(t) => t.address === bank?.mint.toString()
2022-11-19 11:20:36 -08:00
)?.logoURI
}
return logoURI
2022-11-18 11:11:06 -08:00
}, [bank?.mint, mangoTokens])
const { connected, publicKey } = useWallet()
2022-08-02 11:04:00 -07:00
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(() => {
2023-01-05 20:10:25 -08:00
setInputAmount(
floorToDecimal(tokenMax.maxAmount, tokenMax.maxDecimals).toFixed()
)
setSizePercentage('100')
2022-12-08 10:23:26 -08:00
}, [tokenMax])
2022-08-02 11:04:00 -07:00
const handleSizePercentage = useCallback(
(percentage: string) => {
setSizePercentage(percentage)
let amount = new Decimal(tokenMax.maxAmount).mul(percentage).div(100)
amount = floorToDecimal(amount, tokenMax.maxDecimals)
2022-08-03 14:46:37 -07:00
2022-08-02 11:04:00 -07:00
setInputAmount(amount.toString())
},
2022-12-08 10:23:26 -08:00
[tokenMax]
2022-08-02 11:04:00 -07:00
)
2022-07-22 23:15:51 -07:00
const handleSelectToken = (token: string) => {
setSelectedToken(token)
setShowTokenList(false)
}
2022-05-03 21:20:14 -07:00
2022-11-20 15:35:59 -08:00
const handleDeposit = useCallback(async () => {
2022-05-03 21:20:14 -07:00
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
if (!mangoAccount || !group || !bank || !publicKey) return
setSubmitting(true)
try {
2022-06-10 11:10:03 -07:00
const tx = await client.tokenDeposit(
group,
mangoAccount,
2022-11-20 15:35:59 -08:00
bank.mint,
parseFloat(inputAmount)
)
2022-07-05 20:37:49 -07:00
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx,
})
await actions.reloadMangoAccount()
actions.fetchWalletTokens(publicKey)
setSubmitting(false)
onSuccess()
2022-07-05 20:37:49 -07:00
} catch (e: any) {
notify({
title: 'Transaction failed',
description: e.message,
2022-12-02 15:47:08 -08:00
txid: e?.txid,
2022-07-05 20:37:49 -07:00
type: 'error',
})
2022-08-02 11:04:00 -07:00
console.error('Error depositing:', e)
setSubmitting(false)
}
}, [bank, publicKey, inputAmount])
2022-05-03 21:20:14 -07:00
2022-11-11 03:24:24 -08:00
// TODO extract into a shared hook for UserSetup.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
).toNumber(),
walletBalanceValue: walletBalance.maxAmount * value[0].uiPrice!,
}
})
: []
2022-09-01 10:33:29 -07:00
return banks
}, [group?.banksMapByName, walletTokens])
const showInsufficientBalance =
tokenMax.maxAmount < Number(inputAmount) ||
(selectedToken === 'SOL' && maxSolDeposit <= 0)
2022-08-25 17:27:05 -07:00
2022-05-03 21:20:14 -07:00
return (
<>
2022-08-24 17:53:31 -07:00
<EnterBottomExitBottom
2022-10-28 03:01:49 -07:00
className="absolute bottom-0 left-0 z-20 h-full w-full overflow-auto rounded-lg bg-th-bkg-1 p-6"
2022-08-24 17:53:31 -07:00
show={showTokenList}
>
2022-12-18 18:08:49 -08:00
<button
onClick={() => setShowTokenList(false)}
className={`absolute left-4 top-4 z-40 w-6 text-th-fgd-4 focus:outline-none md:right-2 md:top-2 md:hover:text-th-active`}
>
<ArrowLeftIcon className={`h-6 w-6`} />
</button>
<h2 className="mb-4 text-center text-lg">
{t('select-deposit-token')}
</h2>
<div className="flex items-center px-4 pb-2">
<div className="w-1/4 text-left">
2022-08-24 17:53:31 -07:00
<p className="text-xs">{t('token')}</p>
</div>
<div className="w-1/4 text-right">
2022-08-24 17:53:31 -07:00
<p className="text-xs">{t('deposit-rate')}</p>
</div>
<div className="w-1/2 text-right">
2022-08-24 17:53:31 -07:00
<p className="whitespace-nowrap text-xs">{t('wallet-balance')}</p>
</div>
</div>
<ActionTokenList
banks={banks}
onSelect={handleSelectToken}
showDepositRates
sortByKey="walletBalanceValue"
valueKey="walletBalance"
/>
</EnterBottomExitBottom>
<FadeInFadeOut show={!showTokenList}>
<div
className="flex flex-col justify-between"
style={{ height: ACCOUNT_ACTION_MODAL_INNER_HEIGHT }}
>
<div>
<InlineNotification
type="info"
desc={`There is a $${ALPHA_DEPOSIT_LIMIT} account value limit during alpha
testing.`}
2022-08-17 16:54:56 -07:00
/>
<SolBalanceWarnings
amount={inputAmount}
2023-01-08 19:38:09 -08:00
className="mt-2"
setAmount={setInputAmount}
selectedToken={selectedToken}
/>
<div className="mt-4 grid grid-cols-2">
<div className="col-span-2 flex justify-between">
<Label text={`${t('deposit')} ${t('token')}`} />
<MaxAmountButton
className="mb-2"
label={t('wallet-balance')}
onClick={setMax}
value={floorToDecimal(
tokenMax.maxAmount,
tokenMax.maxDecimals
).toFixed()}
/>
</div>
<div className="col-span-1 rounded-lg rounded-r-none border border-r-0 border-th-input-border bg-th-input-bkg">
<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>
<div className="col-span-1">
<NumberFormat
name="amountIn"
id="amountIn"
inputMode="decimal"
thousandSeparator=","
allowNegative={false}
isNumericString={true}
decimalScale={bank?.mintDecimals || 6}
className="w-full rounded-lg rounded-l-none border border-th-input-border bg-th-input-bkg p-3 text-right font-mono text-xl text-th-fgd-1 focus:border-th-input-border-hover focus:outline-none md:hover:border-th-input-border-hover"
placeholder="0.00"
value={inputAmount}
onValueChange={(e: NumberFormatValues) => {
setInputAmount(
!Number.isNaN(Number(e.value)) ? e.value : ''
2022-11-19 11:20:36 -08:00
)
}}
isAllowed={withValueLimit}
/>
</div>
<div className="col-span-2 mt-2">
<ButtonGroup
activeValue={sizePercentage}
className="font-mono"
onChange={(p) => handleSizePercentage(p)}
values={['10', '25', '50', '75', '100']}
unit="%"
/>
</div>
2022-07-23 19:48:26 -07:00
</div>
2023-01-06 00:56:34 -08:00
{bank ? (
<div className="my-6 space-y-1.5 border-y border-th-bkg-3 px-2 py-4 text-sm ">
<HealthImpactTokenChange
mintPk={bank.mint}
uiAmount={Number(inputAmount)}
isDeposit
/>
<div className="flex justify-between">
<p>{t('deposit-amount')}</p>
2023-01-08 19:38:09 -08:00
{inputAmount ? (
<AmountWithValue
amount={formatDecimal(
Number(inputAmount),
bank.mintDecimals
)}
value={formatFixedDecimals(
bank.uiPrice * Number(inputAmount),
true
)}
/>
) : (
<AmountWithValue amount="0" value="$0.00" />
)}
2023-01-06 00:56:34 -08:00
</div>
{/* <div className="flex justify-between">
2022-07-23 19:48:26 -07:00
<div className="flex items-center">
2022-10-05 16:14:11 -07:00
<Tooltip content={t('asset-weight-desc')}>
<p className="tooltip-underline">{t('asset-weight')}</p>
</Tooltip>
2022-07-23 19:48:26 -07:00
</div>
2022-10-07 15:27:36 -07:00
<p className="font-mono">{bank!.initAssetWeight.toFixed(2)}x</p>
</div> */}
2023-01-06 00:56:34 -08:00
<div className="flex justify-between">
<Tooltip content={t('tooltip-collateral-value')}>
<p className="tooltip-underline">{t('collateral-value')}</p>
</Tooltip>
<p className="font-mono text-th-fgd-2">
{formatFixedDecimals(
bank.uiPrice *
Number(inputAmount) *
Number(bank.initAssetWeight),
true
)}
</p>
</div>
</div>
2023-01-06 00:56:34 -08:00
) : null}
2022-08-11 22:48:00 -07:00
</div>
<Button
2023-01-03 03:06:37 -08:00
onClick={connected ? handleDeposit : handleConnect}
2022-10-07 15:27:36 -07:00
className="flex w-full items-center justify-center"
disabled={
2023-01-03 03:06:37 -08:00
connected &&
(!inputAmount || exceedsAlphaMax || showInsufficientBalance)
}
size="large"
>
{!connected ? (
<div className="flex items-center">
<LinkIcon className="mr-2 h-5 w-5" />
{t('connect')}
</div>
) : submitting ? (
2022-08-25 17:27:05 -07:00
<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('swap:insufficient-balance', {
symbol: selectedToken,
})}
2022-08-25 17:27:05 -07:00
</div>
) : (
2022-09-07 17:47:59 -07:00
<div className="flex items-center">
<ArrowDownTrayIcon className="mr-2 h-5 w-5" />
{t('deposit')}
</div>
2022-08-25 17:27:05 -07:00
)}
</Button>
</div>
</FadeInFadeOut>
</>
2022-05-03 21:20:14 -07:00
)
}
export default DepositForm