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

Feat: allow switching wallet #1496

Merged
merged 3 commits into from
Jan 10, 2023
Merged
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
16 changes: 14 additions & 2 deletions src/components/common/ConnectWallet/AccountCenter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import css from '@/components/common/ConnectWallet/styles.module.css'
import EthHashInfo from '@/components/common/EthHashInfo'
import ExpandLessIcon from '@mui/icons-material/ExpandLess'
import ExpandMoreIcon from '@mui/icons-material/ExpandMore'
import useOnboard, { lastWalletStorage } from '@/hooks/wallets/useOnboard'
import useOnboard, { closeAccountSelectionModal, connectWallet } from '@/hooks/wallets/useOnboard'
import { useAppSelector } from '@/store'
import { selectChainById } from '@/store/chainsSlice'
import Identicon from '@/components/common/Identicon'
Expand All @@ -20,14 +20,22 @@ const AccountCenter = ({ wallet }: { wallet: ConnectedWallet }) => {
const chainInfo = useAppSelector((state) => selectChainById(state, wallet.chainId))
const addressBook = useAddressBook()

const handleSwitchWallet = () => {
if (onboard) {
handleClose()
connectWallet(onboard)
closeAccountSelectionModal()
}
}

const handleDisconnect = () => {
if (!wallet) return

onboard?.disconnectWallet({
label: wallet.label,
})

lastWalletStorage.remove()
handleClose()
}

const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
Expand Down Expand Up @@ -92,6 +100,10 @@ const AccountCenter = ({ wallet }: { wallet: ConnectedWallet }) => {

<ChainSwitcher fullWidth />

<Button variant="contained" size="small" onClick={handleSwitchWallet} fullWidth>
Switch wallet
</Button>

<Button onClick={handleDisconnect} variant="danger" size="small" fullWidth disableElevation>
Disconnect
</Button>
Expand Down
68 changes: 47 additions & 21 deletions src/hooks/wallets/useOnboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export type ConnectedWallet = {
provider: EIP1193Provider
}

export const lastWalletStorage = localItem<string>('lastWallet')
const lastWalletStorage = localItem<string>('lastWallet')

const { getStore, setStore, useStore } = new ExternalStore<OnboardAPI>()

Expand Down Expand Up @@ -61,44 +61,70 @@ const getWalletConnectLabel = async ({ label, provider }: ConnectedWallet): Prom
return peerWallet ?? UNKNOWN_PEER
}

const trackWalletType = async (wallet: ConnectedWallet) => {
const trackWalletType = (wallet: ConnectedWallet) => {
trackEvent({ ...WALLET_EVENTS.CONNECT, label: wallet.label })

const wcLabel = await getWalletConnectLabel(wallet)

if (wcLabel) {
trackEvent({
...WALLET_EVENTS.WALLET_CONNECT,
label: wcLabel,
getWalletConnectLabel(wallet)
.then((wcLabel) => {
trackEvent({
...WALLET_EVENTS.WALLET_CONNECT,
label: wcLabel,
})
})
}
.catch(() => null)
}

// Detect mobile devices
const isMobile = () => /iPhone|iPad|iPod|Android/i.test(navigator.userAgent)

// Wrapper that tracks/sets the last used wallet
export const connectWallet = (onboard: OnboardAPI, options?: Parameters<OnboardAPI['connectWallet']>[0]) => {
export const connectWallet = async (onboard: OnboardAPI, options?: Parameters<OnboardAPI['connectWallet']>[0]) => {
// On mobile, automatically choose WalletConnect
if (!options && isMobile()) {
options = {
autoSelect: WalletNames.WALLET_CONNECT,
}
}

return onboard
.connectWallet(options)
.then(async (wallets) => {
const newWallet = getConnectedWallet(wallets)
try {
await onboard.connectWallet(options)
} catch (e) {
logError(Errors._302, (e as Error).message)
return
}

if (newWallet) {
lastWalletStorage.set(newWallet.label)
// Save the last used wallet and track the wallet type
const newWallet = getConnectedWallet(onboard.state.get().wallets)

await trackWalletType(newWallet)
return newWallet
}
})
.catch((e) => logError(Errors._302, (e as Error).message))
if (newWallet) {
// Save
lastWalletStorage.set(newWallet.label)

// Track
trackWalletType(newWallet)
}
}

// A workaround for an onboard "feature" that shows a defunct account select popup
// See https://github.com/blocknative/web3-onboard/issues/888
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mentioned our use case in a comment there.

export const closeAccountSelectionModal = () => {
const maxTries = 100
const modalText = 'Please switch the active account'
let tries = 0

const timer = setInterval(() => {
const onboardModal = document.querySelector('onboard-v2')?.shadowRoot
const isActionRequired = onboardModal?.textContent?.includes(modalText)

if (isActionRequired) {
// Dismiss the modal
;(onboardModal?.querySelector('.background') as HTMLElement)?.click()
tries = maxTries
}

tries += 1
if (tries >= maxTries) clearInterval(timer)
}, 100)
}

// Disable/enable wallets according to chain and cache the last used wallet
Expand Down