2024-02-21 18:01:41 -06:00
|
|
|
import { useState } from 'react';
|
2024-03-07 10:58:55 -06:00
|
|
|
import { Web3 } from 'web3';
|
2024-02-21 18:01:41 -06:00
|
|
|
import './App.css';
|
|
|
|
|
|
|
|
function App() {
|
2024-03-07 10:58:55 -06:00
|
|
|
// 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([]);
|
|
|
|
}
|
|
|
|
|
2024-02-21 18:01:41 -06:00
|
|
|
return (
|
|
|
|
<>
|
2024-03-07 10:58:55 -06:00
|
|
|
{!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>,
|
2024-02-21 18:01:41 -06:00
|
|
|
)}
|
2024-03-07 10:58:55 -06:00
|
|
|
</>
|
|
|
|
)}
|
2024-02-21 18:01:41 -06:00
|
|
|
</>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export default App;
|