Skip to content

Commit

Permalink
Refactor useDepositBTCTransaction and use useMutation
Browse files Browse the repository at this point in the history
  • Loading branch information
kkosiorowska committed Nov 5, 2024
1 parent 8ceb6b4 commit 1717ea5
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 78 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect } from "react"
import React, { useCallback } from "react"
import {
useActionFlowPause,
useActionFlowTokenAmount,
Expand Down Expand Up @@ -34,57 +34,58 @@ export default function DepositBTCModal() {
}, [dispatch, handleBitcoinBalanceInvalidation])

const onError = useCallback(
(error?: unknown) => {
console.error(error)
dispatch(setStatus(PROCESS_STATUSES.FAILED))
},
() => dispatch(setStatus(PROCESS_STATUSES.FAILED)),
[dispatch],
)

const handleStake = useExecuteFunction(stake, onStakeBTCSuccess, onError)

const onDepositBTCSuccess = useCallback(() => {
dispatch(setStatus(PROCESS_STATUSES.LOADING))

logPromiseFailure(handleStake())
}, [dispatch, handleStake])
const onDepositBTCSuccess = useCallback(
(transactionHash: string) => {
dispatch(setTxHash(transactionHash))
logPromiseFailure(handleStake())
},
[dispatch, handleStake],
)

const onDepositBTCError = useCallback(
(error: unknown) => {
if (eip1193.didUserRejectRequest(error)) {
handlePause()
} else {
onError(error)
onError()
}
},
[onError, handlePause],
)

const { sendBitcoinTransaction, transactionHash, inProgress } =
useDepositBTCTransaction(onDepositBTCSuccess, onDepositBTCError)

useEffect(() => {
if (transactionHash) {
dispatch(setTxHash(transactionHash))
}
}, [dispatch, transactionHash])
const { sendBitcoinTransaction, status } = useDepositBTCTransaction(
onDepositBTCSuccess,
onDepositBTCError,
)

const handledDepositBTC = useCallback(async () => {
if (!tokenAmount?.amount || !btcAddress || !depositReceipt) return
const status = await verifyDepositAddress(depositReceipt, btcAddress)

if (status === "valid") {
await sendBitcoinTransaction(btcAddress, tokenAmount?.amount)
const verificationStatus = await verifyDepositAddress(
depositReceipt,
btcAddress,
)

if (verificationStatus === "valid") {
sendBitcoinTransaction({
recipient: btcAddress,
amount: tokenAmount?.amount,
})
} else {
onError()
}
}, [
tokenAmount?.amount,
btcAddress,
depositReceipt,
onError,
verifyDepositAddress,
sendBitcoinTransaction,
tokenAmount?.amount,
onError,
])

const handledDepositBTCWrapper = useCallback(() => {
Expand All @@ -93,7 +94,7 @@ export default function DepositBTCModal() {

useTimeout(handledDepositBTCWrapper, ONE_SEC_IN_MILLISECONDS)

if (inProgress || transactionHash)
if (status === "pending" || status === "success")
return <WalletInteractionModal step="awaiting-transaction" />

return <WalletInteractionModal step="opening-wallet" />
Expand Down
79 changes: 30 additions & 49 deletions dapp/src/hooks/useDepositBTCTransaction.ts
Original file line number Diff line number Diff line change
@@ -1,70 +1,51 @@
import { useCallback, useEffect, useState } from "react"
import { OnErrorCallback, OnSuccessCallback } from "#/types"
import { useMutation } from "@tanstack/react-query"
import { useWallet } from "./useWallet"
import { useConnector } from "./orangeKit/useConnector"

type SendBitcoinTransactionParams = Parameters<
(recipient: string, amount: bigint) => void
>

type UseDepositBTCTransactionReturn = {
inProgress: boolean
transactionHash?: string
sendBitcoinTransaction: (
...params: SendBitcoinTransactionParams
) => Promise<void>
}

export function useDepositBTCTransaction(
onSuccess?: OnSuccessCallback,
onSuccess?: OnSuccessCallback<string>,
onError?: OnErrorCallback,
): UseDepositBTCTransactionReturn {
) {
const connector = useConnector()
const { address } = useWallet()

const [transactionHash, setTransactionHash] = useState<string | undefined>(
undefined,
)
const [inProgress, setInProgress] = useState<boolean>(false)

useEffect(() => {
if (transactionHash && onSuccess) {
onSuccess()
}
}, [onSuccess, transactionHash])

const sendBitcoinTransaction = useCallback(
async (recipient: string, amount: bigint) => {
const {
mutate: sendBitcoinTransaction,
status,
data,
} = useMutation({
mutationKey: ["send-bitcoin"],
mutationFn: async ({
recipient,
amount,
}: {
recipient: string
amount: bigint
}) => {
if (!address) {
throw new Error("Bitcoin account was not connected.")
}

if (!connector) {
throw new Error("Connector was not defined.")
}
// @ts-expect-error adjust types to handle bitcoin wallet wrappers
const client = await connector.getClient()

try {
// @ts-expect-error adjust types to handle bitcoin wallet wrappers
const client = await connector.getClient()

const satoshis = Number(amount)
const satoshis = Number(amount)

setInProgress(true)
// @ts-expect-error adjust types to handle bitcoin wallet wrappers
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment
const txhash: string = await client.sendBitcoin(recipient, satoshis)
setTransactionHash(txhash)
} catch (error) {
if (onError) {
onError(error)
}
console.error(error)
} finally {
setInProgress(false)
}
// @ts-expect-error adjust types to handle bitcoin wallet wrappers
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment
const txhash: string = await client.sendBitcoin(recipient, satoshis)
return txhash
},
onSuccess: (responseData) => onSuccess?.(responseData),
onError: (error) => {
onError?.(error)
console.error(error)
},
[address, connector, onError],
)
})

return { sendBitcoinTransaction, transactionHash, inProgress }
return { sendBitcoinTransaction, status, data }
}
4 changes: 2 additions & 2 deletions dapp/src/hooks/useExecuteFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ export function useExecuteFunction<
return useCallback(
async (...args: Parameters<typeof fn>) => {
try {
await fn(...args)
const response = await fn(...args)

if (onSuccess) {
onSuccess()
onSuccess(response)
}
} catch (error) {
if (onError) {
Expand Down
2 changes: 1 addition & 1 deletion dapp/src/types/callback.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export type OnSuccessCallback = () => void
export type OnSuccessCallback<DataType = unknown> = (data: DataType) => void

export type OnErrorCallback<ErrorType = unknown> = (error: ErrorType) => void

0 comments on commit 1717ea5

Please sign in to comment.