This repository has been archived by the owner on Sep 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hooks.ts
73 lines (63 loc) · 2.33 KB
/
hooks.ts
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
import { useState, useEffect } from 'react'
import { useWeb3React } from '@web3-react/core'
import { injected } from './connectors'
export function useEagerConnect() {
const { activate, active } = useWeb3React()
const [tried, setTried] = useState(false)
useEffect(() => {
injected.isAuthorized().then((isAuthorized: boolean) => {
if (isAuthorized) {
activate(injected, undefined, true).catch(() => {
setTried(true)
})
} else {
setTried(true)
}
})
}, []) // intentionally only running on mount (make sure it's only mounted once :))
// if the connection worked, wait until we get confirmation of that to flip the flag
useEffect(() => {
if (!tried && active) {
setTried(true)
}
}, [tried, active])
return tried
}
export function useInactiveListener(suppress: boolean = false) {
const { active, error, activate } = useWeb3React()
useEffect((): any => {
const { ethereum } = window as any
if (ethereum && ethereum.on && !active && !error && !suppress) {
const handleConnect = () => {
console.log("Handling 'connect' event")
activate(injected)
}
const handleChainChanged = (chainId: string | number) => {
console.log("Handling 'chainChanged' event with payload", chainId)
activate(injected)
}
const handleAccountsChanged = (accounts: string[]) => {
console.log("Handling 'accountsChanged' event with payload", accounts)
if (accounts.length > 0) {
activate(injected)
}
}
const handleNetworkChanged = (networkId: string | number) => {
console.log("Handling 'networkChanged' event with payload", networkId)
activate(injected)
}
ethereum.on('connect', handleConnect)
ethereum.on('chainChanged', handleChainChanged)
ethereum.on('accountsChanged', handleAccountsChanged)
ethereum.on('networkChanged', handleNetworkChanged)
return () => {
if (ethereum.removeListener) {
ethereum.removeListener('connect', handleConnect)
ethereum.removeListener('chainChanged', handleChainChanged)
ethereum.removeListener('accountsChanged', handleAccountsChanged)
ethereum.removeListener('networkChanged', handleNetworkChanged)
}
}
}
}, [active, error, suppress, activate])
}