Skip to content

Commit

Permalink
use ref to resolve import conundrum
Browse files Browse the repository at this point in the history
  • Loading branch information
frontendphil committed Oct 17, 2024
1 parent 9b2e849 commit e8e1cea
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions extension/src/panel/providers/useConnectProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BrowserProvider } from 'ethers'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { MutableRefObject, useCallback, useEffect, useState } from 'react'
import { toast } from 'react-toastify'
import { ChainId } from 'ser-kit'
import { CHAIN_CURRENCY, CHAIN_NAME, EXPLORER_URL, RPC } from '../../chains'
Expand All @@ -9,8 +9,17 @@ import { memoWhilePending } from './memoWhilePending'
// Wallet extensions won't inject connectProvider to the extension panel, so we've built ConnectProvider.
// connectProvider can be used just like window.ethereum

const providerRef: MutableRefObject<ConnectProvider | null> = { current: null }
const getProvider = () => {
if (providerRef.current == null) {
providerRef.current = new ConnectProvider()
}

return providerRef.current
}

export const useConnectProvider = () => {
const provider = useMemo(() => new ConnectProvider(), [])
const provider = getProvider()
const [accounts, setAccounts] = useState<string[]>([])
const [chainId, setChainId] = useState<number | null>(null)
const [ready, setReady] = useState(false)
Expand Down Expand Up @@ -117,8 +126,8 @@ const connectInjectedWallet = memoWhilePending(
}
)

const switchChain = async (provider: ConnectProvider, chainId: ChainId) => {
if (!provider) throw new Error('InjectedWallet not found')
const switchChain = async (chainId: ChainId) => {
const provider = getProvider()

try {
await provider.request({
Expand All @@ -136,9 +145,9 @@ const switchChain = async (provider: ConnectProvider, chainId: ChainId) => {
const handleChainChanged = () => {
resolve()
toast.dismiss(toastId)
provider?.removeListener('chainChanged', handleChainChanged)
provider.removeListener('chainChanged', handleChainChanged)
}
provider?.on('chainChanged', handleChainChanged)
provider.on('chainChanged', handleChainChanged)
})
return
}
Expand Down

0 comments on commit e8e1cea

Please sign in to comment.