Skip to content

Commit

Permalink
Fix the switchChain error encountered when using the "metaMask" conne…
Browse files Browse the repository at this point in the history
…ctor (#4227)

* fix: metaMask switchChain

* chore: changeset

---------

Co-authored-by: Tom Meagher <[email protected]>
  • Loading branch information
xianchenxc and tmm committed Sep 16, 2024
1 parent b0eb89c commit d07ad7f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/tiny-crabs-hug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@wagmi/connectors": patch
---

Fixed MetaMask Connector throwing error after switching to a chain that was just added via `'wallet_addEthereumChain'`.
7 changes: 6 additions & 1 deletion packages/connectors/src/metaMask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@ import type {
import {
type AddEthereumChainParameter,
type Address,
type Hex,
type ProviderConnectInfo,
type ProviderRpcError,
ResourceUnavailableRpcError,
type RpcError,
SwitchChainError,
UserRejectedRequestError,
getAddress,
hexToNumber,
numberToHex,
withRetry,
withTimeout,
Expand Down Expand Up @@ -288,7 +290,10 @@ export function metaMask(parameters: MetaMaskParameters = {}) {
params: [addEthereumChain],
})

const currentChainId = await this.getChainId()
const currentChainId = hexToNumber(
// Call `'eth_chainId'` directly to guard against `this.state.chainId` (via `provider.getChainId`) being stale.
(await provider.request({ method: 'eth_chainId' })) as Hex,
)
if (currentChainId !== chainId)
throw new UserRejectedRequestError(
new Error('User rejected switch after adding network.'),
Expand Down

0 comments on commit d07ad7f

Please sign in to comment.