From 4761c33ed1079657edd67906b08e0f5c564942e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wiktor=20Tkaczy=C5=84ski?= Date: Fri, 1 Mar 2024 21:22:48 +0100 Subject: [PATCH] refactor: initialize Web3Wallet client asynchronously (#109) Sometimes it takes a while to init and it blocks other parts of the app. --- apps/ui/src/composables/useWalletConnect.ts | 36 ++++++++++++--------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/apps/ui/src/composables/useWalletConnect.ts b/apps/ui/src/composables/useWalletConnect.ts index 8a0af43aa..a20e6260e 100644 --- a/apps/ui/src/composables/useWalletConnect.ts +++ b/apps/ui/src/composables/useWalletConnect.ts @@ -10,21 +10,6 @@ import { getABI } from '@/helpers/etherscan'; import { SelectedStrategy } from '@/types'; type ApproveCallback = () => Promise; - -const projectId = import.meta.env.VITE_WC_PROJECT_ID; -const core = new Core({ - projectId -}); -const connector = await Web3Wallet.init({ - core, - metadata: { - name: 'Snapshot X', - description: 'Snapshot X', - url: 'https://snapshotx.org/', - icons: [] - } -}); - type ConnectionData = { logged: boolean; loading: boolean; @@ -32,6 +17,25 @@ type ConnectionData = { proposal: ProposalTypes.Struct | null; }; +let connector: Awaited> | null = null; +async function getConnector() { + if (connector) return connector; + + connector = await Web3Wallet.init({ + core: new Core({ + projectId: import.meta.env.VITE_WC_PROJECT_ID + }), + metadata: { + name: 'Snapshot X', + description: 'Snapshot X', + url: 'https://snapshotx.org/', + icons: [] + } + }); + + return connector; +} + const connections: Ref> = ref({}); async function parseCall(chainId: number, call) { @@ -130,6 +134,7 @@ export function useWalletConnect( async function logout() { if (!session.value) return; + const connector = await getConnector(); await connector.disconnectSession({ topic: session.value.topic, reason: getSdkError('USER_DISCONNECTED') @@ -164,6 +169,7 @@ export function useWalletConnect( loading.value = true; if (logged.value) await logout(); + const connector = await getConnector(); await connector.core.pairing.pair({ uri }); connector.on('session_proposal', async ({ id, params }) => {