1
0
Fork 0
blog/src/features/Web3/hooks/usePrepareSend/prepare.ts

43 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-11-02 22:47:14 +01:00
import { parseEther, parseUnits } from 'viem'
import {
prepareSendTransaction,
prepareWriteContract,
type SendTransactionArgs,
type WriteContractPreparedArgs
} from 'wagmi/actions'
import { abiErc20Transfer } from './abiErc20Transfer'
2023-11-05 17:40:44 +01:00
import type { GetToken } from '../useFetchTokens'
2023-11-02 22:47:14 +01:00
export async function prepare(
2023-11-02 22:47:14 +01:00
selectedToken: GetToken | undefined,
amount: string | undefined,
to: `0x${string}` | null | undefined,
chainId: number | undefined
) {
2023-11-03 23:43:06 +01:00
if (
!chainId ||
!to ||
!amount ||
!selectedToken ||
!selectedToken?.address ||
!selectedToken?.decimals
)
2023-11-02 22:47:14 +01:00
return
const isNative = selectedToken.address === '0x0'
const requestNative = { chainId, to, value: parseEther(amount) }
const requestErc20 = {
chainId,
2023-11-02 22:47:14 +01:00
address: selectedToken.address,
abi: abiErc20Transfer,
functionName: 'transfer',
2023-11-03 23:43:06 +01:00
args: [to, parseUnits(amount, selectedToken.decimals)]
2023-11-02 22:47:14 +01:00
}
const config = isNative
? ((await prepareSendTransaction(requestNative)) as SendTransactionArgs)
: ((await prepareWriteContract(requestErc20)) as WriteContractPreparedArgs)
2023-11-02 22:47:14 +01:00
return config
}