-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathweb3p.js
More file actions
88 lines (78 loc) · 2.37 KB
/
web3p.js
File metadata and controls
88 lines (78 loc) · 2.37 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { useContext } from "react";
import Web3 from "web3"; // Web3
import { useState, useEffect } from "react"; // State management
import { createContainer } from "unstated-next"; // Unstated-next containerization
import { EthereumProvider } from "@walletconnect/ethereum-provider"; // EthereumProvider (WalletConnect3Modal)
import { RPCWeb3Provider } from "@compound-finance/comet-extension";
import { useRPC } from "../components/hooks/useRPC";
import { Embedded } from "containers"; // Embedded
function useWeb3() {
const embedded = useContext(Embedded);
const rpc = useRPC();
const [web3, setWeb3] = useState(null); // Web3 provider
const [address, setAddress] = useState(null); // ETH address
/**
* Authenticate, save web3 provider, and save eth address
*/
const authenticate = async () => {
let provider;
// Toggle modal
if (!embedded) {
// EthereumProvider provider options (triggers WalletConnectModal)
provider = await EthereumProvider.init({
projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_ID,
chains: [1], // mainnet
showQrModal: true, // prompts modal using @walletconnect/modal
methods: ["eth_signTypedData_v4"],
});
await provider.enable();
} else {
provider = new RPCWeb3Provider(rpc.sendRPC);
}
// Generate web3 object and save
const web3 = new Web3(provider);
setWeb3(web3);
// Collect address
const accounts = await web3.eth.getAccounts();
const address = accounts[0];
setAddress(address);
return;
};
/**
* Unauthenticate and clear cache
*/
const unauthenticate = async () => {
// Check if logged in
if (web3 && web3.currentProvider && web3.currentProvider.close) {
// Close provider
await web3.currentProvider.close();
}
// Nullify web3 provider and address
setAddress(null);
setWeb3(null);
};
/**
* Checks validity of Ethereum address
* @param {String} address to check
* @returns {Boolean} true if address is valid
*/
const isValidAddress = (address) => {
return web3.utils.isAddress(address);
};
// On mount
useEffect(() => {
if (embedded) {
authenticate();
}
}, []);
return {
web3,
address,
authenticate,
unauthenticate,
isValidAddress,
};
}
// Create unstated-next container
const web3p = createContainer(useWeb3);
export default web3p;