dgf-prototype/client/src/App.jsx

62 lines
1.5 KiB
JavaScript

import { useState } from 'react';
import { Web3 } from 'web3';
import './App.css';
function App() {
// react state to store and show the connected account
const [connectedAccounts, setConnectedAccounts] = useState([]);
async function connectMetamask() {
// instantiate Web3 with the injected provider
const web3 = new Web3(window.ethereum);
// request user to connect accounts (Metamask will prompt)
await window.ethereum.request({ method: 'eth_requestAccounts' });
// get the connected accounts
const accounts = await web3.eth.getAccounts();
// show the first connected account in the react page
setConnectedAccounts(accounts);
}
async function disconnectMetamask() {
await window.ethereum.request({
method: 'wallet_revokePermissions',
params: [
{
eth_accounts: {},
},
],
});
setConnectedAccounts([]);
}
return (
<>
{!window.ethereum && (
<>
Please download Metamask
</>
)}
{window.ethereum && (
<>
{/* Button to trigger Metamask connection */}
<button type="button" onClick={() => connectMetamask()}>Connect to Metamask</button>
{/* Button to disconnect Metamask */}
<button type="button" onClick={() => disconnectMetamask()}>Disconnect from Metamask</button>
{/* Display the connected account */}
{connectedAccounts.map(
(connectedAccount) => <h2 key={connectedAccount}>{connectedAccount}</h2>,
)}
</>
)}
</>
);
}
export default App;