-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathweb3.js
210 lines (197 loc) · 6.24 KB
/
web3.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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import {
default as WalletConnect,
default as WalletConnectProvider,
} from '@walletconnect/web3-provider';
import { IS_DEFAULT_PROVIDER_DISABLED } from 'constants/features';
import { ethers } from 'ethers';
import { createContext, useEffect, useRef, useState } from 'react';
import {
handleCatchErrorEvent,
handleConnectAccountEvent,
} from 'utils/analytics';
import Web3Modal from 'web3modal';
export const Web3Context = createContext();
export function Web3Provider({ children }) {
const web3ModalRef = useRef();
const [isReady, setIsReady] = useState(false);
const [instance, setInstance] = useState(null);
const [provider, setProvider] = useState(null);
const [defaultProvider, setDefaultProvider] = useState(null);
const [account, setAccount] = useState(null);
const [networkChainId, setNetworkChainId] = useState(null);
const [isNetworkChainIdCorrect, setIsNetworkChainCorrect] = useState(null);
async function initContext() {
try {
// Show web3 modal or autoconnects
const instance = await web3ModalRef.current.connect();
// Define data
setIsReady(false);
const provider = new ethers.providers.Web3Provider(instance, 'any');
const accounts = await provider.listAccounts();
const network = await provider.getNetwork();
const networkChainId = network?.chainId;
// Add listeners if the user has changed the chain or account
instance.addListener('chainChanged', (chainId) =>
setNetworkChainId(chainId),
);
instance.addListener('accountsChanged', (accounts) => {
if (accounts && accounts.length > 0) {
setAccount(accounts[0]);
}
});
// Update states
setInstance(instance);
setProvider(provider);
if (accounts && accounts.length > 0) {
setAccount(accounts[0]);
}
setNetworkChainId(networkChainId);
} catch (error) {
console.error(error);
handleCatchErrorEvent(error, { type: 'web3' });
} finally {
setIsReady(true);
}
}
async function clearContext() {
try {
setIsReady(false);
// Disconnect provider
if (instance instanceof WalletConnectProvider) {
instance.disconnect();
}
// Remove listeners
instance.removeAllListeners('chainChanged');
instance.removeAllListeners('accountsChanged');
// Clear providers
web3ModalRef.current.clearCachedProvider();
localStorage.removeItem('walletconnect');
// Clear states
setInstance(null);
setProvider(null);
setAccount(null);
setNetworkChainId(null);
setIsNetworkChainCorrect(null);
} catch (error) {
console.error(error);
handleCatchErrorEvent(error, { type: 'clear context' });
} finally {
setIsReady(true);
}
}
async function connectWallet() {
initContext();
}
async function disconnectWallet() {
clearContext();
}
async function switchNetwork() {
try {
await instance.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: process.env.NEXT_PUBLIC_NETWORK_CHAIN_ID_HEX }],
});
} catch (error) {
console.error(error);
handleCatchErrorEvent(error, { type: 'change network' });
if (
error?.code === 4902 ||
error?.message?.toLowerCase()?.includes('unrecognized chain id')
) {
addNetwork();
}
}
}
async function addNetwork() {
try {
await instance.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: process.env.NEXT_PUBLIC_NETWORK_CHAIN_ID_HEX,
rpcUrls: [process.env.NEXT_PUBLIC_NETWORK_RPC_URL],
chainName: process.env.NEXT_PUBLIC_NETWORK_NAME,
nativeCurrency: {
name: process.env.NEXT_PUBLIC_NETWORK_CURRENCY_NAME,
symbol: process.env.NEXT_PUBLIC_NETWORK_CURRENCY_SYMBOL,
decimals: parseInt(
process.env.NEXT_PUBLIC_NETWORK_CURRENCY_DECIMALS,
),
},
blockExplorerUrls: [
process.env.NEXT_PUBLIC_NETWORK_BLOCK_EXPLORER_URL,
],
},
],
});
} catch (error) {
console.error(error);
handleCatchErrorEvent(error, { type: 'add chain' });
}
}
useEffect(() => {
// Init default provider
// TODO: Can we use public RPC instead of Infura?
if (!defaultProvider && !IS_DEFAULT_PROVIDER_DISABLED) {
const infuraProvider = new ethers.providers.InfuraWebSocketProvider(
process.env.NEXT_PUBLIC_INFURA_NETWORK,
process.env.NEXT_PUBLIC_INFURA_KEY,
);
setDefaultProvider(infuraProvider);
}
// Config web3 modal and try autoconnect
if (!web3ModalRef.current) {
// Config Web3Modal
const providerOptions = {
walletconnect: {
package: WalletConnect,
options: {
rpc: {
80001: 'https://rpc-mumbai.maticvigil.com', // TODO: Move to .env
},
},
},
};
const web3Modal = new Web3Modal({
cacheProvider: true,
providerOptions,
});
web3ModalRef.current = web3Modal;
// Connect wallet if cached provider exists
if (web3ModalRef.current.cachedProvider) {
initContext();
} else {
setIsReady(true);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const isChainIdCorrect =
networkChainId?.toString() === process.env.NEXT_PUBLIC_NETWORK_CHAIN_ID;
const isChainIdHexCorrect =
networkChainId?.toString() ===
process.env.NEXT_PUBLIC_NETWORK_CHAIN_ID_HEX;
setIsNetworkChainCorrect(isChainIdCorrect || isChainIdHexCorrect);
}, [networkChainId]);
useEffect(() => {
if (account) {
handleConnectAccountEvent(account);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [account]);
const value = {
state: {
isReady: isReady,
defaultProvider: defaultProvider,
provider: provider,
account: account,
networkChainId: networkChainId,
isNetworkChainIdCorrect: isNetworkChainIdCorrect,
},
connectWallet,
disconnectWallet,
switchNetwork,
};
return <Web3Context.Provider value={value}>{children}</Web3Context.Provider>;
}