Created
February 7, 2022 16:02
-
-
Save BetterProgramming/c470735cda01332967a65e1dc6d78eb2 to your computer and use it in GitHub Desktop.
This file contains 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 styles from "../styles/Home.module.css"; | |
import Web3Modal from "web3modal"; | |
import { useState, useEffect } from "react"; | |
import { ethers } from "ethers"; | |
import WalletConnectProvider from "@walletconnect/web3-provider"; | |
import { abi } from "../constants/abi"; | |
let web3Modal; | |
const providerOptions = { | |
walletconnect: { | |
package: WalletConnectProvider, // required | |
options: { | |
rpc: { 42: process.env.NEXT_PUBLIC_RPC_URL }, // required | |
}, | |
}, | |
}; | |
if (typeof window !== "undefined") { | |
web3Modal = new Web3Modal({ | |
cacheProvider: false, | |
providerOptions, // required | |
}); | |
} | |
export default function Home() { | |
const [isConnected, setIsConnected] = useState(false); | |
const [hasMetamask, setHasMetamask] = useState(false); | |
const [signer, setSigner] = useState(undefined); | |
useEffect(() => { | |
if (typeof window.ethereum !== "undefined") { | |
setHasMetamask(true); | |
} | |
}); | |
async function connect() { | |
if (typeof window.ethereum !== "undefined") { | |
try { | |
const web3ModalProvider = await web3Modal.connect(); | |
setIsConnected(true); | |
const provider = new ethers.providers.Web3Provider(web3ModalProvider); | |
setSigner(provider.getSigner()); | |
} catch (e) { | |
console.log(e); | |
} | |
} else { | |
setIsConnected(false); | |
} | |
} | |
async function execute() { | |
if (typeof window.ethereum !== "undefined") { | |
const contractAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; | |
const contract = new ethers.Contract(contractAddress, abi, signer); | |
try { | |
await contract.store(42); | |
} catch (error) { | |
console.log(error); | |
} | |
} else { | |
console.log("Please install MetaMask"); | |
} | |
} | |
return ( | |
<div> | |
{hasMetamask ? ( | |
isConnected ? ( | |
"Connected! " | |
) : ( | |
<button onClick={() => connect()}>Connect</button> | |
) | |
) : ( | |
"Please install metamask" | |
)} | |
{isConnected ? <button onClick={() => execute()}>Execute</button> : ""} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment