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

82 lines
2.5 KiB
TypeScript
Raw Normal View History

2022-07-28 03:51:36 -07:00
import { ModalProps } from '../../types/modal'
import Modal from '../shared/Modal'
2022-09-12 08:53:57 -07:00
import mangoStore from '@store/mangoStore'
2022-07-28 03:51:36 -07:00
import { notify } from '../../utils/notifications'
import Button from '../shared/Button'
import { useTranslation } from 'next-i18next'
import { useState } from 'react'
import BounceLoader from '../shared/BounceLoader'
import { MangoAccount } from '@blockworks-foundation/mango-v4'
2022-09-11 05:05:21 -07:00
import { TrashIcon } from '@heroicons/react/20/solid'
2022-07-28 03:51:36 -07:00
const CloseAccountModal = ({ isOpen, onClose }: ModalProps) => {
const { t } = useTranslation('common')
const [loading, setLoading] = useState(false)
2022-08-11 21:20:17 -07:00
const set = mangoStore((s) => s.set)
2022-07-28 03:51:36 -07:00
const handleCloseMangoAccount = async () => {
const client = mangoStore.getState().client
const mangoAccount = mangoStore.getState().mangoAccount.current
2022-10-07 04:47:15 -07:00
const mangoAccounts = mangoStore.getState().mangoAccounts
2022-07-28 03:51:36 -07:00
const group = mangoStore.getState().group
if (!mangoAccount || !group) return
setLoading(true)
try {
const tx = await client.closeMangoAccount(group, mangoAccount)
if (tx) {
const newMangoAccounts = mangoAccounts.filter(
(ma) => !ma.publicKey.equals(mangoAccount.publicKey)
)
let newCurrentAccount: MangoAccount
if (newMangoAccounts[0]) {
newCurrentAccount = await newMangoAccounts[0].reload(client)
}
2022-07-28 03:51:36 -07:00
setLoading(false)
onClose()
notify({
title: t('account-closed'),
type: 'success',
txid: tx,
})
2022-08-11 21:20:17 -07:00
set((state) => {
2022-10-07 04:47:15 -07:00
state.mangoAccounts = newMangoAccounts
state.mangoAccount.current = newCurrentAccount
2022-08-11 21:20:17 -07:00
})
2022-07-28 03:51:36 -07:00
}
} catch (e) {
setLoading(false)
2022-08-02 11:04:00 -07:00
console.error(e)
2022-07-28 03:51:36 -07:00
}
}
return (
<Modal isOpen={isOpen} onClose={onClose}>
<div className="h-56">
{loading ? (
<BounceLoader loadingMessage={t('closing-account')} />
) : (
<div className="flex h-full flex-col justify-between">
<div className="pb-6">
<h2 className="mb-1">{t('close-account')}</h2>
2022-07-28 05:13:42 -07:00
<p>{t('close-account-desc')}</p>
2022-07-28 03:51:36 -07:00
</div>
<Button
className="w-full"
onClick={handleCloseMangoAccount}
size="large"
>
2022-09-11 05:05:21 -07:00
<div className="flex items-center justify-center">
<TrashIcon className="mr-2 h-5 w-5" />
{t('close-account')}
</div>
2022-07-28 03:51:36 -07:00
</Button>
</div>
)}
</div>
</Modal>
)
}
export default CloseAccountModal