Skip to content

Commit

Permalink
chore: tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
tmm committed Nov 7, 2024
1 parent 752ffef commit 160fa84
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 22 deletions.
2 changes: 1 addition & 1 deletion .changeset/unlucky-boats-dance.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
"@wagmi/core": patch
---

Fixed injected connector throwing error after switching to a chain that was just added via 'wallet_addEthereumChain'
Fixed `injected` connector race condition after calling `'wallet_addEthereumChain'` in `switchChain`.
35 changes: 14 additions & 21 deletions packages/core/src/connectors/injected.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,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 @@ -428,15 +438,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 @@ -486,23 +488,14 @@ export function injected(parameters: InjectedParameters = {}) {
})
.then(async () => {
const currentChainId = await this.getChainId()
if (currentChainId === chainId) {
if (currentChainId === chainId)
config.emitter.emit('change', { chainId })
} else {
else
throw new UserRejectedRequestError(
new Error('User rejected switch after adding network.'),
)
}
}),
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
Expand Down

0 comments on commit 160fa84

Please sign in to comment.