Skip to content

Instantly share code, notes, and snippets.

@rpuntaie
Created June 17, 2022 19:56
Show Gist options
  • Save rpuntaie/d95000607a84c72804a898ba325d1aa0 to your computer and use it in GitHub Desktop.
Save rpuntaie/d95000607a84c72804a898ba325d1aa0 to your computer and use it in GitHub Desktop.
setup react with ethers (web3 alternative) using hardhat
#!/usr/bin/env bash
npx create-react-app reactweb3
cd reactweb3
yarn add ethers hardhat @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers
mkdir contract
cd contract
npx hardhat # simple project
npx hardhat compile
npx hardhat test
npx hardhat node # keep this running
#####################################
cd reactweb3/contract
mv scripts/sample-script.js scripts/deploy.js
XX=$(npx hardhat run scripts/deploy.js --network localhost | cut -d ":" -f 2 | cut -d " " -f 2)
cd ../src
ln -s ../contract/artifacts
cd ..
cat > src/App.js << EOF
import React, { useState, useRef, useEffect } from "react";
import Greeter from "./artifacts/contracts/Greeter.sol/Greeter.json";
import { ethers } from "ethers";
export default function App() {
var contract = useRef();
var [greet, setGreet] = useState();
async function connectWallet() {
try {
const { ethereum } = window;
if (!ethereum) {
alert("Please install MetaMask!");
return;
}
const accounts = await ethereum.request({
method: "eth_requestAccounts",
});
console.log("Connected", accounts[0]);
fetchGreetings();
} catch (error) {
console.log(error);
}
};
const fetchGreetings = async () => {
// todo: change this contract address
let contractAddress = "${XX}";
const { ethereum } = window;
if (!ethereum) {
alert("Please install MetaMask!");
return;
}
const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();
contract.current = new ethers.Contract(
contractAddress,
Greeter.abi,
signer
);
setGreet(await contract.current.greet())
console.log(greet);
};
useEffect(() => {
connectWallet();
}, []);
function ChangeGreeting() {
const guys = Math.floor(Math.random() * 9);
const newGreet = \`Hi you \${guys} guys!\`;
async function _changegreeting() {
const tx = await contract.current.setGreeting(newGreet);
await tx.wait();
setGreet(await contract.current.greet())
}
_changegreeting();
}
return <>
<div>{greet}</div>
<div><button onClick={ChangeGreeting}>Change</button></div>
</>;
}
EOF
npm start
# Metamask:
# - enable test networks in settings
# - select the local network on port 8545
# - import account using private key of first test account
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment