forked from wevm/references
-
Notifications
You must be signed in to change notification settings - Fork 0
/
injected.ts
333 lines (297 loc) · 9.81 KB
/
injected.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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import type { Chain } from '@wagmi/chains'
import type { Address } from 'abitype'
import {
ProviderRpcError,
ResourceNotFoundRpcError,
SwitchChainError,
UserRejectedRequestError,
createWalletClient,
custom,
getAddress,
numberToHex,
} from 'viem'
import { Connector } from './base'
import {
ChainNotConfiguredForConnectorError,
ConnectorNotFoundError,
} from './errors'
import { WindowProvider } from './types'
import { getInjectedName } from './utils/getInjectedName'
import { normalizeChainId } from './utils/normalizeChainId'
export type InjectedConnectorOptions = {
/** Name of connector */
name?: string | ((detectedName: string | string[]) => string)
/**
* [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) Ethereum Provider to target
*
* @default
* () => typeof window !== 'undefined' ? window.ethereum : undefined
*/
getProvider?: () => WindowProvider | undefined
/**
* MetaMask and other injected providers do not support programmatic disconnect.
* This flag simulates the disconnect behavior by keeping track of connection status in storage. See [GitHub issue](https://github.com/MetaMask/metamask-extension/issues/10353) for more info.
* @default true
*/
shimDisconnect?: boolean
}
type ConnectorOptions = InjectedConnectorOptions &
Required<Pick<InjectedConnectorOptions, 'getProvider'>>
export class InjectedConnector extends Connector<
WindowProvider | undefined,
ConnectorOptions
> {
readonly id: string = 'injected'
readonly name: string
readonly ready: boolean
#provider?: WindowProvider
protected shimDisconnectKey = `${this.id}.shimDisconnect`
// rome-ignore lint/correctness/noUnreachableSuper: <explanation>
constructor({
chains,
options: options_,
}: {
chains?: Chain[]
options?: InjectedConnectorOptions
} = {}) {
const options = {
shimDisconnect: true,
getProvider() {
if (typeof window === 'undefined') return
const ethereum = (window as unknown as { ethereum?: WindowProvider })
.ethereum
if (ethereum?.providers) return ethereum.providers[0]
return ethereum
},
...options_,
}
super({ chains, options })
const provider = options.getProvider()
if (typeof options.name === 'string') this.name = options.name
else if (provider) {
const detectedName = getInjectedName(provider)
if (options.name) this.name = options.name(detectedName)
else {
if (typeof detectedName === 'string') this.name = detectedName
else this.name = detectedName[0] as string
}
} else this.name = 'Injected'
this.ready = !!provider
}
async connect({ chainId }: { chainId?: number } = {}) {
try {
const provider = await this.getProvider()
if (!provider) throw new ConnectorNotFoundError()
if (provider.on) {
provider.on('accountsChanged', this.onAccountsChanged)
provider.on('chainChanged', this.onChainChanged)
provider.on('disconnect', this.onDisconnect)
}
this.emit('message', { type: 'connecting' })
const accounts = await provider.request({
method: 'eth_requestAccounts',
})
const account = getAddress(accounts[0] as string)
// Switch to chain if provided
let id = await this.getChainId()
let unsupported = this.isChainUnsupported(id)
if (chainId && id !== chainId) {
const chain = await this.switchChain(chainId)
id = chain.id
unsupported = this.isChainUnsupported(id)
}
// Add shim to storage signalling wallet is connected
if (this.options.shimDisconnect)
this.storage?.setItem(this.shimDisconnectKey, true)
return { account, chain: { id, unsupported } }
} catch (error) {
if (this.isUserRejectedRequestError(error))
throw new UserRejectedRequestError(error as Error)
if ((error as ProviderRpcError).code === -32002)
throw new ResourceNotFoundRpcError(error as ProviderRpcError)
throw error
}
}
async disconnect() {
const provider = await this.getProvider()
if (!provider?.removeListener) return
provider.removeListener('accountsChanged', this.onAccountsChanged)
provider.removeListener('chainChanged', this.onChainChanged)
provider.removeListener('disconnect', this.onDisconnect)
// Remove shim signalling wallet is disconnected
if (this.options.shimDisconnect)
this.storage?.removeItem(this.shimDisconnectKey)
}
async getAccount() {
const provider = await this.getProvider()
if (!provider) throw new ConnectorNotFoundError()
const accounts = await provider.request({
method: 'eth_accounts',
})
// return checksum address
return getAddress(accounts[0] as string)
}
async getChainId() {
const provider = await this.getProvider()
if (!provider) throw new ConnectorNotFoundError()
return provider.request({ method: 'eth_chainId' }).then(normalizeChainId)
}
async getProvider() {
const provider = this.options.getProvider()
if (provider) this.#provider = provider
return this.#provider
}
async getWalletClient({ chainId }: { chainId?: number } = {}) {
const [provider, account] = await Promise.all([
this.getProvider(),
this.getAccount(),
])
const chain = this.chains.find((x) => x.id === chainId)
if (!provider) throw new Error('provider is required.')
return createWalletClient({
account,
chain,
transport: custom(provider),
})
}
async isAuthorized() {
try {
if (
this.options.shimDisconnect &&
// If shim does not exist in storage, wallet is disconnected
!this.storage?.getItem(this.shimDisconnectKey)
)
return false
const provider = await this.getProvider()
if (!provider) throw new ConnectorNotFoundError()
const account = await this.getAccount()
return !!account
} catch {
return false
}
}
async switchChain(chainId: number) {
const provider = await this.getProvider()
if (!provider) throw new ConnectorNotFoundError()
const id = numberToHex(chainId)
try {
await Promise.all([
provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: id }],
}),
new Promise<void>((res) =>
this.on('change', ({ chain }) => {
if (chain?.id === chainId) res()
}),
),
])
return (
this.chains.find((x) => x.id === chainId) ?? {
id: chainId,
name: `Chain ${id}`,
network: `${id}`,
nativeCurrency: { name: 'Ether', decimals: 18, symbol: 'ETH' },
rpcUrls: { default: { http: [''] }, public: { http: [''] } },
}
)
} catch (error) {
const chain = this.chains.find((x) => x.id === chainId)
if (!chain)
throw new ChainNotConfiguredForConnectorError({
chainId,
connectorId: this.id,
})
// Indicates chain is not added to provider
if (
(error as ProviderRpcError).code === 4902 ||
// Unwrapping for MetaMask Mobile
// https://github.com/MetaMask/metamask-mobile/issues/2944#issuecomment-976988719
(error as ProviderRpcError<{ originalError?: { code: number } }>)?.data
?.originalError?.code === 4902
) {
try {
await provider.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: id,
chainName: chain.name,
nativeCurrency: chain.nativeCurrency,
rpcUrls: [chain.rpcUrls.public?.http[0] ?? ''],
blockExplorerUrls: this.getBlockExplorerUrls(chain),
},
],
})
const currentChainId = await this.getChainId()
if (currentChainId !== chainId)
throw new UserRejectedRequestError(
new Error('User rejected switch after adding network.'),
)
return chain
} catch (error) {
throw new UserRejectedRequestError(error as Error)
}
}
if (this.isUserRejectedRequestError(error))
throw new UserRejectedRequestError(error as Error)
throw new SwitchChainError(error as Error)
}
}
async watchAsset({
address,
decimals = 18,
image,
symbol,
}: {
address: Address
decimals?: number
image?: string
symbol: string
}) {
const provider = await this.getProvider()
if (!provider) throw new ConnectorNotFoundError()
return provider.request({
method: 'wallet_watchAsset',
params: {
type: 'ERC20',
options: {
address,
decimals,
image,
symbol,
},
},
})
}
protected onAccountsChanged = (accounts: string[]) => {
if (accounts.length === 0) this.emit('disconnect')
else
this.emit('change', {
account: getAddress(accounts[0] as string),
})
}
protected onChainChanged = (chainId: number | string) => {
const id = normalizeChainId(chainId)
const unsupported = this.isChainUnsupported(id)
this.emit('change', { chain: { id, unsupported } })
}
protected onDisconnect = async (error: Error) => {
// If MetaMask emits a `code: 1013` error, wait for reconnection before disconnecting
// https://github.com/MetaMask/providers/pull/120
if ((error as ProviderRpcError).code === 1013) {
const provider = await this.getProvider()
if (provider) {
const isAuthorized = await this.getAccount()
if (isAuthorized) return
}
}
this.emit('disconnect')
// Remove shim signalling wallet is disconnected
if (this.options.shimDisconnect)
this.storage?.removeItem(this.shimDisconnectKey)
}
protected isUserRejectedRequestError(error: unknown) {
return (error as ProviderRpcError).code === 4001
}
}