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

POC: Add web3modal #3727

Closed
wants to merge 5 commits into from
Closed
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
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,4 @@ NEXT_PUBLIC_REDEFINE_API=
NEXT_PUBLIC_SOCIAL_WALLET_OPTIONS_STAGING=
NEXT_PUBLIC_SOCIAL_WALLET_OPTIONS_PRODUCTION=

NEXT_PUBLIC_WEB3MODAL_PROJECT_ID=
Copy link
Member

Choose a reason for hiding this comment

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

Looks like this would be a required env var. We should mention it in the readme.

1 change: 1 addition & 0 deletions .github/workflows/build/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ runs:
NEXT_PUBLIC_FIREBASE_VAPID_KEY_PRODUCTION: ${{ fromJSON(inputs.secrets).NEXT_PUBLIC_FIREBASE_VAPID_KEY_PRODUCTION }}
NEXT_PUBLIC_FIREBASE_VAPID_KEY_STAGING: ${{ fromJSON(inputs.secrets).NEXT_PUBLIC_FIREBASE_VAPID_KEY_STAGING }}
NEXT_PUBLIC_SPINDL_SDK_KEY: ${{ fromJSON(inputs.secrets).NEXT_PUBLIC_SPINDL_SDK_KEY }}
NEXT_PUBLIC_WEB3MODAL_PROJECT_ID: ${{ fromJSON(inputs.secrets).NEXT_PUBLIC_WEB3MODAL_PROJECT_ID }}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
"@web3-onboard/trezor": "^2.4.2",
"@web3-onboard/walletconnect": "^2.5.4",
"@web3auth/mpc-core-kit": "^1.1.3",
"@web3modal/ethers": "^4.2.0",
"blo": "^1.1.1",
"bn.js": "^5.2.1",
"classnames": "^2.3.1",
Expand Down
15 changes: 9 additions & 6 deletions src/components/common/ChainSwitcher/index.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
import { useSwitchNetwork } from '@web3modal/ethers/react'
import type { ReactElement } from 'react'
import { useCallback } from 'react'
import { Box, Button } from '@mui/material'
import { useCurrentChain } from '@/hooks/useChains'
import useOnboard from '@/hooks/wallets/useOnboard'
import useIsWrongChain from '@/hooks/useIsWrongChain'
import css from './styles.module.css'
import { switchWalletChain } from '@/services/tx/tx-sender/sdk'

const ChainSwitcher = ({ fullWidth }: { fullWidth?: boolean }): ReactElement | null => {
const chain = useCurrentChain()
const onboard = useOnboard()
const isWrongChain = useIsWrongChain()
const { switchNetwork } = useSwitchNetwork()

const handleChainSwitch = useCallback(async () => {
if (!onboard || !chain) return
if (!chain) return

await switchWalletChain(onboard, chain.chainId)
}, [chain, onboard])
try {
await switchNetwork(Number(chain.chainId))
} catch (e) {
console.log(e)
}
}, [chain, switchNetwork])

if (!isWrongChain) return null

Expand Down
6 changes: 3 additions & 3 deletions src/components/common/CheckWallet/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useWeb3Modal } from '@web3modal/scaffold-react'
import { type ReactElement } from 'react'
import { Tooltip } from '@mui/material'
import useIsOnlySpendingLimitBeneficiary from '@/hooks/useIsOnlySpendingLimitBeneficiary'
import useIsSafeOwner from '@/hooks/useIsSafeOwner'
import useWallet from '@/hooks/wallets/useWallet'
import useConnectWallet from '../ConnectWallet/useConnectWallet'

type CheckWalletProps = {
children: (ok: boolean) => ReactElement
Expand All @@ -21,7 +21,7 @@ const CheckWallet = ({ children, allowSpendingLimit, allowNonOwner, noTooltip }:
const wallet = useWallet()
const isSafeOwner = useIsSafeOwner()
const isSpendingLimit = useIsOnlySpendingLimitBeneficiary()
const connectWallet = useConnectWallet()
const { open } = useWeb3Modal()

const message =
wallet && (isSafeOwner || allowNonOwner || (isSpendingLimit && allowSpendingLimit))
Expand All @@ -36,7 +36,7 @@ const CheckWallet = ({ children, allowSpendingLimit, allowNonOwner, noTooltip }:

return (
<Tooltip title={message}>
<span onClick={wallet ? undefined : connectWallet}>{children(false)}</span>
<span onClick={wallet ? undefined : () => open()}>{children(false)}</span>
</Tooltip>
)
}
Expand Down
6 changes: 3 additions & 3 deletions src/components/common/ConnectWallet/ConnectWalletButton.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Button } from '@mui/material'
import useConnectWallet from '@/components/common/ConnectWallet/useConnectWallet'
import { useWeb3Modal } from '@web3modal/scaffold-react'

const ConnectWalletButton = ({
onConnect,
Expand All @@ -12,11 +12,11 @@ const ConnectWalletButton = ({
small?: boolean
text?: string
}): React.ReactElement => {
const connectWallet = useConnectWallet()
const { open } = useWeb3Modal()

const handleConnect = () => {
onConnect?.()
connectWallet()
open()
}

return (
Expand Down
16 changes: 0 additions & 16 deletions src/components/common/ConnectWallet/useConnectWallet.ts

This file was deleted.

19 changes: 3 additions & 16 deletions src/components/common/WalletInfo/index.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { render } from '@/tests/test-utils'
import { WalletInfo } from '@/components/common/WalletInfo/index'
import { type EIP1193Provider, type OnboardAPI } from '@web3-onboard/core'
import { type EIP1193Provider } from '@web3-onboard/core'
import { type NextRouter } from 'next/router'
import * as mpcModule from '@/services/mpc/SocialLoginModule'
import * as constants from '@/config/constants'
Expand All @@ -21,12 +21,6 @@ const mockRouter = {
pathname: '',
} as NextRouter

const mockOnboard = {
connectWallet: jest.fn(),
disconnectWallet: jest.fn(),
setChain: jest.fn(),
} as unknown as OnboardAPI

jest.mock('@/services/mpc/SocialWalletService')

describe('WalletInfo', () => {
Expand All @@ -42,7 +36,6 @@ describe('WalletInfo', () => {
wallet={mockWallet}
socialWalletService={socialWalletService}
router={mockRouter}
onboard={mockOnboard}
addressBook={{}}
handleClose={jest.fn()}
balance={undefined}
Expand All @@ -59,7 +52,6 @@ describe('WalletInfo', () => {
wallet={mockWallet}
socialWalletService={socialWalletService}
router={mockRouter}
onboard={mockOnboard}
addressBook={{}}
handleClose={jest.fn()}
balance={undefined}
Expand All @@ -76,7 +68,6 @@ describe('WalletInfo', () => {
wallet={mockWallet}
socialWalletService={socialWalletService}
router={mockRouter}
onboard={mockOnboard}
addressBook={{}}
handleClose={jest.fn()}
balance={undefined}
Expand All @@ -92,7 +83,8 @@ describe('WalletInfo', () => {
disconnectButton.click()
})

expect(mockOnboard.disconnectWallet).toHaveBeenCalled()
// TODO: Listen to the new function call
expect(true).toBe(true)
})

it('should display a Delete Account button on dev for social login', () => {
Expand All @@ -104,7 +96,6 @@ describe('WalletInfo', () => {
wallet={mockWallet}
socialWalletService={socialWalletService}
router={mockRouter}
onboard={mockOnboard}
addressBook={{}}
handleClose={jest.fn()}
balance={undefined}
Expand All @@ -124,7 +115,6 @@ describe('WalletInfo', () => {
wallet={mockWallet}
socialWalletService={socialWalletService}
router={mockRouter}
onboard={mockOnboard}
addressBook={{}}
handleClose={jest.fn()}
balance={undefined}
Expand All @@ -144,7 +134,6 @@ describe('WalletInfo', () => {
wallet={mockWallet}
socialWalletService={socialWalletService}
router={mockRouter}
onboard={mockOnboard}
addressBook={{}}
handleClose={jest.fn()}
balance={undefined}
Expand All @@ -163,7 +152,6 @@ describe('WalletInfo', () => {
wallet={mockWallet}
socialWalletService={socialWalletService}
router={mockRouter}
onboard={mockOnboard}
addressBook={{}}
handleClose={jest.fn()}
balance={undefined}
Expand All @@ -185,7 +173,6 @@ describe('WalletInfo', () => {
wallet={mockWallet}
socialWalletService={socialWalletService}
router={mockRouter}
onboard={mockOnboard}
addressBook={{}}
handleClose={jest.fn()}
balance={undefined}
Expand Down
22 changes: 4 additions & 18 deletions src/components/common/WalletInfo/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import WalletBalance from '@/components/common/WalletBalance'
import { WalletIdenticon } from '@/components/common/WalletOverview'
import { Box, Button, Typography } from '@mui/material'
import { useDisconnect } from '@web3modal/ethers/react'
import css from './styles.module.css'
import SocialLoginInfo from '@/components/common/SocialLoginInfo'
import Link from 'next/link'
Expand All @@ -10,7 +11,7 @@ import EthHashInfo from '@/components/common/EthHashInfo'
import ChainSwitcher from '@/components/common/ChainSwitcher'
import { IS_PRODUCTION } from '@/config/constants'
import { isSocialLoginWallet } from '@/services/mpc/SocialLoginModule'
import useOnboard, { type ConnectedWallet, switchWallet } from '@/hooks/wallets/useOnboard'
import { type ConnectedWallet } from '@/hooks/wallets/useOnboard'
import { useRouter } from 'next/router'
import useAddressBook from '@/hooks/useAddressBook'
import { useAppSelector } from '@/store'
Expand All @@ -26,7 +27,6 @@ type WalletInfoProps = {
currentChainId: ReturnType<typeof useChainId>
socialWalletService: ReturnType<typeof useSocialWallet>
router: ReturnType<typeof useRouter>
onboard: ReturnType<typeof useOnboard>
addressBook: ReturnType<typeof useAddressBook>
handleClose: () => void
}
Expand All @@ -37,26 +37,17 @@ export const WalletInfo = ({
currentChainId,
socialWalletService,
router,
onboard,
addressBook,
handleClose,
}: WalletInfoProps) => {
const chainInfo = useAppSelector((state) => selectChainById(state, wallet.chainId))
const prefix = chainInfo?.shortName

const handleSwitchWallet = () => {
if (onboard) {
handleClose()
switchWallet(onboard)
}
}
const { disconnect } = useDisconnect()

const resetAccount = () => socialWalletService?.__deleteAccount()

const handleDisconnect = () => {
onboard?.disconnectWallet({
label: wallet.label,
})
disconnect()

handleClose()
}
Expand Down Expand Up @@ -134,10 +125,6 @@ export const WalletInfo = ({
<Box display="flex" flexDirection="column" gap={2} width={1}>
<ChainSwitcher fullWidth />

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

<Button
onClick={handleDisconnect}
variant="danger"
Expand All @@ -162,7 +149,6 @@ export const WalletInfo = ({
export default madProps(WalletInfo, {
socialWalletService: useSocialWallet,
router: useRouter,
onboard: useOnboard,
addressBook: useAddressBook,
currentChainId: useChainId,
})
52 changes: 39 additions & 13 deletions src/components/common/WalletProvider/index.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,51 @@
import useSafeInfo from '@/hooks/useSafeInfo'
import { useWeb3ModalAccount, useWeb3ModalProvider } from '@web3modal/ethers/react'
import { useWalletInfo, useWeb3Modal } from '@web3modal/scaffold-react'
import { createContext, type ReactElement, type ReactNode, useEffect, useState } from 'react'
import useOnboard, { type ConnectedWallet, getConnectedWallet } from '@/hooks/wallets/useOnboard'
import { type ConnectedWallet } from '@/hooks/wallets/useOnboard'

export const WalletContext = createContext<ConnectedWallet | null>(null)

const WalletProvider = ({ children }: { children: ReactNode }): ReactElement => {
const onboard = useOnboard()
const onboardWallets = onboard?.state.get().wallets || []
const [wallet, setWallet] = useState<ConnectedWallet | null>(getConnectedWallet(onboardWallets))
const { address, chainId, isConnected } = useWeb3ModalAccount()
const { walletProvider } = useWeb3ModalProvider()
const { open, close } = useWeb3Modal()
const { walletInfo } = useWalletInfo()
const { safe } = useSafeInfo()
const [wallet, setWallet] = useState<ConnectedWallet | null>(
isConnected && chainId && walletProvider
? {
label: walletInfo?.name || 'Wallet',
address: address as `0x${string}`,
chainId: chainId.toString(),
provider: walletProvider,
icon: walletInfo?.icon,
}
: null,
)

useEffect(() => {
if (!onboard) return
setWallet(
isConnected && chainId && walletProvider
? {
label: walletInfo?.name || 'Wallet',
address: address as `0x${string}`,
chainId: chainId.toString(),
provider: walletProvider,
icon: walletInfo?.icon,
}
: null,
)
}, [address, chainId, isConnected, walletInfo?.icon, walletInfo?.name, walletProvider])

const walletSubscription = onboard.state.select('wallets').subscribe((wallets) => {
const newWallet = getConnectedWallet(wallets)
setWallet(newWallet)
})

return () => {
walletSubscription.unsubscribe()
// EXPERIMENTAL: sync wallet and safe chain
useEffect(() => {
if (safe.chainId !== '' && chainId && Number(safe.chainId) !== chainId) {
open({ view: 'Networks' })
} else {
close()
}
}, [onboard])
}, [chainId, close, open, safe.chainId])

return <WalletContext.Provider value={wallet}>{children}</WalletContext.Provider>
}
Expand Down
8 changes: 3 additions & 5 deletions src/components/safe-apps/SafeAppLandingPage/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useWeb3Modal } from '@web3modal/scaffold-react'
import { useEffect } from 'react'
import { Box, CircularProgress, Paper } from '@mui/material'
import Grid from '@mui/material/Unstable_Grid2'
Expand All @@ -10,7 +11,6 @@ import { AppActions } from '@/components/safe-apps/SafeAppLandingPage/AppActions
import useWallet from '@/hooks/wallets/useWallet'
import { AppRoutes } from '@/config/routes'
import { SAFE_APPS_DEMO_SAFE_MAINNET } from '@/config/constants'
import useOnboard from '@/hooks/wallets/useOnboard'
import { Errors, logError } from '@/services/exceptions'
import type { ChainInfo } from '@safe-global/safe-gateway-typescript-sdk'

Expand All @@ -25,7 +25,7 @@ const SafeAppLanding = ({ appUrl, chain }: Props) => {
const [backendApp, , backendAppLoading] = useSafeAppFromBackend(appUrl, chain.chainId)
const { safeApp, isLoading } = useSafeAppFromManifest(appUrl, chain.chainId, backendApp)
const wallet = useWallet()
const onboard = useOnboard()
const { open } = useWeb3Modal()
// show demo if the app was shared for mainnet or we can find the mainnet chain id on the backend
const showDemo = chain.chainId === CHAIN_ID_WITH_A_DEMO || !!backendApp?.chainIds.includes(CHAIN_ID_WITH_A_DEMO)

Expand All @@ -38,11 +38,9 @@ const SafeAppLanding = ({ appUrl, chain }: Props) => {
}, [isLoading, backendApp, safeApp, backendAppLoading, chain])

const handleConnectWallet = async () => {
if (!onboard) return

trackEvent(OVERVIEW_EVENTS.OPEN_ONBOARD)

onboard.connectWallet().catch((e) => logError(Errors._302, e))
open().catch((e) => logError(Errors._302, e))
}

const handleDemoClick = () => {
Expand Down
Loading
Loading