1
0
mirror of https://github.com/kremalicious/blog.git synced 2024-06-25 18:56:25 +02:00
blog/src/components/molecules/Web3Donation/index.tsx

76 lines
1.9 KiB
TypeScript
Raw Normal View History

import React, { ReactElement, useState } from 'react'
2023-08-17 13:43:32 +02:00
import { parseEther } from 'viem'
2023-01-29 22:58:19 +01:00
import { ConnectButton } from '@rainbow-me/rainbowkit'
2022-09-17 15:58:59 +02:00
import { useDebounce } from 'use-debounce'
2023-01-29 22:58:19 +01:00
import { usePrepareSendTransaction, useSendTransaction } from 'wagmi'
2019-11-22 21:26:50 +01:00
import Alert, { getTransactionMessage } from './Alert'
2023-01-29 22:58:19 +01:00
import InputGroup from './InputGroup'
import * as styles from './index.module.css'
2018-10-09 23:48:25 +02:00
2020-05-22 14:38:19 +02:00
export default function Web3Donation({
address
}: {
address: string
}): ReactElement {
2022-09-17 15:58:59 +02:00
const [amount, setAmount] = useState('0.01')
const [debouncedAmount] = useDebounce(amount, 500)
const { config } = usePrepareSendTransaction({
2023-08-17 13:43:32 +02:00
to: address,
value: debouncedAmount ? parseEther(debouncedAmount) : undefined
2022-09-17 15:58:59 +02:00
})
2023-08-17 13:43:32 +02:00
const { sendTransactionAsync, isError, isSuccess } =
useSendTransaction(config)
2021-03-23 21:38:06 +01:00
const [message, setMessage] = useState<{ status: string; text: string }>()
const [transactionHash, setTransactionHash] = useState<string>()
2019-11-21 21:32:55 +01:00
2022-09-17 15:58:59 +02:00
async function handleSendTransaction() {
2019-11-21 21:32:55 +01:00
setMessage({
status: 'loading',
2019-11-22 21:26:50 +01:00
text: getTransactionMessage().waitingForUser
2019-11-21 21:32:55 +01:00
})
2018-10-09 23:48:25 +02:00
2020-01-13 22:07:48 +01:00
try {
2023-08-17 13:43:32 +02:00
const result = await sendTransactionAsync()
if (isError) {
throw new Error(null)
}
setTransactionHash(result?.hash)
2020-01-13 22:07:48 +01:00
setMessage({
status: 'loading',
text: getTransactionMessage().waitingConfirmation
})
2018-10-30 18:08:07 +01:00
2023-08-17 13:43:32 +02:00
if (isSuccess) {
setMessage({
status: 'success',
text: getTransactionMessage().success
})
}
2020-01-13 22:07:48 +01:00
} catch (error) {
2021-03-23 21:38:06 +01:00
setMessage(null)
2020-01-13 22:07:48 +01:00
}
2018-10-09 23:48:25 +02:00
}
2019-11-21 21:32:55 +01:00
return (
2022-09-17 15:58:59 +02:00
<form
className={styles.web3}
2022-09-17 15:58:59 +02:00
onSubmit={(e) => {
e.preventDefault()
handleSendTransaction()
}}
>
<ConnectButton chainStatus="icon" showBalance={false} />
2021-03-23 01:09:32 +01:00
{message ? (
<Alert message={message} transactionHash={transactionHash} />
2019-11-21 21:32:55 +01:00
) : (
2022-09-17 15:58:59 +02:00
<InputGroup amount={amount} setAmount={setAmount} />
2019-11-21 21:32:55 +01:00
)}
2022-09-17 15:58:59 +02:00
</form>
2019-11-21 21:32:55 +01:00
)
2018-10-09 23:48:25 +02:00
}