Skip to content

Instantly share code, notes, and snippets.

@BetterProgramming
Created February 7, 2022 16:01
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 BetterProgramming/273c851ec34a50ec6a195e65452ac029 to your computer and use it in GitHub Desktop.
Save BetterProgramming/273c851ec34a50ec6a195e65452ac029 to your computer and use it in GitHub Desktop.
import styles from "../styles/Home.module.css";
import { ethers } from "ethers";
import { useEffect, useState } from "react";
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 {
await ethereum.request({ method: "eth_requestAccounts" });
setIsConnected(true);
const provider = new ethers.providers.Web3Provider(window.ethereum);
setSigner(provider.getSigner());
} catch (e) {
console.log(e);
}
} else {
setIsConnected(false);
}
}
async function execute() {
if (typeof window.ethereum !== "undefined") {
const contractAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3";
const abi = [
{
inputs: [
{
internalType: "string",
name: "_name",
type: "string",
},
{
internalType: "uint256",
name: "_favoriteNumber",
type: "uint256",
},
],
name: "addPerson",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "string",
name: "",
type: "string",
},
],
name: "nameToFavoriteNumber",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
name: "people",
outputs: [
{
internalType: "uint256",
name: "favoriteNumber",
type: "uint256",
},
{
internalType: "string",
name: "name",
type: "string",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "retrieve",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "_favoriteNumber",
type: "uint256",
},
],
name: "store",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
];
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