Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: injected connector throws error after switching to a chain that was just added via 'wallet_addEthereumChain'. #4311

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 throwing error after switching to a chain that was just added via 'wallet_addEthereumChain'
36 changes: 26 additions & 10 deletions packages/core/src/connectors/injected.ts
Original file line number Diff line number Diff line change
Expand Up @@ -478,16 +478,32 @@ 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.'),
)
}
}),
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 (error) {
Expand Down
Loading