This repository has been archived by the owner on Sep 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathauthEthereum.js
89 lines (81 loc) · 2.52 KB
/
authEthereum.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
import Web3Modal from 'web3modal'
import WalletConnectProvider from '@walletconnect/web3-provider'
import { ethers } from 'ethers'
import {
setEthProvider,
setSignerProvider
} from '@near-eth/client'
import render from './render'
import { onClick } from './domHelpers'
import { chainIdToEthNetwork } from './utils'
/*
Web3 modal helps us "connect" external wallets:
*/
let theme = 'light'
if (window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches) {
theme = 'dark'
};
window.web3Modal = new Web3Modal({
cacheProvider: true, // optional
providerOptions: {
walletconnect: {
package: WalletConnectProvider, // required
options: {
infuraId: process.env.INFURA_ID
}
}
},
theme: theme
})
async function login () {
const provider = await window.web3Modal.connect()
window.provider = provider
setEthProvider(new ethers.providers.InfuraProvider(
process.env.ethNetworkId === 'main' ? 'mainnet' : process.env.ethNetworkId,
process.env.INFURA_ID
))
setSignerProvider(new ethers.providers.Web3Provider(provider, 'any'))
if (provider.isMetaMask || provider.isImToken) {
window.ethUserAddress = provider.selectedAddress
window.connectedEthNetwork = chainIdToEthNetwork[parseInt(provider.chainId)]
} else {
window.ethUserAddress = provider.accounts[0]
window.connectedEthNetwork = chainIdToEthNetwork[provider.chainId]
}
provider.on('accountsChanged', (accounts) => {
window.ethUserAddress = accounts[0]
window.location.reload()
})
provider.on('chainChanged', (chainId) => {
window.connectedEthNetwork = chainIdToEthNetwork[parseInt(chainId)]
window.isValidEthNetwork = window.connectedEthNetwork === process.env.ethNetworkId
render()
})
provider.on('disconnect', (code, reason) => {
console.log(code, reason)
setTimeout(() => window.location.reload())
window.web3Modal.clearCachedProvider()
render()
})
window.isValidEthNetwork = window.connectedEthNetwork === process.env.ethNetworkId
window.ethInitialized = true
render()
}
onClick('authEthereum', login)
onClick('switchEthWallet', async () => {
window.ethInitialized = false
await window.web3Modal.clearCachedProvider()
localStorage.removeItem('walletconnect')
window.dom.hide('unsupportedNetworkModal')
try {
await login()
} catch (error) {
// user closed modal without selecting wallet
window.location.reload()
}
})
// on page load, check if user has already signed in via MetaMask
if (window.web3Modal.cachedProvider) {
login()
}