1
0
Fork 0
blog/src/features/Web3/hooks/useSend/useSend.tsx

60 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-03-13 02:20:29 +01:00
import { $txHash, $selectedToken, $amount } from '@features/Web3/stores'
import { useStore } from '@nanostores/react'
2023-11-03 21:56:08 +01:00
import { useState } from 'react'
import { send } from './send'
2023-11-05 23:07:34 +01:00
import { isUnhelpfulErrorMessage } from './isUnhelpfulErrorMessage'
2024-03-14 14:18:21 +01:00
import { useAccount, useConfig, useEnsAddress, useSwitchChain } from 'wagmi'
2024-03-13 11:37:05 +01:00
import siteConfig from '@config/blog.config'
2024-03-13 02:20:29 +01:00
export function useSend() {
const selectedToken = useStore($selectedToken)
2024-03-13 02:20:29 +01:00
const amount = useStore($amount)
const config = useConfig()
2024-03-13 11:37:05 +01:00
const { chainId } = useAccount()
const { ens } = siteConfig.author.ether
const { data: to } = useEnsAddress({ name: ens, chainId: 1 })
2024-03-14 14:18:21 +01:00
const { switchChain } = useSwitchChain()
const [isLoading, setIsLoading] = useState(false)
const [isError, setIsError] = useState(false)
const [error, setError] = useState<string | undefined>()
2023-11-03 21:56:08 +01:00
async function handleSend() {
2024-03-14 14:18:21 +01:00
if (!selectedToken || !amount || !to) return
// switch chains first
if (chainId !== selectedToken.chainId) {
switchChain({ chainId: selectedToken.chainId })
}
try {
setIsError(false)
setError(undefined)
setIsLoading(true)
2024-03-14 14:18:21 +01:00
const hash = await send(
config,
selectedToken,
amount,
to,
selectedToken.chainId
)
2024-03-13 02:20:29 +01:00
if (hash) $txHash.set(hash)
} catch (error: unknown) {
2023-11-05 16:54:17 +01:00
const errorMessage = (error as Error).message
console.error(errorMessage)
2023-11-03 23:43:06 +01:00
// only expose useful errors in UI
2023-11-05 23:07:34 +01:00
if (isUnhelpfulErrorMessage(errorMessage)) {
2023-11-03 23:43:06 +01:00
setError(undefined)
} else {
setError((error as Error).message)
}
setIsError(true)
} finally {
setIsLoading(false)
}
}
return { handleSend, isLoading, error, isError }
}