mango-v4-ui/components/UserSetup.tsx

572 lines
21 KiB
TypeScript
Raw Normal View History

2022-11-01 21:41:12 -07:00
import { Transition } from '@headlessui/react'
import {
ArrowDownTrayIcon,
CheckCircleIcon,
FireIcon,
PencilIcon,
PlusCircleIcon,
XMarkIcon,
} from '@heroicons/react/20/solid'
import { Wallet } from '@project-serum/anchor'
2022-11-11 03:39:14 -08:00
import { TokenInstructions } from '@project-serum/serum'
2022-11-01 21:41:12 -07:00
import { useWallet } from '@solana/wallet-adapter-react'
import mangoStore from '@store/mangoStore'
import Decimal from 'decimal.js'
2022-11-13 03:44:08 -08:00
import useLocalStorageState from 'hooks/useLocalStorageState'
2022-11-01 21:41:12 -07:00
import { useTranslation } from 'next-i18next'
import Image from 'next/image'
2022-11-12 03:16:02 -08:00
import {
ChangeEvent,
ReactNode,
useCallback,
useEffect,
useMemo,
useState,
} from 'react'
2022-11-13 03:44:08 -08:00
import { IS_ONBOARDED_KEY, MIN_SOL_BALANCE } from 'utils/constants'
2022-11-01 21:41:12 -07:00
import { notify } from 'utils/notifications'
import { floorToDecimal } from 'utils/numbers'
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 { walletBalanceForToken } from './modals/DepositModal'
import ParticlesBackground from './ParticlesBackground'
2022-11-13 03:44:08 -08:00
import EditNftProfilePic from './profile/EditNftProfilePic'
import EditProfileForm from './profile/EditProfileForm'
2022-11-01 21:41:12 -07:00
import Button, { IconButton, LinkButton } from './shared/Button'
import InlineNotification from './shared/InlineNotification'
2022-11-11 03:24:24 -08:00
import Loading from './shared/Loading'
2022-11-01 21:41:12 -07:00
import MaxAmountButton from './shared/MaxAmountButton'
import { handleWalletConnect } from './wallet/ConnectWalletButton'
const UserSetup = ({ onClose }: { onClose: () => void }) => {
2022-11-12 02:26:43 -08:00
const { t } = useTranslation(['common', 'onboarding'])
2022-11-01 21:41:12 -07:00
const group = mangoStore((s) => s.group)
const { connected, select, wallet, wallets } = useWallet()
const mangoAccount = mangoStore((s) => s.mangoAccount.current)
const mangoAccountLoading = mangoStore((s) => s.mangoAccount.initialLoad)
const [accountName, setAccountName] = useState('')
const [loadingAccount, setLoadingAccount] = useState(false)
const [showSetupStep, setShowSetupStep] = useState(0)
2022-11-11 03:24:24 -08:00
const [depositToken, setDepositToken] = useState('USDC')
2022-11-01 21:41:12 -07:00
const [depositAmount, setDepositAmount] = useState('')
const [submitDeposit, setSubmitDeposit] = useState(false)
const [sizePercentage, setSizePercentage] = useState('')
2022-11-12 03:16:02 -08:00
const [showEditProfilePic, setShowEditProfilePic] = useState(false)
2022-11-01 21:41:12 -07:00
const walletTokens = mangoStore((s) => s.wallet.tokens)
2022-11-13 03:44:08 -08:00
const [, setIsOnboarded] = useLocalStorageState(IS_ONBOARDED_KEY)
2022-11-01 21:41:12 -07:00
2022-11-11 03:39:14 -08:00
const solBalance = useMemo(() => {
return (
walletTokens.find((t) =>
t.mint.equals(TokenInstructions.WRAPPED_SOL_MINT)
)?.uiAmount || 0
)
}, [walletTokens])
2022-11-01 21:41:12 -07:00
const connectWallet = async () => {
if (wallet) {
try {
await handleWalletConnect(wallet)
} catch (e) {
notify({
title: 'Setup failed. Refresh and try again.',
type: 'error',
})
}
}
}
2022-11-11 03:24:24 -08:00
useEffect(() => {
if (connected) {
setShowSetupStep(2)
}
}, [connected])
2022-11-01 21:41:12 -07:00
const handleCreateAccount = useCallback(async () => {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const actions = mangoStore.getState().actions
if (!group || !wallet) return
setLoadingAccount(true)
try {
const tx = await client.createMangoAccount(
group,
0,
accountName || 'Account 1',
undefined, // tokenCount
undefined, // serum3Count
8, // perpCount
8 // perpOoCount
)
actions.fetchMangoAccounts(wallet!.adapter as unknown as Wallet)
if (tx) {
2022-11-11 03:24:24 -08:00
actions.fetchWalletTokens(wallet!.adapter as unknown as Wallet) // need to update sol balance after account rent
2022-11-01 21:41:12 -07:00
setShowSetupStep(3)
notify({
title: t('new-account-success'),
type: 'success',
txid: tx,
})
}
} catch (e: any) {
notify({
title: t('new-account-failed'),
txid: e?.signature,
type: 'error',
})
console.error(e)
2022-11-11 03:24:24 -08:00
} finally {
setLoadingAccount(false)
2022-11-01 21:41:12 -07:00
}
}, [accountName, wallet, t])
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()
2022-11-13 03:44:08 -08:00
setShowSetupStep(4)
2022-11-01 21:41:12 -07:00
setSubmitDeposit(false)
} catch (e: any) {
notify({
title: 'Transaction failed',
description: e.message,
txid: e?.txid,
type: 'error',
})
setSubmitDeposit(false)
console.error(e)
}
}, [depositAmount, depositToken, onClose])
useEffect(() => {
if (mangoAccount && showSetupStep === 2) {
2022-11-13 03:44:08 -08:00
setIsOnboarded(true)
2022-11-01 21:41:12 -07:00
onClose()
}
}, [mangoAccount, showSetupStep, onClose])
const banks = useMemo(() => {
const banks = group?.banksMapByName
? Array.from(group?.banksMapByName, ([key, value]) => {
const walletBalance = walletBalanceForToken(walletTokens, key)
return {
key,
value,
tokenDecimals: walletBalance.maxDecimals,
walletBalance: floorToDecimal(
walletBalance.maxAmount,
walletBalance.maxDecimals
).toNumber(),
walletBalanceValue: walletBalance.maxAmount * value[0]?.uiPrice!,
}
})
: []
return banks
}, [group?.banksMapByName, walletTokens])
const tokenMax = useMemo(() => {
const bank = banks.find((bank) => bank.key === depositToken)
if (bank) {
return { amount: bank.walletBalance, decimals: bank.tokenDecimals }
}
return { amount: 0, decimals: 0 }
}, [banks, depositToken])
const handleSizePercentage = useCallback(
(percentage: string) => {
setSizePercentage(percentage)
let amount = new Decimal(tokenMax.amount).mul(percentage).div(100)
if (percentage !== '100') {
amount = floorToDecimal(amount, tokenMax.decimals)
}
setDepositAmount(amount.toString())
},
[tokenMax]
)
const handleNextStep = () => {
setShowSetupStep(showSetupStep + 1)
}
return (
2022-11-11 03:24:24 -08:00
<div className="radial-gradient-bg fixed inset-0 z-20 grid overflow-hidden lg:grid-cols-2">
<img
className="absolute -bottom-6 right-0 hidden h-auto w-[53%] lg:block xl:w-[57%]"
src="/images/trade.png"
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={{
2022-11-13 03:44:08 -08:00
width: `${(showSetupStep / 4) * 100}%`,
2022-11-11 03:24:24 -08:00
}}
className="flex bg-th-primary transition-all duration-700 ease-out"
/>
</div>
<div className="absolute top-6 right-6 z-10">
<IconButton hideBg onClick={() => onClose()}>
2022-11-12 02:26:43 -08:00
<XMarkIcon className="h-6 w-6 text-th-fgd-4" />
2022-11-11 03:24:24 -08:00
</IconButton>
</div>
<div className="col-span-1 flex flex-col items-center justify-center p-6 pt-24">
2022-11-12 03:16:02 -08:00
<UserSetupTransition show={showSetupStep === 0}>
2022-11-11 03:24:24 -08:00
<h2 className="mb-4 text-5xl lg:text-6xl">
2022-11-12 02:26:43 -08:00
{t('onboarding:intro-heading')}
2022-11-11 03:24:24 -08:00
</h2>
2022-11-12 02:26:43 -08:00
<p className="mb-4 text-base">{t('onboarding:intro-desc')}</p>
2022-11-01 21:41:12 -07: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-green" />
2022-11-12 02:26:43 -08:00
<p className="text-base">{t('onboarding:bullet-1')}</p>
2022-11-01 21:41:12 -07:00
</div>
{/* <div className="flex items-center space-x-2">
<CheckCircleIcon className="h-5 w-5 text-th-green" />
<p className="text-base">Deeply liquid markets</p>
</div> */}
<div className="flex items-center space-x-2">
<CheckCircleIcon className="h-5 w-5 text-th-green" />
2022-11-12 02:26:43 -08:00
<p className="text-base">{t('onboarding:bullet-2')}</p>
2022-11-01 21:41:12 -07:00
</div>
<div className="flex items-center space-x-2">
<CheckCircleIcon className="h-5 w-5 text-th-green" />
2022-11-12 02:26:43 -08:00
<p className="text-base">{t('onboarding:bullet-3')}</p>
2022-11-01 21:41:12 -07:00
</div>
<div className="flex items-center space-x-2">
<CheckCircleIcon className="h-5 w-5 text-th-green" />
2022-11-12 02:26:43 -08:00
<p className="text-base">{t('onboarding:bullet-4')}</p>
2022-11-01 21:41:12 -07:00
</div>
</div>
2022-11-11 03:24:24 -08:00
<Button className="w-44" onClick={handleNextStep} size="large">
2022-11-01 21:41:12 -07:00
<div className="flex items-center justify-center">
<FireIcon className="mr-2 h-5 w-5" />
2022-11-12 02:26:43 -08:00
{t('onboarding:lets-go')}
2022-11-01 21:41:12 -07:00
</div>
</Button>
2022-11-12 03:16:02 -08:00
</UserSetupTransition>
<UserSetupTransition delay show={showSetupStep === 1}>
2022-11-11 03:24:24 -08:00
{showSetupStep === 1 ? (
2022-11-01 21:41:12 -07:00
<div>
2022-11-12 02:26:43 -08:00
<h2 className="mb-6 text-5xl lg:text-6xl">
{t('onboarding:connect-wallet')}
</h2>
<p className="mb-2 text-base">{t('onboarding:choose-wallet')}</p>
2022-11-01 21:41:12 -07:00
<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-primary text-th-fgd-1 md:hover:border-th-primary'
: '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>
2022-11-11 03:24:24 -08:00
<Button
className="mt-10 flex w-44 items-center justify-center"
onClick={connectWallet}
size="large"
>
{connected && mangoAccountLoading ? (
<Loading />
) : (
<div className="flex items-center justify-center">
<WalletIcon className="mr-2 h-5 w-5" />
2022-11-12 02:26:43 -08:00
{t('onboarding:connect-wallet')}
2022-11-11 03:24:24 -08:00
</div>
)}
2022-11-01 21:41:12 -07:00
</Button>
</div>
2022-11-11 03:24:24 -08:00
) : null}
2022-11-12 03:16:02 -08:00
</UserSetupTransition>
<UserSetupTransition
delay
2022-11-11 03:24:24 -08:00
show={showSetupStep === 2 && !mangoAccountLoading}
2022-11-01 21:41:12 -07:00
>
2022-11-11 03:24:24 -08:00
{showSetupStep === 2 ? (
2022-11-01 21:41:12 -07:00
<div>
<div className="pb-6">
2022-11-11 03:24:24 -08:00
<h2 className="mb-4 text-5xl lg:text-6xl">
2022-11-12 02:26:43 -08:00
{t('onboarding:create-account')}
2022-11-11 03:24:24 -08:00
</h2>
2022-11-01 21:41:12 -07:00
<p className="text-base">
2022-11-12 02:26:43 -08:00
{t('onboarding:create-account-desc')}
2022-11-01 21:41:12 -07:00
</p>
</div>
<div className="pb-4">
2022-11-13 03:44:08 -08:00
<Label text={t('account-name')} optional />
2022-11-01 21:41:12 -07:00
<Input
type="text"
name="name"
id="name"
2022-11-13 03:44:08 -08:00
placeholder="e.g. Highly Profitable Trading Strategies"
2022-11-01 21:41:12 -07:00
value={accountName}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setAccountName(e.target.value)
}
/>
</div>
<div>
<InlineNotification type="info" desc={t('insufficient-sol')} />
<div className="mt-10">
<Button
2022-11-11 03:24:24 -08:00
className="mb-6 flex w-44 items-center justify-center"
2022-11-11 03:39:14 -08:00
disabled={solBalance < MIN_SOL_BALANCE}
2022-11-11 03:24:24 -08:00
onClick={handleCreateAccount}
2022-11-01 21:41:12 -07:00
size="large"
>
2022-11-11 03:24:24 -08:00
{loadingAccount ? (
<Loading />
) : (
<div className="flex items-center justify-center">
<PlusCircleIcon className="mr-2 h-5 w-5" />
2022-11-12 02:26:43 -08:00
{t('create-account')}
2022-11-11 03:24:24 -08:00
</div>
)}
2022-11-01 21:41:12 -07:00
</Button>
2022-11-11 03:39:14 -08:00
{solBalance < MIN_SOL_BALANCE ? (
<div className="mb-6">
<InlineNotification
type="error"
desc={t('deposit-more-sol')}
/>
</div>
) : null}
2022-11-01 21:41:12 -07:00
<LinkButton onClick={onClose}>
<span className="default-transition text-th-fgd-4 underline md:hover:text-th-fgd-3 md:hover:no-underline">
2022-11-12 02:26:43 -08:00
{t('onboarding:skip')}
2022-11-01 21:41:12 -07:00
</span>
</LinkButton>
</div>
</div>
</div>
2022-11-11 03:24:24 -08:00
) : null}
2022-11-12 03:16:02 -08:00
</UserSetupTransition>
<UserSetupTransition delay show={showSetupStep === 3}>
2022-11-11 03:24:24 -08:00
{showSetupStep === 3 ? (
<div className="relative">
2022-11-12 02:26:43 -08:00
<h2 className="mb-6 text-5xl lg:text-6xl">
{t('onboarding:fund-account')}
</h2>
2022-11-12 03:16:02 -08:00
<UserSetupTransition show={depositToken.length > 0}>
2022-11-11 03:24:24 -08:00
<div className="flex justify-between">
2022-11-12 02:26:43 -08:00
<Label text={t('amount')} />
2022-11-11 03:24:24 -08:00
<MaxAmountButton
className="mb-2"
label="Wallet Max"
onClick={() =>
setDepositAmount(
floorToDecimal(
tokenMax.amount,
tokenMax.decimals
).toFixed()
)
}
value={floorToDecimal(
tokenMax.amount,
tokenMax.decimals
).toFixed()}
/>
</div>
<div className="mb-10 grid grid-cols-2">
<button
className="col-span-1 flex items-center rounded-lg rounded-r-none border border-r-0 border-th-bkg-4 bg-transparent px-4 hover:bg-transparent"
onClick={() => setDepositToken('')}
2022-11-01 21:41:12 -07:00
>
2022-11-11 03:24:24 -08:00
<div className="ml-1.5 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-1.5 text-xl font-bold text-th-fgd-1">
{depositToken}
2022-11-01 21:41:12 -07:00
</p>
</div>
2022-11-11 03:24:24 -08:00
<PencilIcon className="ml-2 h-5 w-5 text-th-fgd-3" />
2022-11-01 21:41:12 -07:00
</div>
2022-11-11 03:24:24 -08:00
</button>
<Input
className="col-span-1 w-full rounded-lg rounded-l-none border border-th-bkg-4 bg-transparent p-3 text-right text-xl font-bold tracking-wider text-th-fgd-1 focus:outline-none"
type="text"
name="deposit"
id="deposit"
placeholder="0.00"
value={depositAmount}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setDepositAmount(e.target.value)
}
/>
<div className="col-span-2 mt-2">
<ButtonGroup
activeValue={sizePercentage}
onChange={(p) => handleSizePercentage(p)}
values={['10', '25', '50', '75', '100']}
unit="%"
2022-11-01 21:41:12 -07:00
/>
</div>
2022-11-11 03:24:24 -08:00
</div>
2022-11-01 21:41:12 -07:00
<Button
2022-11-11 03:24:24 -08:00
className="mb-6 flex w-44 items-center justify-center"
2022-11-01 21:41:12 -07:00
disabled={!depositAmount || !depositToken}
onClick={handleDeposit}
size="large"
>
2022-11-11 03:24:24 -08:00
{submitDeposit ? (
<Loading />
) : (
<div className="flex items-center justify-center">
<ArrowDownTrayIcon className="mr-2 h-5 w-5" />
2022-11-12 02:26:43 -08:00
{t('deposit')}
2022-11-11 03:24:24 -08:00
</div>
)}
2022-11-01 21:41:12 -07:00
</Button>
2022-11-13 03:44:08 -08:00
<LinkButton onClick={() => setShowSetupStep(4)}>
2022-11-01 21:41:12 -07:00
<span className="default-transition text-th-fgd-4 underline md:hover:text-th-fgd-3 md:hover:no-underline">
2022-11-12 02:26:43 -08:00
{t('onboarding:skip')}
2022-11-01 21:41:12 -07:00
</span>
</LinkButton>
2022-11-12 03:16:02 -08:00
</UserSetupTransition>
<UserSetupTransition show={depositToken.length === 0}>
2022-11-11 03:24:24 -08:00
<div
className="thin-scroll absolute top-36 w-full overflow-auto"
style={{ height: 'calc(100vh - 380px)' }}
>
<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={setDepositToken}
showDepositRates
sortByKey="walletBalanceValue"
valueKey="walletBalance"
/>
</div>
2022-11-12 03:16:02 -08:00
</UserSetupTransition>
2022-11-01 21:41:12 -07:00
</div>
2022-11-11 03:24:24 -08:00
) : null}
2022-11-12 03:16:02 -08:00
</UserSetupTransition>
2022-11-13 03:44:08 -08:00
<UserSetupTransition delay show={showSetupStep === 4}>
{showSetupStep === 4 ? (
<div className="relative">
<h2 className="mb-4 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-11-01 21:41:12 -07:00
</div>
2022-11-11 03:24:24 -08:00
<div className="col-span-1 hidden h-screen lg:block">
2022-11-10 04:58:13 -08:00
<ParticlesBackground />
2022-11-01 21:41:12 -07:00
</div>
</div>
)
}
export default UserSetup
2022-11-12 03:16:02 -08:00
const UserSetupTransition = ({
show,
children,
delay = false,
}: {
show: boolean
children: ReactNode
delay?: boolean
}) => {
return (
<Transition
appear
className="h-full w-full max-w-md"
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>
)
}