-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathuseConnectProvider.tsx
169 lines (141 loc) · 4.87 KB
/
useConnectProvider.tsx
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
import { CHAIN_CURRENCY, CHAIN_NAME, EXPLORER_URL, RPC } from '@/chains'
import { infoToast } from '@/components'
import { useWindowId } from '@/inject-bridge'
import { Eip1193Provider } from '@/types'
import { MutableRefObject, useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { ChainId } from 'ser-kit'
import { ConnectionStatus } from '../connectTypes'
import { ConnectProvider } from './ConnectProvider'
import { InjectedWalletError } from './InjectedWalletError'
import { useConnect } from './useConnect'
// Wallet extensions won't inject connectProvider to the extension panel, so we've built ConnectProvider.
// connectProvider can be used just like window.ethereum
const providerRef: MutableRefObject<ConnectProvider | null> = { current: null }
const getProvider = (windowId: number) => {
if (providerRef.current == null) {
providerRef.current = new ConnectProvider(windowId)
}
return providerRef.current
}
export const useConnectProvider = () => {
const provider = getProvider(useWindowId())
const [accounts, setAccounts] = useState<string[]>([])
const [chainId, setChainId] = useState<ChainId | null>(null)
const [ready, setReady] = useState(false)
const [connectionStatus, setConnectionStatus] =
useState<ConnectionStatus>('disconnected')
useEffect(() => {
let canceled = false
const ifNotCanceled =
<Args extends any[]>(callback: (...operationParameters: Args) => void) =>
(...args: Args) => {
if (!canceled) {
callback(...args)
}
}
const handleAccountsChanged = ifNotCanceled((accounts: string[]) => {
setAccounts(accounts)
})
const handleChainChanged = ifNotCanceled((chainIdHex: string) => {
const chainId = parseInt(chainIdHex.slice(2), 16)
setChainId(chainId as unknown as ChainId)
})
const handleDisconnect = ifNotCanceled((error: Error) => {
console.warn(error)
setChainId(null)
setAccounts([])
})
provider.on('accountsChanged', handleAccountsChanged)
provider.on('chainChanged', handleChainChanged)
provider.on('disconnect', handleDisconnect)
provider.on('readyChanged', ifNotCanceled(setReady))
return () => {
if (!provider) {
return
}
canceled = true
provider.removeListener('accountsChanged', handleAccountsChanged)
provider.removeListener('chainChanged', handleChainChanged)
provider.removeListener('disconnect', handleDisconnect)
provider.removeListener('readyChanged', setReady)
}
}, [provider])
const connect = useConnect(provider, {
onBeforeConnect() {
setConnectionStatus('connecting')
},
onConnect(chainId, accounts) {
setChainId(chainId)
setAccounts(accounts)
setConnectionStatus('connected')
},
onError() {
setConnectionStatus('error')
},
})
return {
provider,
ready,
connect,
connectionStatus,
switchChain: (chainId: ChainId) => switchChain(provider, chainId),
accounts,
chainId,
}
}
const switchChain = async (provider: Eip1193Provider, chainId: ChainId) => {
try {
await provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: `0x${chainId.toString(16)}` }],
})
} catch (err) {
if ((err as InjectedWalletError).code === -32002) {
// another wallet_switchEthereumChain request is already pending
const { promise, resolve } = Promise.withResolvers<void>()
const toastId = infoToast({
title: 'Chain',
message: 'Check your wallet to confirm switching the network',
})
const handleChainChanged = (): void => {
toast.dismiss(toastId)
provider.removeListener('chainChanged', handleChainChanged)
resolve()
}
provider.on('chainChanged', handleChainChanged)
return promise
}
if ((err as InjectedWalletError).code === 4902) {
// the requested chain has not been added by InjectedWallet
await provider.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: `0x${chainId.toString(16)}`,
chainName: CHAIN_NAME[chainId],
nativeCurrency: {
name: CHAIN_CURRENCY[chainId],
symbol: CHAIN_CURRENCY[chainId],
decimals: 18,
},
rpcUrls: [RPC[chainId]],
blockExplorerUrls: [EXPLORER_URL[chainId]],
},
],
})
} else {
throw err
}
}
const { promise, resolve } = Promise.withResolvers<void>()
const handleChainChanged = () => {
provider.removeListener('chainChanged', handleChainChanged)
resolve()
}
provider.on('chainChanged', handleChainChanged)
// wait for chain change event (InjectedWallet will emit this event
// only after some delay, so our state that reacts to this event
// would be out of sync if we don't wait here)
return promise
}