diff --git a/.changeset/unlucky-boats-dance.md b/.changeset/unlucky-boats-dance.md index 488418235b..7d2842b981 100644 --- a/.changeset/unlucky-boats-dance.md +++ b/.changeset/unlucky-boats-dance.md @@ -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`. diff --git a/packages/core/src/connectors/injected.ts b/packages/core/src/connectors/injected.ts index 0a1579c1ca..aefb747fdf 100644 --- a/packages/core/src/connectors/injected.ts +++ b/packages/core/src/connectors/injected.ts @@ -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((resolve) => { + const listener = ((data) => { + if ('chainId' in data && data.chainId === chainId) { + config.emitter.off('change', listener) + resolve() + } + }) satisfies Parameters[1] + config.emitter.on('change', listener) + }) + try { await Promise.all([ provider @@ -428,15 +438,7 @@ export function injected(parameters: InjectedParameters = {}) { if (currentChainId === chainId) config.emitter.emit('change', { chainId }) }), - new Promise((resolve) => { - const listener = ((data) => { - if ('chainId' in data && data.chainId === chainId) { - config.emitter.off('change', listener) - resolve() - } - }) satisfies Parameters[1] - config.emitter.on('change', listener) - }), + promise, ]) return chain } catch (err) { @@ -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((resolve) => { - const listener = ((data) => { - if ('chainId' in data && data.chainId === chainId) { - config.emitter.off('change', listener) - resolve() - } - }) satisfies Parameters[1] - config.emitter.on('change', listener) - }), + promise, ]) return chain