import { useQueryClient, useMutation, MutationOptions, DefaultError, } from "@tanstack/react-query" import { useAuthApiClient } from "./useAuthApiClient" import { QUERY_KEYS } from "./constants" import type { CreateAccountRequest, CreateAccountResponse } from "../api" import { useWalletAccount } from "./useWalletAccount" import { getBitcoinPublicKeyFromConnector } from "../utils/wagmi" export function useCreateAccount( mutationOptions: Omit< MutationOptions, "mutationFn" | "mutationKey" > = {}, ) { const queryClient = useQueryClient() const authApiClient = useAuthApiClient() const walletAccount = useWalletAccount() const { onSuccess: customOnSuccess, ...restMutationOptions } = mutationOptions const { mutate, mutateAsync, ...rest } = useMutation({ mutationFn: async ( createAccountMutationFnParameters: CreateAccountRequest, ) => { if (createAccountMutationFnParameters.type === "wallet") { if (!walletAccount?.connector) { throw new Error("Connector not defined.") } const bitcoinPublicKey = await getBitcoinPublicKeyFromConnector( walletAccount.connector, ) // Creating bitcoin mezo account if (bitcoinPublicKey) { return authApiClient.createAccount({ ...createAccountMutationFnParameters, bitcoinPublicKey, }) } } // Creating evm mezo account return authApiClient.createAccount({ ...createAccountMutationFnParameters, }) }, onSuccess: (data, variables, context) => { queryClient.resetQueries({ queryKey: [QUERY_KEYS.ACCOUNT], }) if (customOnSuccess) customOnSuccess(data, variables, context) }, ...restMutationOptions, }) return { createAccount: mutate, createAccountAsync: mutateAsync, ...rest } }