Skip to content

Instantly share code, notes, and snippets.

@mhw32
Last active June 15, 2023 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhw32/da9278f64fb603b248c85aade706df56 to your computer and use it in GitHub Desktop.
Save mhw32/da9278f64fb603b248c85aade706df56 to your computer and use it in GitHub Desktop.
Example of using the DappNotificationContext from Web3Analytic's SDK
import React, { FC, useState, useContext } from 'react';
import { ethers } from 'ethers';
import { DappNotificationContext } from '@web3analytic/notifications-react';
// To ignore typing issues
declare let window: any;
const ConnectWallet: FC = () => {
// State variable to store the connected wallet address
const [address, setAddress] = useState<string>('');
// State variable to check if the user is connected to MetaMask
const [isConnected, setIsConnected] = useState<boolean>(false);
const { onConnectAddress } = useContext(DappNotificationContext);
/**
* Example for adding Web3Analytic callback when user connects to MetaMask.
*/
async function connectToMetamask() {
if (window.ethereum) {
const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send('eth_requestAccounts', []);
const signer = provider.getSigner();
try {
var address: string = await signer.getAddress();
address = address.toLowerCase().trim();
setAddress(address);
setIsConnected(true);
onConnectAddress(address);
} catch (err: any) {
setIsConnected(false);
}
}
}
return (
<div
style={{
padding: '5rem',
margin: 'auto',
textAlign: 'center',
}}
>
<h2>In-Dapp Notifications Demo</h2>
<div
style={{
padding: '2rem',
}}
>
<button
onClick={() => connectToMetamask()}
style={{
border: '2px solid black',
borderColor: '#2196F3',
borderRadius: '8px',
color: 'dodgerblue',
padding: '14px 28px',
fontSize: '16px',
cursor: 'pointer',
}}
>
{isConnected ? `Connected to ${address.substring(0, 10)}...` : 'Connect MetaMask'}
</button>
</div>
</div>
);
}
export default ConnectWallet;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment