Created
March 21, 2022 05:53
-
-
Save jarrodlilkendey/51927f8c942a908c9b438f5554531834 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Component } from 'react'; | |
| import { ethers } from "ethers"; | |
| class Metamask extends Component { | |
| constructor(props) { | |
| super(props); | |
| this.state = { | |
| }; | |
| } | |
| async connectToMetamask() { | |
| const provider = new ethers.providers.Web3Provider(window.ethereum) | |
| const accounts = await provider.send("eth_requestAccounts", []); | |
| const balance = await provider.getBalance(accounts[0]); | |
| const balanceInEther = ethers.utils.formatEther(balance); | |
| const block = await provider.getBlockNumber(); | |
| provider.on("block", (block) => { | |
| this.setState({ block }) | |
| }) | |
| this.setState({ selectedAddress: accounts[0], balance: balanceInEther, block }) | |
| } | |
| renderMetamask() { | |
| if (!this.state.selectedAddress) { | |
| return ( | |
| <button onClick={() => this.connectToMetamask()}>Connect to Metamask</button> | |
| ) | |
| } else { | |
| return ( | |
| <div> | |
| <p>Welcome {this.state.selectedAddress}</p> | |
| <p>Your ETH Balance is: {this.state.balance}</p> | |
| <p>Current ETH Block is: {this.state.block}</p> | |
| </div> | |
| ); | |
| } | |
| } | |
| render() { | |
| return( | |
| <div> | |
| {this.renderMetamask()} | |
| </div> | |
| ) | |
| } | |
| } | |
| export default Metamask; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment