Skip to content

Commit

Permalink
Fix race condition in injected.ts (#4207)
Browse files Browse the repository at this point in the history
* Fix race condition in injected.ts

It can hangs if "once" catches an event with unexpected chainId

* chore: tweaks

---------

Co-authored-by: Tom Meagher <tom@meagher.co>
  • Loading branch information
Smert and tmm authored Sep 27, 2024
1 parent e4d2933 commit 56f2482
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 10 deletions.
6 changes: 6 additions & 0 deletions .changeset/hungry-colts-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@wagmi/connectors": patch
"@wagmi/core": patch
---

Updated chain switch listener for `injected` and `metaMask` to be more robust.
14 changes: 9 additions & 5 deletions packages/connectors/src/metaMask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,15 @@ export function metaMask(parameters: MetaMaskParameters = {}) {
if (currentChainId === chainId)
config.emitter.emit('change', { chainId })
}),
new Promise<void>((resolve) =>
config.emitter.once('change', ({ chainId: currentChainId }) => {
if (currentChainId === chainId) resolve()
}),
),
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)
}),
])
return chain
} catch (err) {
Expand Down
14 changes: 9 additions & 5 deletions packages/core/src/connectors/injected.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,11 +428,15 @@ export function injected(parameters: InjectedParameters = {}) {
if (currentChainId === chainId)
config.emitter.emit('change', { chainId })
}),
new Promise<void>((resolve) =>
config.emitter.once('change', ({ chainId: currentChainId }) => {
if (currentChainId === chainId) resolve()
}),
),
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)
}),
])
return chain
} catch (err) {
Expand Down

0 comments on commit 56f2482

Please sign in to comment.