From 1e3695dd095f736b0fbddb4b04773a87a8737958 Mon Sep 17 00:00:00 2001 From: Tolgahan Arikan Date: Fri, 13 Dec 2024 16:25:33 +0300 Subject: [PATCH] Fix WalletConnect initial chain issue --- .../connectors/walletConnect/walletConnect.ts | 47 +++++++++++++++++-- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/packages/kit/src/connectors/walletConnect/walletConnect.ts b/packages/kit/src/connectors/walletConnect/walletConnect.ts index 99b5d778..b368017e 100644 --- a/packages/kit/src/connectors/walletConnect/walletConnect.ts +++ b/packages/kit/src/connectors/walletConnect/walletConnect.ts @@ -1,3 +1,4 @@ +import { createConnector } from 'wagmi' import { walletConnect as walletConnectbase, WalletConnectParameters } from 'wagmi/connectors' import { Wallet } from '../../types' @@ -8,13 +9,51 @@ export const walletConnect = (options: WalletConnectParameters): Wallet => ({ id: 'wallet-connect', logoDark: WalletConnectLogo, logoLight: WalletConnectLogo, - // iconBackground: '#fff', name: 'Walletconnect', type: 'wallet', createConnector: () => { - const connector = walletConnectbase({ - ...options + const baseConnector = walletConnectbase(options) + + return createConnector(config => { + const connector = baseConnector(config) + + const connect = async (params?: { chainId?: number }) => { + const targetChainId = params?.chainId ?? config.chains[0]?.id + if (!targetChainId) { + throw new Error('No target chain ID available') + } + + if (!connector.connect || !connector.switchChain) { + throw new Error('WalletConnect connector not properly initialized') + } + + // First establish the basic connection + const result = await connector.connect() + + // Only attempt to switch chains if we're not already on the target chain + if (result.chainId !== targetChainId) { + try { + // Switch to the target chain + await connector.switchChain({ chainId: targetChainId }) + + // Return the connection with the updated chain + return { + accounts: result.accounts, + chainId: targetChainId + } + } catch (error) { + console.warn('Failed to switch chain:', error) + return result + } + } + + return result + } + + return { + ...connector, + connect + } }) - return connector } })