1
0
Fork 0
blog/src/components/molecules/Web3Donation/Account.tsx

50 lines
1.4 KiB
TypeScript
Raw Normal View History

2020-05-22 15:51:08 +02:00
import React, { ReactElement, useState, useEffect } from 'react'
import { toDataUrl } from 'ethereum-blockies'
2019-11-22 21:26:50 +01:00
import { formatEther } from '@ethersproject/units'
2021-03-23 21:38:06 +01:00
import useWeb3, { connectors } from '../../../hooks/useWeb3'
2021-03-14 01:34:04 +01:00
import {
accountWrap,
blockies as styleBlockies,
2021-03-23 01:09:32 +01:00
balance,
link
2021-03-14 01:34:04 +01:00
} from './Account.module.css'
2018-10-14 21:48:38 +02:00
2020-05-22 15:51:08 +02:00
export default function Account(): ReactElement {
2021-03-23 01:09:32 +01:00
const { library, account, activate } = useWeb3()
2021-03-23 21:38:06 +01:00
const [ethBalance, setEthBalance] = useState('0')
const blockies = account && toDataUrl(account)
2018-10-14 21:48:38 +02:00
2020-05-22 15:51:08 +02:00
useEffect(() => {
if (!library || !account) return
async function init() {
const balance = await library.getBalance(account)
2021-03-23 21:38:06 +01:00
setEthBalance(balance.toString())
2020-05-22 15:51:08 +02:00
}
init()
}, [library, account])
2019-11-22 21:26:50 +01:00
const accountDisplay =
account &&
`${account.substring(0, 8)}...${account.substring(account.length - 4)}`
const balanceDisplay =
ethBalance && `Ξ${parseFloat(formatEther(ethBalance)).toPrecision(4)}`
2021-03-23 21:38:06 +01:00
return account ? (
2021-03-14 01:34:04 +01:00
<div className={accountWrap} title={account}>
<span>
<img className={styleBlockies} src={blockies} alt="Blockies" />
2019-11-22 21:26:50 +01:00
{accountDisplay}
</span>
2021-03-14 01:34:04 +01:00
<span className={balance}>{balanceDisplay}</span>
2019-11-22 21:26:50 +01:00
</div>
2021-03-23 21:38:06 +01:00
) : (
<button
className={`link ${link}`}
onClick={() => activate(connectors.MetaMask)}
>
Connect MetaMask
</button>
2019-11-22 21:26:50 +01:00
)
}