mars-v2-frontend/hooks/mutations/useWithdrawFunds.tsx
Gustavo Mauricio 9bc09c68af
Withdraw assets from account (#43)
* withdraw modal and respective hooks initial commit

* max withdraw amount hook logic improvements

* withdraw flow code cleanup

* reset modal state when reopened

* memoize withdraw amount. percentage value fix

* unused store selector

* credit manager and accountnft clients added to store

* script to pull generated types from rover repo
2022-11-07 16:36:12 +00:00

77 lines
1.9 KiB
TypeScript

import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useMemo } from 'react'
import { toast } from 'react-toastify'
import useWalletStore from 'stores/useWalletStore'
import { hardcodedFee } from 'utils/contants'
import useCreditManagerStore from 'stores/useCreditManagerStore'
import { queryKeys } from 'types/query-keys-factory'
const useWithdrawFunds = (
amount: number,
borrowAmount: number,
denom: string,
options?: {
onSuccess?: () => void
}
) => {
const selectedAccount = useCreditManagerStore((s) => s.selectedAccount ?? '')
const address = useWalletStore((s) => s.address)
const creditManagerClient = useWalletStore((s) => s.clients.creditManager)
const queryClient = useQueryClient()
const actions = useMemo(() => {
if (borrowAmount > 0) {
return [
{
borrow: {
denom,
amount: String(borrowAmount),
},
},
{
withdraw: {
denom,
amount: String(amount),
},
},
]
}
return [
{
withdraw: {
denom,
amount: String(amount),
},
},
]
}, [amount, borrowAmount, denom])
const { onSuccess } = { ...options }
return useMutation(
async () =>
creditManagerClient?.updateCreditAccount(
{ accountId: selectedAccount, actions },
hardcodedFee
),
{
onSuccess: () => {
queryClient.invalidateQueries(queryKeys.creditAccountsPositions(selectedAccount))
queryClient.invalidateQueries(queryKeys.tokenBalance(address, denom))
queryClient.invalidateQueries(queryKeys.allBalances(address))
queryClient.invalidateQueries(queryKeys.redbankBalances())
onSuccess && onSuccess()
},
onError: (err: Error) => {
toast.error(err.message)
},
}
)
}
export default useWithdrawFunds