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

[Create Safe] Handle wallet connection #1087

Merged
merged 5 commits into from
Nov 8, 2022
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { renderHook } from '@/tests/test-utils'
import useSyncSafeCreationStep from '@/components/new-safe/CreateSafe/useSyncSafeCreationStep'
import * as wallet from '@/hooks/wallets/useWallet'
import * as localStorage from '@/services/local-storage/useLocalStorage'
import type { ConnectedWallet } from '@/services/onboard'

describe('useSyncSafeCreationStep', () => {
beforeEach(() => {
jest.clearAllMocks()
})

it('should go to the first step if no wallet is connected', async () => {
jest.spyOn(wallet, 'default').mockReturnValue(null)
const mockSetStep = jest.fn()

renderHook(() => useSyncSafeCreationStep(mockSetStep))

expect(mockSetStep).toHaveBeenCalledWith(0)
})

it('should go to the fourth step if there is a pending safe', async () => {
jest.spyOn(localStorage, 'default').mockReturnValue([{}, jest.fn()])
jest.spyOn(wallet, 'default').mockReturnValue({ address: '0x1' } as ConnectedWallet)
const mockSetStep = jest.fn()

renderHook(() => useSyncSafeCreationStep(mockSetStep))

expect(mockSetStep).toHaveBeenCalledWith(4)
})

it('should not do anything if wallet is connected and there is no pending safe', async () => {
jest.spyOn(localStorage, 'default').mockReturnValue([undefined, jest.fn()])
jest.spyOn(wallet, 'default').mockReturnValue({ address: '0x1' } as ConnectedWallet)
const mockSetStep = jest.fn()

renderHook(() => useSyncSafeCreationStep(mockSetStep))

expect(mockSetStep).not.toHaveBeenCalled()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,22 @@ import type { StepRenderProps } from '@/components/new-safe/CardStepper/useCardS
import type { PendingSafeData } from '@/components/new-safe/steps/Step4'
import type { NewSafeFormData } from '@/components/new-safe/CreateSafe/index'
import { SAFE_PENDING_CREATION_STORAGE_KEY } from '@/components/new-safe/steps/Step4'
import useWallet from '@/hooks/wallets/useWallet'

const useSetCreationStep = (setStep: StepRenderProps<NewSafeFormData>['setStep'], isConnected: boolean) => {
const useSyncSafeCreationStep = (setStep: StepRenderProps<NewSafeFormData>['setStep']) => {
Copy link
Member

Choose a reason for hiding this comment

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

I think even though it's quite trivial we should write a small test for this.

Copy link
Member Author

Choose a reason for hiding this comment

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

done

const [pendingSafe] = useLocalStorage<PendingSafeData | undefined>(SAFE_PENDING_CREATION_STORAGE_KEY)
const wallet = useWallet()

useEffect(() => {
if (!isConnected) {
if (!wallet) {
setStep(0)
}

// Jump to the status screen if there is already a tx submitted
if (pendingSafe) {
setStep(4)
}
}, [isConnected, setStep, pendingSafe])
}, [wallet, setStep, pendingSafe])
}

export default useSetCreationStep
export default useSyncSafeCreationStep
17 changes: 17 additions & 0 deletions src/components/new-safe/NetworkWarning/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Alert, AlertTitle } from '@mui/material'
import { useCurrentChain } from '@/hooks/useChains'

const NetworkWarning = () => {
const chain = useCurrentChain()

if (!chain) return null

return (
<Alert severity="info" sx={{ mt: 3 }}>
<AlertTitle sx={{ fontWeight: 700 }}>Change your wallet network</AlertTitle>
You are trying to create a Safe on {chain.chainName}. Make sure that your wallet is set to the same network.
</Alert>
)
}

export default NetworkWarning
72 changes: 17 additions & 55 deletions src/components/new-safe/steps/Step0/index.tsx
Original file line number Diff line number Diff line change
@@ -1,80 +1,42 @@
import { Box, Button, Divider, Grid, Typography } from '@mui/material'
import { useEffect } from 'react'
import { Box, Grid } from '@mui/material'
import useWallet from '@/hooks/wallets/useWallet'
import ChainSwitcher from '@/components/common/ChainSwitcher'
import NetworkSelector from '@/components/common/NetworkSelector'
import useIsWrongChain from '@/hooks/useIsWrongChain'
import { useCurrentChain } from '@/hooks/useChains'
import { isPairingSupported } from '@/services/pairing/utils'

import type { NewSafeFormData } from '@/components/new-safe/CreateSafe'
import type { StepRenderProps } from '@/components/new-safe/CardStepper/useCardStepper'
import WalletDetails from '@/components/common/ConnectWallet/WalletDetails'
import PairingDetails from '@/components/common/PairingDetails'
import type { ConnectedWallet } from '@/services/onboard'
import useIsConnected from '@/hooks/useIsConnected'
import useSetCreationStep from '@/components/new-safe/CreateSafe/useSetCreationStep'
import useSyncSafeCreationStep from '@/components/new-safe/CreateSafe/useSyncSafeCreationStep'
import layoutCss from '@/components/new-safe/CreateSafe/styles.module.css'

export const ConnectWalletContent = ({ onSubmit }: { onSubmit: StepRenderProps<NewSafeFormData>['onSubmit'] }) => {
const isWrongChain = useIsWrongChain()
const CreateSafeStep0 = ({ onSubmit, setStep }: StepRenderProps<NewSafeFormData>) => {
const wallet = useWallet()
const chain = useCurrentChain()
const isSupported = isPairingSupported(chain?.disabledWallets)
useSyncSafeCreationStep(setStep)

const onConnect = (wallet?: ConnectedWallet) => {
useEffect(() => {
if (!wallet) return

onSubmit({ owners: [{ address: wallet.address, name: wallet.ens || '' }] })
}
}, [onSubmit, wallet])

return (
<>
{wallet && !isWrongChain && <Typography mb={2}>Wallet connected</Typography>}
{wallet ? (
<Typography component="div">
Creating a Safe on <NetworkSelector />
</Typography>
) : (
<>
<Grid container spacing={3}>
<Grid item xs={12} md={6} display="flex" flexDirection="column" alignItems="center" gap={2}>
<WalletDetails onConnect={onConnect} />
</Grid>

{isSupported && (
<Grid item xs={12} md={6} display="flex" flexDirection="column" alignItems="center" gap={2}>
<PairingDetails vertical />
</Grid>
)}
<Box className={layoutCss.row}>
<Grid container spacing={3}>
<Grid item xs={12} md={6} display="flex" flexDirection="column" alignItems="center" gap={2}>
<WalletDetails />
</Grid>
</>
)}
{isWrongChain && (
<Typography>
Your wallet connection must match the selected network. <ChainSwitcher />
</Typography>
)}
</>
)
}

const CreateSafeStep0 = ({ onSubmit, onBack, setStep }: StepRenderProps<NewSafeFormData>) => {
const isConnected = useIsConnected()
useSetCreationStep(setStep, isConnected)

return (
<>
<Box className={layoutCss.row}>
<ConnectWalletContent onSubmit={onSubmit} />
</Box>
<Divider />
<Box className={layoutCss.row} display="flex" flexDirection="row" justifyContent="space-between" gap={3}>
<Button variant="outlined" size="small" onClick={() => onBack()}>
Cancel
</Button>
<Button variant="contained" size="stretched" onClick={() => onSubmit({})} disabled={!isConnected}>
Next
</Button>
{isSupported && (
<Grid item xs={12} md={6} display="flex" flexDirection="column" alignItems="center" gap={2}>
<PairingDetails vertical />
</Grid>
)}
</Grid>
</Box>
</>
)
Expand Down
29 changes: 12 additions & 17 deletions src/components/new-safe/steps/Step1/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@ import {
Button,
Grid,
} from '@mui/material'
import ArrowBackIcon from '@mui/icons-material/ArrowBack'
import { useForm } from 'react-hook-form'
import { useMnemonicSafeName } from '@/hooks/useMnemonicName'
import InfoIcon from '@/public/images/notifications/info.svg'
import NetworkSelector from '@/components/common/NetworkSelector'
import type { StepRenderProps } from '../../CardStepper/useCardStepper'
import type { NewSafeFormData } from '../../CreateSafe'
import useIsConnected from '@/hooks/useIsConnected'
import useSetCreationStep from '@/components/new-safe/CreateSafe/useSetCreationStep'
import useSyncSafeCreationStep from '@/components/new-safe/CreateSafe/useSyncSafeCreationStep'

import css from './styles.module.css'
import layoutCss from '@/components/new-safe/CreateSafe/styles.module.css'
import useIsWrongChain from '@/hooks/useIsWrongChain'
import NetworkWarning from '@/components/new-safe/NetworkWarning'

type CreateSafeStep1Form = {
name: string
Expand All @@ -36,18 +36,17 @@ const STEP_1_FORM_ID = 'create-safe-step-1-form'
function CreateSafeStep1({
data,
onSubmit,
onBack,
setStep,
setSafeName,
}: StepRenderProps<NewSafeFormData> & { setSafeName: (name: string) => void }) {
const fallbackName = useMnemonicSafeName()
const isConnected = useIsConnected()
useSetCreationStep(setStep, isConnected)
const isWrongChain = useIsWrongChain()
useSyncSafeCreationStep(setStep)

const {
handleSubmit,
register,
formState: { errors },
formState: { errors, isValid },
} = useForm<CreateSafeStep1Form>({
mode: 'all',
defaultValues: {
Expand All @@ -61,6 +60,8 @@ function CreateSafeStep1({
onSubmit({ ...data, name })
}

const isDisabled = isWrongChain || !isValid

return (
<form onSubmit={handleSubmit(onFormSubmit)} id={STEP_1_FORM_ID}>
<Box className={layoutCss.row}>
Expand Down Expand Up @@ -107,19 +108,13 @@ function CreateSafeStep1({
</Link>
.
</Typography>

{isWrongChain && <NetworkWarning />}
</Box>
<Divider />
<Box className={layoutCss.row}>
<Box display="flex" flexDirection="row" justifyContent="space-between" gap={3}>
<Button
variant="outlined"
size="small"
onClick={() => onBack()}
startIcon={<ArrowBackIcon fontSize="small" />}
>
Back
</Button>
<Button type="submit" variant="contained" size="stretched" disabled={!isConnected}>
<Box display="flex" flexDirection="row" justifyContent="flex-end" gap={3}>
<Button type="submit" variant="contained" size="stretched" disabled={isDisabled}>
Next
</Button>
</Box>
Expand Down
24 changes: 15 additions & 9 deletions src/components/new-safe/steps/Step2/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ import type { StepRenderProps } from '../../CardStepper/useCardStepper'
import type { NewSafeFormData } from '../../CreateSafe'
import type { CreateSafeInfoItem } from '../../CreateSafeInfos'
import { useSafeSetupHints } from './useSafeSetupHints'
import useIsConnected from '@/hooks/useIsConnected'
import useSetCreationStep from '@/components/new-safe/CreateSafe/useSetCreationStep'
import useSyncSafeCreationStep from '@/components/new-safe/CreateSafe/useSyncSafeCreationStep'
import ArrowBackIcon from '@mui/icons-material/ArrowBack'
import css from './styles.module.css'
import layoutCss from '@/components/new-safe/CreateSafe/styles.module.css'
import NetworkWarning from '@/components/new-safe/NetworkWarning'
import useIsWrongChain from '@/hooks/useIsWrongChain'

export type CreateSafeStep2Form = {
owners: NamedAddress[]
Expand All @@ -37,8 +38,8 @@ const CreateSafeStep2 = ({
}: StepRenderProps<NewSafeFormData> & {
setDynamicHint: (hints: CreateSafeInfoItem | undefined) => void
}): ReactElement => {
const isConnected = useIsConnected()
useSetCreationStep(setStep, isConnected)
const isWrongChain = useIsWrongChain()
useSyncSafeCreationStep(setStep)

const formMethods = useForm<CreateSafeStep2Form>({
mode: 'all',
Expand All @@ -48,16 +49,19 @@ const CreateSafeStep2 = ({
},
})

const { register, handleSubmit, control, watch } = formMethods
const { register, handleSubmit, control, watch, formState, getValues } = formMethods

const allFormData = watch()
const threshold = watch(CreateSafeStep2Fields.threshold)

const { fields: ownerFields, append: appendOwner, remove: removeOwner } = useFieldArray({ control, name: 'owners' })

useSafeSetupHints(allFormData.threshold, ownerFields.length, setDynamicHint)
const isDisabled = isWrongChain || !formState.isValid

useSafeSetupHints(threshold, ownerFields.length, setDynamicHint)

const handleBack = () => {
onBack(allFormData)
const formData = getValues()
onBack(formData)
}

return (
Expand Down Expand Up @@ -125,14 +129,16 @@ const CreateSafeStep2 = ({
</Select>{' '}
out of {ownerFields.length} owner(s).
</Box>

{isWrongChain && <NetworkWarning />}
</Box>
<Divider />
<Box className={layoutCss.row}>
<Box display="flex" flexDirection="row" justifyContent="space-between" gap={3}>
<Button variant="outlined" size="small" onClick={handleBack} startIcon={<ArrowBackIcon fontSize="small" />}>
Back
</Button>
<Button type="submit" variant="contained" size="stretched" disabled={!isConnected}>
<Button type="submit" variant="contained" size="stretched" disabled={isDisabled}>
Next
</Button>
</Box>
Expand Down
Loading