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

Add signature modal and signature functionality #549

Merged
merged 7 commits into from
Feb 2, 2024
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
78 changes: 78 additions & 0 deletions components/Modal/Sign.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import {
Button,
Heading,
Icon,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
Text,
} from '@chakra-ui/react'
import { FaFileSignature } from '@react-icons/all-files/fa/FaFileSignature'
import useTranslation from 'next-translate/useTranslation'
import { FC, useCallback, useState } from 'react'
import { Connector, useDisconnect } from 'wagmi'
import useAccount from '../../hooks/useAccount'

type Props = {
connector?: Connector
isOpen: boolean
onClose: () => void
}

const SignModal: FC<Props> = ({ connector, isOpen, onClose }) => {
const { t } = useTranslation('components')
const { sign } = useAccount()
const { disconnect } = useDisconnect()
const [isLoading, setLoading] = useState(false)

const onSign = useCallback(async () => {
if (!connector) return
setLoading(true)
try {
await sign(connector)
} catch (e: any) {
disconnect()
} finally {
onClose()
setLoading(false)
}
}, [connector, disconnect, onClose, sign])

return (
<Modal
isOpen={isOpen}
onClose={() => {
onClose()
disconnect()
}}
isCentered
size="sm"
>
<ModalOverlay />
<ModalContent>
<ModalHeader>
<Heading as="h3" variant="heading1" color="brand.black">
{t('modal.signature.title')}
</Heading>
</ModalHeader>
<ModalCloseButton />
<ModalBody textAlign="center">
<Icon as={FaFileSignature} w={12} h={12} color="green.500" />
<Heading variant="heading1">{t('modal.signature.sub-title')}</Heading>
<Text variant="text-sm">{t('modal.signature.description')}</Text>
</ModalBody>
<ModalFooter as="div">
<Button onClick={onSign} isLoading={isLoading} mx="auto" size="md">
{t('modal.signature.action')}
</Button>
</ModalFooter>
</ModalContent>
</Modal>
)
}

export default SignModal
23 changes: 13 additions & 10 deletions hooks/useAccount.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useAuthenticate, useIsLoggedIn } from '@liteflow/react'
import { JwtPayload, jwtDecode } from 'jwt-decode'
import { useCallback, useEffect, useMemo } from 'react'
import { useCallback, useMemo } from 'react'
import { useCookies } from 'react-cookie'
import { Connector, useAccount as useWagmiAccount } from 'wagmi'
import { walletClientToSigner } from './useSigner'
Expand All @@ -12,6 +12,7 @@ type AccountDetail = {
jwtToken: string | null
logout: () => Promise<void>
login: (connector: Connector) => Promise<void>
sign: (connector: Connector) => Promise<void>
}

export const COOKIE_JWT_TOKEN = 'jwt-token'
Expand Down Expand Up @@ -57,14 +58,6 @@ export default function useAccount(): AccountDetail {
[isLoggedInWhileReconnect, isLoggedInToAPI],
)

// Reconnect based on the token and mark as logged in
useEffect(() => {
if (isLoggedInToAPI) return
if (!isReconnecting) return
if (!jwt) return
setAuthenticationToken(jwt.token)
}, [isLoggedInToAPI, isReconnecting, jwt, setAuthenticationToken])

const login = useCallback(
async (connector: Connector) => {
const wallet = await connector.getWalletClient()
Expand All @@ -73,6 +66,14 @@ export default function useAccount(): AccountDetail {
if (jwt && currentAddress === jwt.address) {
return setAuthenticationToken(jwt.token)
}
},
[jwt, setAuthenticationToken],
)

const sign = useCallback(
async (connector: Connector) => {
const wallet = await connector.getWalletClient()
const signer = walletClientToSigner(wallet)
const { jwtToken } = await authenticate(signer)

const newJwt = jwtDecode<JwtPayload>(jwtToken)
Expand All @@ -86,7 +87,7 @@ export default function useAccount(): AccountDetail {
: {}),
})
},
[jwt, authenticate, setAuthenticationToken, setCookie],
[authenticate, setCookie],
)

// Server side
Expand All @@ -98,6 +99,7 @@ export default function useAccount(): AccountDetail {
isConnected: !!jwt,
logout,
login,
sign,
}
}

Expand All @@ -108,5 +110,6 @@ export default function useAccount(): AccountDetail {
isConnected,
logout,
login,
sign,
}
}
6 changes: 6 additions & 0 deletions locales/en/components.json
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,12 @@
"title": "Sign in with your wallet",
"description": "Connect with one of the following options.",
"alternative": "Or sign in with"
},
"signature": {
"title": "Signature",
"sub-title": "Verify your account",
"description": "To complete the connection, you must sign a message in your wallet to verify that you are the owner of this account.",
"action": "Send message"
}
},
"back": "Go back",
Expand Down
6 changes: 6 additions & 0 deletions locales/es-mx/components.json
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,12 @@
"title": "Inicia sesión con tu Wallet",
"description": "Conéctate con alguna de las siguientes opciones:",
"alternative": "O inicia sesión con:"
},
"signature": {
"title": "Signature",
"sub-title": "Verify your account",
"description": "To complete the connection, you must sign a message in your wallet to verify that you are the owner of this account.",
"action": "Send message"
}
},
"back": "Volver",
Expand Down
6 changes: 6 additions & 0 deletions locales/ja/components.json
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,12 @@
"title": "ウォレットでサインインする",
"description": "次のいずれかのオプションを使用して接続します。",
"alternative": "または、"
},
"signature": {
"title": "Signature",
"sub-title": "Verify your account",
"description": "To complete the connection, you must sign a message in your wallet to verify that you are the owner of this account.",
"action": "Send message"
}
},
"back": "戻る",
Expand Down
6 changes: 6 additions & 0 deletions locales/zh-cn/components.json
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,12 @@
"title": "使用钱包登录",
"description": "使用以下选项之一进行连接。",
"alternative": "或使用"
},
"signature": {
"title": "Signature",
"sub-title": "Verify your account",
"description": "To complete the connection, you must sign a message in your wallet to verify that you are the owner of this account.",
"action": "Send message"
}
},
"back": "返回",
Expand Down
24 changes: 18 additions & 6 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ApolloProvider } from '@apollo/client'
import Bugsnag from '@bugsnag/js'
import BugsnagPluginReact from '@bugsnag/plugin-react'
import { Box, ChakraProvider } from '@chakra-ui/react'
import { Box, ChakraProvider, useDisclosure } from '@chakra-ui/react'
import { LiteflowProvider } from '@liteflow/react'
import { RainbowKitProvider, lightTheme } from '@rainbow-me/rainbowkit'
import '@rainbow-me/rainbowkit/styles.css'
Expand All @@ -22,7 +22,7 @@ import React, {
useMemo,
useState,
} from 'react'
import { Cookies, CookiesProvider } from 'react-cookie'
import { Cookies, CookiesProvider, useCookies } from 'react-cookie'
import {
WagmiConfig,
useDisconnect,
Expand All @@ -31,6 +31,7 @@ import {
import getClient from '../client'
import CartContext from '../components/CartContext'
import Footer from '../components/Footer/Footer'
import SignModal from '../components/Modal/Sign'
import Navbar from '../components/Navbar/Navbar'
import connectors from '../connectors'
import getEnvironment, { Environment, EnvironmentContext } from '../environment'
Expand Down Expand Up @@ -125,14 +126,18 @@ function AccountProvider({
onError,
}: PropsWithChildren<{ onError: (code: number) => void }>) {
const { LITEFLOW_API_KEY, BASE_URL } = useEnvironment()
const { login, jwtToken, logout } = useAccount()
const { jwtToken, login, logout } = useAccount()
const { disconnect } = useDisconnect()
const { isOpen, onOpen, onClose } = useDisclosure()
const [cookies] = useCookies<string, COOKIES>([COOKIE_JWT_TOKEN])

const { connector } = useWagmiAccount({
async onConnect({ connector }) {
if (!connector) return
try {
await login(connector)
// jwtToken from useAccount is null on refresh, so we need to check the cookies
if (!cookies[COOKIE_JWT_TOKEN]) onOpen()
} catch (e: any) {
disconnect()
}
Expand All @@ -145,12 +150,14 @@ function AccountProvider({
// handle change of account
useEffect(() => {
if (!connector) return
const handleLogin = () => login(connector)
const handleLogin = () => {
login(connector).then(onOpen).catch(onError)
}
connector.on('change', handleLogin)
return () => {
connector.off('change', handleLogin)
}
}, [connector, login])
}, [connector, login, onError, onOpen])

const client = useMemo(
// The client needs to be reset when the jwtToken changes but only on the client as the server will
Expand All @@ -166,7 +173,12 @@ function AccountProvider({
[jwtToken, onError, LITEFLOW_API_KEY, BASE_URL],
)

return <ApolloProvider client={client}>{children}</ApolloProvider>
return (
<>
<ApolloProvider client={client}>{children}</ApolloProvider>
<SignModal connector={connector} isOpen={isOpen} onClose={onClose} />
</>
)
}

export type MyAppProps = {
Expand Down
Loading