1
0
Fork 0
blog/src/features/Web3/hooks/useSend/send.ts

32 lines
988 B
TypeScript
Raw Normal View History

2024-03-13 02:20:29 +01:00
import { sendTransaction, writeContract } from 'wagmi/actions'
2023-11-05 21:11:13 +01:00
import type { GetToken } from '../useFetchTokens'
2024-03-13 02:20:29 +01:00
import { parseEther, parseUnits } from 'viem'
import { abiErc20Transfer } from './abiErc20Transfer'
import type { UseConfigReturnType } from 'wagmi'
2023-11-02 04:22:04 +01:00
export async function send(
2024-03-13 02:20:29 +01:00
config: UseConfigReturnType,
2023-11-02 04:22:04 +01:00
selectedToken: GetToken | undefined,
2024-03-13 02:20:29 +01:00
amount: string | undefined,
2024-03-13 11:37:05 +01:00
to: `0x${string}` | null | undefined,
2024-03-13 02:20:29 +01:00
chainId: number | undefined
2023-11-02 04:22:04 +01:00
) {
2024-03-13 02:20:29 +01:00
if (!selectedToken?.decimals || !amount || !to) return
2023-11-02 04:22:04 +01:00
2024-03-14 14:18:21 +01:00
const isNative = selectedToken.address.startsWith('0x0')
2024-03-13 02:20:29 +01:00
const requestNative = { chainId, to, value: parseEther(amount) }
const requestErc20 = {
chainId,
address: selectedToken.address,
abi: abiErc20Transfer,
functionName: 'transfer',
args: [to, parseUnits(amount, selectedToken.decimals)]
}
const result = isNative
? await sendTransaction(config, requestNative)
: await writeContract(config, requestErc20)
2023-11-02 04:22:04 +01:00
return result
}