forked from adrianmcli/web3-vs-ethers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useCounterContract.js
44 lines (36 loc) · 1.27 KB
/
useCounterContract.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { useState, useRef, useEffect } from "react";
import { ethers } from "ethers";
import artifact from "../smart-contracts/build/contracts/Counter.json";
export default function useCounterContract() {
const contract = useRef();
const [count, setCount] = useState();
// function to get current count and update UI
const updateCount = async () => {
const newCount = await contract.current.getCount();
setCount(newCount.toString());
};
// function to invoke a mutating method on our contract
const increment = async () => {
const tx = await contract.current.increment();
await tx.wait(); // wait for mining
updateCount(); // update count on UI
};
useEffect(() => {
// this is only run once on component mounting
const setup = async () => {
const provider = new ethers.providers.JsonRpcProvider();
const network = await provider.getNetwork();
const contractAddress = artifact.networks[network.chainId].address;
// instantiate contract instance and assign to component ref variable
contract.current = new ethers.Contract(
contractAddress,
artifact.abi,
provider.getSigner(),
);
// update count on UI
updateCount();
};
setup();
}, []);
return { count, increment };
}