Skip to content

Commit

Permalink
fix: injected connector throws error after switching to a chain that …
Browse files Browse the repository at this point in the history
…was just added via `'wallet_addEthereumChain'`. (#4311)

* fix: injected connector throwing error after switching to a chain that was just added via `'wallet_addEthereumChain'`.

* chore: changeset

* chore: tweaks

---------

Co-authored-by: Tom Meagher <[email protected]>
  • Loading branch information
chybisov and tmm authored Nov 7, 2024
1 parent feef3b2 commit e08681c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 19 deletions.
5 changes: 5 additions & 0 deletions .changeset/unlucky-boats-dance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@wagmi/core": patch
---

Fixed `injected` connector race condition after calling `'wallet_addEthereumChain'` in `switchChain`.
47 changes: 28 additions & 19 deletions packages/core/src/connectors/injected.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,16 @@ export function injected(parameters: InjectedParameters = {}) {
const chain = config.chains.find((x) => x.id === chainId)
if (!chain) throw new SwitchChainError(new ChainNotConfiguredError())

const promise = new Promise<void>((resolve) => {
const listener = ((data) => {
if ('chainId' in data && data.chainId === chainId) {
config.emitter.off('change', listener)
resolve()
}
}) satisfies Parameters<typeof config.emitter.on>[1]
config.emitter.on('change', listener)
})

try {
await Promise.all([
provider
Expand All @@ -375,15 +385,7 @@ export function injected(parameters: InjectedParameters = {}) {
if (currentChainId === chainId)
config.emitter.emit('change', { chainId })
}),
new Promise<void>((resolve) => {
const listener = ((data) => {
if ('chainId' in data && data.chainId === chainId) {
config.emitter.off('change', listener)
resolve()
}
}) satisfies Parameters<typeof config.emitter.on>[1]
config.emitter.on('change', listener)
}),
promise,
])
return chain
} catch (err) {
Expand Down Expand Up @@ -425,16 +427,23 @@ export function injected(parameters: InjectedParameters = {}) {
rpcUrls,
} satisfies AddEthereumChainParameter

await provider.request({
method: 'wallet_addEthereumChain',
params: [addEthereumChain],
})

const currentChainId = await this.getChainId()
if (currentChainId !== chainId)
throw new UserRejectedRequestError(
new Error('User rejected switch after adding network.'),
)
await Promise.all([
provider
.request({
method: 'wallet_addEthereumChain',
params: [addEthereumChain],
})
.then(async () => {
const currentChainId = await this.getChainId()
if (currentChainId === chainId)
config.emitter.emit('change', { chainId })
else
throw new UserRejectedRequestError(
new Error('User rejected switch after adding network.'),
)
}),
promise,
])

return chain
} catch (error) {
Expand Down

0 comments on commit e08681c

Please sign in to comment.