Skip to content

Instantly share code, notes, and snippets.

@mhw32
Created 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/b8f6507b0913ea98f3f36a75ab97caaf to your computer and use it in GitHub Desktop.
Save mhw32/b8f6507b0913ea98f3f36a75ab97caaf to your computer and use it in GitHub Desktop.
Example of using the DappNotification and registerImpression from Web3Analytic's SDK
import React, { FC, useState } from 'react';
import { ethers } from 'ethers';
import { registerImpression, PromptType, RegisterImpressionResponseType } from '@web3analytic/notifications-sdk';
import { DappNotification } 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);
// State variable to store the ID of the impression
const [impressionId, setImpressionId] = useState<number | null>(null);
// State variable to store the prompt
const [prompt, setPrompt] = useState<PromptType | null>(null);
// Demo relies on an API key. Please set in `.env` file.
const apiKey: string = process.env.REACT_APP_WEB3ANALYTIC_API_KEY || '';
/**
* 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();
setAddress(address.toLowerCase().trim());
setIsConnected(true);
registerImpression(apiKey, address, 0)
.then((res: RegisterImpressionResponseType) => {
console.log('App `registerImpression` response:', res);
if (res.impressionId) {
setImpressionId(res.impressionId);
}
if (res.prompt) {
setPrompt(res.prompt);
}
})
.catch((err: any) => {
console.log('App `registerImpression` error:', err);
});
} 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>
<DappNotification apiKey={apiKey} impressionId={impressionId} prompt={prompt} />
</div>
</div>
);
}
export default ConnectWallet;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment