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

634 lines
24 KiB
TypeScript
Raw Normal View History

2022-12-20 17:14:35 -08:00
import { toUiDecimalsForQuote } from '@blockworks-foundation/mango-v4'
import { Transition } from '@headlessui/react'
import {
ArrowDownTrayIcon,
CheckCircleIcon,
ExclamationCircleIcon,
FireIcon,
PencilIcon,
} from '@heroicons/react/20/solid'
import { useWallet } from '@solana/wallet-adapter-react'
import mangoStore from '@store/mangoStore'
import Decimal from 'decimal.js'
import useMangoAccount from 'hooks/useMangoAccount'
import useMangoGroup from 'hooks/useMangoGroup'
import useSolBalance from 'hooks/useSolBalance'
import { useTranslation } from 'next-i18next'
import Image from 'next/image'
import {
ChangeEvent,
ReactNode,
useCallback,
useEffect,
useMemo,
useState,
} from 'react'
import { ALPHA_DEPOSIT_LIMIT } from 'utils/constants'
import { notify } from 'utils/notifications'
import ActionTokenList from '../account/ActionTokenList'
import ButtonGroup from '../forms/ButtonGroup'
import Input from '../forms/Input'
import Label from '../forms/Label'
import WalletIcon from '../icons/WalletIcon'
import ParticlesBackground from '../ParticlesBackground'
// import EditNftProfilePic from '../profile/EditNftProfilePic'
// import EditProfileForm from '../profile/EditProfileForm'
2022-12-20 17:14:35 -08:00
import Button, { LinkButton } from '../shared/Button'
import InlineNotification from '../shared/InlineNotification'
import Loading from '../shared/Loading'
import MaxAmountButton from '../shared/MaxAmountButton'
import SolBalanceWarnings from '../shared/SolBalanceWarnings'
import { useEnhancedWallet } from '../wallet/EnhancedWalletProvider'
import Modal from '../shared/Modal'
2023-01-03 15:58:31 -08:00
import NumberFormat, { NumberFormatValues } from 'react-number-format'
import { withValueLimit } from '@components/swap/SwapForm'
2023-01-29 20:13:38 -08:00
import useBanksWithBalances from 'hooks/useBanksWithBalances'
import BankAmountWithValue from '@components/shared/BankAmountWithValue'
2022-12-20 17:14:35 -08:00
const UserSetupModal = ({
isOpen,
onClose,
}: {
isOpen: boolean
onClose: () => void
}) => {
const { t } = useTranslation(['common', 'onboarding', 'swap'])
const { group } = useMangoGroup()
const { connected, select, wallet, wallets, publicKey } = useWallet()
2022-12-20 17:14:35 -08:00
const { mangoAccount } = useMangoAccount()
const mangoAccountLoading = mangoStore((s) => s.mangoAccount.initialLoad)
const [accountName, setAccountName] = useState('')
const [loadingAccount, setLoadingAccount] = useState(false)
const [showSetupStep, setShowSetupStep] = useState(0)
const [depositToken, setDepositToken] = useState('USDC')
const [depositAmount, setDepositAmount] = useState('')
const [submitDeposit, setSubmitDeposit] = useState(false)
const [sizePercentage, setSizePercentage] = useState('')
// const [showEditProfilePic, setShowEditProfilePic] = useState(false)
2022-12-20 17:14:35 -08:00
const { handleConnect } = useEnhancedWallet()
const { maxSolDeposit } = useSolBalance()
2023-01-29 20:13:38 -08:00
const banks = useBanksWithBalances('walletBalance')
2022-12-20 17:14:35 -08:00
useEffect(() => {
if (connected) {
setShowSetupStep(2)
}
}, [connected])
const handleCreateAccount = useCallback(async () => {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const actions = mangoStore.getState().actions
if (!group || !publicKey) return
2022-12-20 17:14:35 -08:00
setLoadingAccount(true)
try {
const tx = await client.createMangoAccount(
group,
0,
accountName || 'Account 1',
undefined, // tokenCount
undefined, // serum3Count
8, // perpCount
8 // perpOoCount
)
actions.fetchMangoAccounts(publicKey)
2022-12-20 17:14:35 -08:00
if (tx) {
actions.fetchWalletTokens(publicKey) // need to update sol balance after account rent
2022-12-20 17:14:35 -08:00
setShowSetupStep(3)
notify({
title: t('new-account-success'),
type: 'success',
txid: tx,
})
}
} catch (e: any) {
notify({
title: t('new-account-failed'),
txid: e?.txid,
type: 'error',
})
console.error(e)
} finally {
setLoadingAccount(false)
}
}, [accountName, publicKey, t])
2022-12-20 17:14:35 -08:00
const handleDeposit = useCallback(async () => {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const actions = mangoStore.getState().actions
const mangoAccount = mangoStore.getState().mangoAccount.current
if (!mangoAccount || !group) return
const bank = group.banksMapByName.get(depositToken)![0]
try {
setSubmitDeposit(true)
const tx = await client.tokenDeposit(
group,
mangoAccount,
bank.mint,
parseFloat(depositAmount)
)
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx,
})
await actions.reloadMangoAccount()
setSubmitDeposit(false)
onClose()
// setShowSetupStep(4)
2022-12-20 17:14:35 -08:00
} catch (e: any) {
notify({
title: 'Transaction failed',
description: e.message,
txid: e?.txid,
type: 'error',
})
setSubmitDeposit(false)
console.error(e)
}
}, [depositAmount, depositToken])
useEffect(() => {
if (mangoAccount && showSetupStep === 2) {
onClose()
}
}, [mangoAccount, showSetupStep, onClose])
const depositBank = useMemo(() => {
2023-01-29 20:13:38 -08:00
return banks.find((b) => b.bank.name === depositToken)?.bank
2022-12-20 17:14:35 -08:00
}, [depositToken, banks])
const exceedsAlphaMax = useMemo(() => {
const mangoAccount = mangoStore.getState().mangoAccount.current
if (!group || !mangoAccount) return
if (
mangoAccount.owner.toString() ===
'8SSLjXBEVk9nesbhi9UMCA32uijbVBUqWoKPPQPTekzt'
)
return false
const accountValue = toUiDecimalsForQuote(
mangoAccount.getEquity(group)!.toNumber()
)
return (
parseFloat(depositAmount) * (depositBank?.uiPrice || 1) >
ALPHA_DEPOSIT_LIMIT || accountValue > ALPHA_DEPOSIT_LIMIT
)
}, [depositAmount, depositBank, group])
const tokenMax = useMemo(() => {
2023-01-29 20:13:38 -08:00
const bank = banks.find((b) => b.bank.name === depositToken)
2022-12-20 17:14:35 -08:00
if (bank) {
2023-01-29 20:13:38 -08:00
return { amount: bank.walletBalance, decimals: bank.bank.mintDecimals }
2022-12-20 17:14:35 -08:00
}
return { amount: 0, decimals: 0 }
}, [banks, depositToken])
2023-01-03 15:58:31 -08:00
const showInsufficientBalance =
tokenMax.amount < Number(depositAmount) ||
(depositToken === 'SOL' && maxSolDeposit <= 0)
2022-12-20 17:14:35 -08:00
const setMax = useCallback(() => {
const max = new Decimal(tokenMax.amount).toDecimalPlaces(
tokenMax.decimals,
Decimal.ROUND_FLOOR
)
setDepositAmount(max.toString())
setSizePercentage('100')
}, [tokenMax])
2022-12-20 17:14:35 -08:00
const handleSizePercentage = useCallback(
(percentage: string) => {
setSizePercentage(percentage)
const amount = new Decimal(tokenMax.amount)
.mul(percentage)
.div(100)
.toDecimalPlaces(tokenMax.decimals, Decimal.ROUND_FLOOR)
2022-12-20 17:14:35 -08:00
setDepositAmount(amount.toString())
},
[tokenMax]
)
const handleNextStep = () => {
setShowSetupStep(showSetupStep + 1)
}
return (
<Modal isOpen={isOpen} onClose={onClose} fullScreen disableOutsideClose>
2022-12-20 17:14:35 -08:00
<div className="radial-gradient-bg grid h-screen overflow-auto text-left lg:grid-cols-2">
<img
className="absolute -bottom-6 right-0 hidden h-auto w-[53%] lg:block xl:w-[57%]"
2023-01-02 17:18:17 -08:00
src="/images/trade@0.75x.png"
srcSet="/images/trade@0.75x.png 1157w, /images/trade@1x.png 1542w,
2023-01-02 16:30:19 -08:00
/images/trade@2x.png 3084w"
2023-01-02 17:18:17 -08:00
sizes="(max-width: 1600px) 1157px, (max-width: 2500px) 1542px, 3084px"
2022-12-20 17:14:35 -08:00
alt="next"
/>
<img
className={`absolute top-6 left-6 h-10 w-10 flex-shrink-0`}
src="/logos/logo-mark.svg"
alt="next"
/>
<div className="absolute top-0 left-0 z-10 flex h-1.5 w-full flex-grow bg-th-bkg-3">
<div
style={{
width: `${(showSetupStep / 3) * 100}%`,
2022-12-20 17:14:35 -08:00
}}
className="flex bg-th-active transition-all duration-700 ease-out"
/>
</div>
<div className="col-span-1 flex flex-col items-center justify-center p-6 pt-24">
<UserSetupTransition show={showSetupStep === 0}>
<h2 className="mb-4 font-display text-3xl tracking-normal md:text-5xl lg:text-6xl">
{t('onboarding:intro-heading')}
</h2>
2022-12-20 19:36:40 -08:00
<p className="text-base sm:mb-4">{t('onboarding:intro-desc')}</p>
2022-12-20 17:14:35 -08:00
<div className="mb-6 space-y-2 py-3">
<div className="flex items-center space-x-2">
<CheckCircleIcon className="h-5 w-5 text-th-success" />
<p className="text-base">{t('onboarding:bullet-1')}</p>
</div>
<div className="flex items-center space-x-2">
<CheckCircleIcon className="h-5 w-5 text-th-success" />
<p className="text-base">{t('onboarding:bullet-2')}</p>
</div>
<div className="flex items-center space-x-2">
<CheckCircleIcon className="h-5 w-5 text-th-success" />
<p className="text-base">{t('onboarding:bullet-3')}</p>
</div>
<div className="flex items-center space-x-2">
<CheckCircleIcon className="h-5 w-5 text-th-success" />
<p className="text-base">{t('onboarding:bullet-4')}</p>
</div>
</div>
<Button
className="mb-12 w-44"
onClick={handleNextStep}
size="large"
>
<div className="flex items-center justify-center">
<FireIcon className="mr-2 h-5 w-5" />
{t('onboarding:lets-go')}
</div>
</Button>
</UserSetupTransition>
<UserSetupTransition delay show={showSetupStep === 1}>
{showSetupStep === 1 ? (
<div>
<h2 className="mb-6 font-display text-3xl tracking-normal md:text-5xl lg:text-6xl">
{t('onboarding:connect-wallet')}
</h2>
<p className="mb-2 text-base">
{t('onboarding:choose-wallet')}
</p>
<div className="space-y-2">
{wallets?.map((w) => (
<button
className={`col-span-1 w-full rounded-md border py-3 px-4 text-base font-normal focus:outline-none md:hover:cursor-pointer md:hover:border-th-fgd-4 ${
w.adapter.name === wallet?.adapter.name
? 'border-th-active text-th-fgd-1 md:hover:border-th-active'
: 'border-th-bkg-4 text-th-fgd-4'
}`}
onClick={() => {
select(w.adapter.name)
}}
key={w.adapter.name}
>
<div className="flex items-center">
<img
src={w.adapter.icon}
className="mr-2 h-5 w-5"
alt={`${w.adapter.name} icon`}
/>
{w.adapter.name}
</div>
</button>
))}
</div>
<Button
2023-01-03 15:58:31 -08:00
className="mt-10 flex items-center justify-center"
2022-12-20 17:14:35 -08:00
onClick={handleConnect}
size="large"
>
{connected && mangoAccountLoading ? (
<Loading />
) : (
<div className="flex items-center justify-center">
<WalletIcon className="mr-2 h-5 w-5" />
{t('onboarding:connect-wallet')}
</div>
)}
</Button>
</div>
) : null}
</UserSetupTransition>
<UserSetupTransition
delay
show={showSetupStep === 2 && !mangoAccountLoading}
>
{showSetupStep === 2 ? (
<div>
<div className="pb-6">
<h2 className="mb-4 font-display text-3xl tracking-normal md:text-5xl lg:text-6xl">
{t('onboarding:create-account')}
</h2>
<p className="text-base">
{t('onboarding:create-account-desc')}
</p>
</div>
2023-01-03 15:58:31 -08:00
<div className="mb-4">
2022-12-20 17:14:35 -08:00
<Label text={t('account-name')} optional />
<Input
type="text"
name="name"
id="name"
placeholder="e.g. Main Account"
value={accountName}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setAccountName(e.target.value)
}
2023-01-25 01:19:12 -08:00
maxLength={30}
2022-12-20 17:14:35 -08:00
/>
</div>
<SolBalanceWarnings className="mt-4" />
2023-01-03 15:58:31 -08:00
<div className="mt-2">
2022-12-20 17:14:35 -08:00
<InlineNotification
type="info"
desc={t('insufficient-sol')}
/>
<div className="mt-10">
<Button
2023-01-03 15:58:31 -08:00
className="mb-6 flex items-center justify-center"
2022-12-20 17:14:35 -08:00
disabled={maxSolDeposit <= 0}
onClick={handleCreateAccount}
size="large"
>
{loadingAccount ? (
<Loading />
) : (
<div className="flex items-center justify-center">
{t('create-account')}
</div>
)}
</Button>
<LinkButton onClick={onClose}>
<span className="default-transition text-th-fgd-4 underline md:hover:text-th-fgd-3 md:hover:no-underline">
{t('onboarding:skip')}
</span>
</LinkButton>
</div>
</div>
</div>
) : null}
</UserSetupTransition>
<UserSetupTransition delay show={showSetupStep === 3}>
{showSetupStep === 3 ? (
<div className="relative">
<h2 className="mb-6 font-display text-3xl tracking-normal md:text-5xl lg:text-6xl">
{t('onboarding:fund-account')}
</h2>
<UserSetupTransition show={depositToken.length > 0}>
<div className="mb-4">
<InlineNotification
type="info"
desc={`There is a $${ALPHA_DEPOSIT_LIMIT} account value limit during alpha testing.`}
/>
<SolBalanceWarnings
amount={depositAmount}
className="mt-4"
2022-12-20 17:14:35 -08:00
setAmount={setDepositAmount}
selectedToken={depositToken}
/>
</div>
<div className="flex justify-between">
<Label text={t('amount')} />
<MaxAmountButton
className="mb-2"
2023-01-23 19:04:05 -08:00
decimals={tokenMax.decimals}
2023-01-03 15:58:31 -08:00
label="Max"
onClick={setMax}
2023-01-23 19:04:05 -08:00
value={tokenMax.amount}
2022-12-20 17:14:35 -08:00
/>
</div>
<div className="mb-6 grid grid-cols-2">
<button
2023-01-03 15:58:31 -08:00
className="col-span-1 flex items-center rounded-lg rounded-r-none border border-r-0 border-th-input-border bg-th-input-bkg px-4"
2022-12-20 17:14:35 -08:00
onClick={() => setDepositToken('')}
>
<div className="flex w-full items-center justify-between">
<div className="flex items-center">
<Image
alt=""
width="20"
height="20"
src={`/icons/${depositToken.toLowerCase()}.svg`}
/>
<p className="ml-2 text-xl font-bold text-th-fgd-1">
{depositToken}
</p>
</div>
<PencilIcon className="ml-2 h-5 w-5 text-th-fgd-3" />
</div>
</button>
2023-01-03 15:58:31 -08:00
<NumberFormat
name="amountIn"
id="amountIn"
inputMode="decimal"
thousandSeparator=","
allowNegative={false}
isNumericString={true}
decimalScale={tokenMax.decimals || 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"
2022-12-20 17:14:35 -08:00
placeholder="0.00"
value={depositAmount}
2023-01-03 15:58:31 -08:00
onValueChange={(e: NumberFormatValues) => {
setDepositAmount(
!Number.isNaN(Number(e.value)) ? e.value : ''
)
}}
isAllowed={withValueLimit}
2022-12-20 17:14:35 -08:00
/>
<div className="col-span-2 mt-2">
<ButtonGroup
activeValue={sizePercentage}
onChange={(p) => handleSizePercentage(p)}
values={['10', '25', '50', '75', '100']}
unit="%"
/>
</div>
</div>
2023-01-06 02:32:54 -08:00
{depositBank ? (
<div className="border-y border-th-bkg-3">
<div className="flex justify-between px-2 py-4">
<p>{t('deposit-amount')}</p>
<p className="font-mono text-th-fgd-2">
2023-01-29 20:13:38 -08:00
<BankAmountWithValue
amount={depositAmount}
bank={depositBank}
/>
{/* {depositAmount ? (
2023-01-06 02:32:54 -08:00
<>
2023-01-24 17:12:13 -08:00
<FormatNumericValue
value={depositAmount}
decimals={depositBank.mintDecimals}
/>{' '}
2023-01-06 02:32:54 -08:00
<span className="text-xs text-th-fgd-3">
(
2023-01-24 16:54:24 -08:00
<FormatNumericValue
value={
depositBank.uiPrice * Number(depositAmount)
}
decimals={2}
isUsd
/>
2023-01-06 02:32:54 -08:00
)
</span>
</>
) : (
<>
0{' '}
<span className="text-xs text-th-fgd-3">
($0.00)
</span>
</>
2023-01-29 20:13:38 -08:00
)} */}
2023-01-06 02:32:54 -08:00
</p>
</div>
2022-12-20 17:14:35 -08:00
</div>
2023-01-06 02:32:54 -08:00
) : null}
2022-12-20 17:14:35 -08:00
<Button
2023-01-06 02:32:54 -08:00
className="mb-6 mt-10 flex items-center justify-center"
2022-12-20 17:14:35 -08:00
disabled={
!depositAmount ||
!depositToken ||
exceedsAlphaMax ||
showInsufficientBalance
}
onClick={handleDeposit}
size="large"
>
{submitDeposit ? (
<Loading />
) : showInsufficientBalance ? (
<div className="flex items-center">
<ExclamationCircleIcon className="mr-2 h-5 w-5 flex-shrink-0" />
{t('swap:insufficient-balance', {
symbol: depositToken,
})}
</div>
) : (
<div className="flex items-center justify-center">
<ArrowDownTrayIcon className="mr-2 h-5 w-5" />
{t('deposit')}
</div>
)}
</Button>
<LinkButton onClick={onClose}>
2022-12-20 17:14:35 -08:00
<span className="default-transition text-th-fgd-4 underline md:hover:text-th-fgd-3 md:hover:no-underline">
{t('onboarding:skip')}
</span>
</LinkButton>
</UserSetupTransition>
<UserSetupTransition show={depositToken.length === 0}>
<div
className="thin-scroll absolute top-36 w-full overflow-auto"
style={{ height: 'calc(100vh - 380px)' }}
>
<div className="flex items-center px-4 pb-2">
<div className="w-1/4">
2022-12-20 17:14:35 -08:00
<p className="text-xs">{t('token')}</p>
</div>
<div className="w-1/4 text-right">
2022-12-20 17:14:35 -08:00
<p className="text-xs">{t('deposit-rate')}</p>
</div>
<div className="w-1/2 text-right">
2022-12-20 17:14:35 -08:00
<p className="whitespace-nowrap text-xs">
{t('wallet-balance')}
</p>
</div>
</div>
<ActionTokenList
banks={banks}
onSelect={setDepositToken}
showDepositRates
valueKey="walletBalance"
/>
</div>
</UserSetupTransition>
</div>
) : null}
</UserSetupTransition>
{/* <UserSetupTransition delay show={showSetupStep === 4}>
2022-12-20 17:14:35 -08:00
{showSetupStep === 4 ? (
<div className="relative">
<h2 className="mb-4 font-display text-3xl tracking-normal md:text-5xl lg:text-6xl">
{t('onboarding:your-profile')}
</h2>
<p className="text-base">{t('onboarding:profile-desc')}</p>
{!showEditProfilePic ? (
<div className="mt-6 border-t border-th-bkg-3 pt-3">
<EditProfileForm
onFinish={onClose}
onEditProfileImage={() => setShowEditProfilePic(true)}
onboarding
/>
<LinkButton className="mt-6" onClick={onClose}>
<span className="default-transition text-th-fgd-4 underline md:hover:text-th-fgd-3 md:hover:no-underline">
{t('onboarding:skip-finish')}
</span>
</LinkButton>
</div>
) : null}
<UserSetupTransition show={showEditProfilePic}>
<div
className="thin-scroll absolute mt-6 w-full overflow-auto border-t border-th-bkg-3 px-2 pt-6"
style={{ height: 'calc(100vh - 360px)' }}
>
<EditNftProfilePic
onClose={() => setShowEditProfilePic(false)}
/>
</div>
</UserSetupTransition>
</div>
) : null}
</UserSetupTransition> */}
2022-12-20 17:14:35 -08:00
</div>
<div className="col-span-1 hidden h-screen lg:block">
<ParticlesBackground />
</div>
</div>
</Modal>
)
}
export default UserSetupModal
const UserSetupTransition = ({
show,
children,
delay = false,
}: {
show: boolean
children: ReactNode
delay?: boolean
}) => {
return (
<Transition
appear
className="h-full w-full max-w-lg"
show={show}
enter={`transition ease-in duration-300 ${delay ? 'delay-300' : ''}`}
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition ease-out duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
{children}
</Transition>
)
}