Use SSR for wallets (#2397)

* Use SSR for wallet forms

* Fix back/forward navigation with useData hook

* Fix protocol fallback not working with shallow routing

* Fix wallet refetch

* Replace useEffect for default selection with smart link

* Remove unused useWalletQuery

* Move server2client wallet transform into single function

* Add comment about graphql-tag fragment warning

* Check if wallet not found

* Handle wallet is sometimes null on back or forward navigation
This commit is contained in:
ekzyis 2025-08-10 19:15:40 +02:00 committed by GitHub
parent abfe54125a
commit 21a9696ea0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 107 additions and 99 deletions

View File

@ -1,20 +1,33 @@
import { getGetServerSideProps } from '@/api/ssrApollo' import { getGetServerSideProps } from '@/api/ssrApollo'
import { useData } from '@/components/use-data'
import { WalletForms as WalletFormsComponent } from '@/wallets/client/components' import { WalletForms as WalletFormsComponent } from '@/wallets/client/components'
import { WALLET } from '@/wallets/client/fragments'
import { useDecryptedWallet } from '@/wallets/client/hooks'
import { unurlify } from '@/wallets/lib/util' import { unurlify } from '@/wallets/lib/util'
import { useParams } from 'next/navigation' import { useQuery } from '@apollo/client'
import { useRouter } from 'next/router'
export const getServerSideProps = getGetServerSideProps({ authRequired: true }) const variablesFunc = params => {
const id = Number(params.slug[0])
return !Number.isNaN(id) ? { id } : { name: unurlify(params.slug[0]) }
}
export const getServerSideProps = getGetServerSideProps({ query: WALLET, variables: variablesFunc, authRequired: true })
export default function WalletForms () { export default function WalletForms ({ ssrData }) {
const params = useParams() const router = useRouter()
const walletName = unurlify(params.slug[0]) const variables = variablesFunc(router.query)
// this will print the following warning in the console:
// Warning: fragment with name WalletTemplateFields already exists.
// graphql-tag enforces all fragment names across your application to be unique
// this is not a problem because the warning is only meant to avoid overwriting fragments but we're reusing it
const { data, refetch } = useQuery(WALLET, { variables })
const dat = useData(data, ssrData)
// if the wallet name is a number, we are showing a configured wallet const decryptedWallet = useDecryptedWallet(dat?.wallet)
// otherwise, we are showing a template const wallet = decryptedWallet ?? ssrData?.wallet
const isNumber = !Number.isNaN(Number(walletName)) if (!wallet) {
if (isNumber) { return null
return <WalletFormsComponent id={Number(walletName)} />
} }
return <WalletFormsComponent name={walletName} /> return <WalletFormsComponent wallet={wallet} refetch={refetch} />
} }

View File

@ -7,7 +7,7 @@ import Link from 'next/link'
import RecvIcon from '@/svgs/arrow-left-down-line.svg' import RecvIcon from '@/svgs/arrow-left-down-line.svg'
import SendIcon from '@/svgs/arrow-right-up-line.svg' import SendIcon from '@/svgs/arrow-right-up-line.svg'
import DragIcon from '@/svgs/draggable.svg' import DragIcon from '@/svgs/draggable.svg'
import { useWalletImage, useWalletSupport, useWalletStatus, WalletStatus } from '@/wallets/client/hooks' import { useWalletImage, useWalletSupport, useWalletStatus, WalletStatus, useProtocolTemplates } from '@/wallets/client/hooks'
import { isWallet, urlify, walletDisplayName } from '@/wallets/lib/util' import { isWallet, urlify, walletDisplayName } from '@/wallets/lib/util'
import { Draggable } from '@/wallets/client/components' import { Draggable } from '@/wallets/client/components'
@ -56,8 +56,14 @@ export function WalletCard ({ wallet, draggable = false, index, ...props }) {
function WalletLink ({ wallet, children }) { function WalletLink ({ wallet, children }) {
const support = useWalletSupport(wallet) const support = useWalletSupport(wallet)
const sendRecvParam = support.send ? 'send' : 'receive' const protocols = useProtocolTemplates(wallet)
const href = '/wallets' + (isWallet(wallet) ? `/${wallet.id}` : `/${urlify(wallet.name)}`) + `/${sendRecvParam}` const firstSend = protocols.find(p => p.send)
const firstRecv = protocols.find(p => !p.send)
let href = '/wallets'
href += isWallet(wallet) ? `/${wallet.id}` : `/${urlify(wallet.name)}`
href += support.send ? `/send/${urlify(firstSend.name)}` : `/receive/${urlify(firstRecv.name)}`
return <Link href={href}>{children}</Link> return <Link href={href}>{children}</Link>
} }

View File

@ -1,4 +1,4 @@
import { useEffect, useCallback, useMemo, createContext, useContext } from 'react' import { useCallback, useMemo, createContext, useContext } from 'react'
import { Button, InputGroup, Nav } from 'react-bootstrap' import { Button, InputGroup, Nav } from 'react-bootstrap'
import Link from 'next/link' import Link from 'next/link'
import { useParams, usePathname } from 'next/navigation' import { useParams, usePathname } from 'next/navigation'
@ -9,7 +9,7 @@ import styles from '@/styles/wallet.module.css'
import navStyles from '@/styles/nav.module.css' import navStyles from '@/styles/nav.module.css'
import { Checkbox, Form, Input, PasswordInput, SubmitButton } from '@/components/form' import { Checkbox, Form, Input, PasswordInput, SubmitButton } from '@/components/form'
import CancelButton from '@/components/cancel-button' import CancelButton from '@/components/cancel-button'
import { useWalletProtocolUpsert, useWalletProtocolRemove, useWalletQuery, TemplateLogsProvider } from '@/wallets/client/hooks' import { useWalletProtocolUpsert, useWalletProtocolRemove, useProtocolTemplates, TemplateLogsProvider } from '@/wallets/client/hooks'
import { useToast } from '@/components/toast' import { useToast } from '@/components/toast'
import Text from '@/components/text' import Text from '@/components/text'
import Info from '@/components/info' import Info from '@/components/info'
@ -17,11 +17,7 @@ import classNames from 'classnames'
const WalletFormsContext = createContext() const WalletFormsContext = createContext()
export function WalletForms ({ id, name }) { export function WalletForms ({ wallet, refetch }) {
// TODO(wallet-v2): handle loading and error states
const { data, refetch } = useWalletQuery({ name, id })
const wallet = data?.wallet
return ( return (
<WalletLayout> <WalletLayout>
<div className={styles.form}> <div className={styles.form}>
@ -81,9 +77,14 @@ function WalletFormSelector () {
} }
function WalletSendRecvSelector () { function WalletSendRecvSelector () {
const wallet = useWallet()
const path = useWalletPathname() const path = useWalletPathname()
const protocols = useProtocolTemplates(wallet)
const selected = useSendRecvParam() const selected = useSendRecvParam()
const firstSend = protocols.find(p => p.send)
const firstRecv = protocols.find(p => !p.send)
// TODO(wallet-v2): if you click a nav link again, it will update the URL // TODO(wallet-v2): if you click a nav link again, it will update the URL
// but not run the effect again to select the first protocol by default // but not run the effect again to select the first protocol by default
return ( return (
@ -93,12 +94,12 @@ function WalletSendRecvSelector () {
activeKey={selected} activeKey={selected}
> >
<Nav.Item> <Nav.Item>
<Link href={`/${path}/send`} passHref legacyBehavior replace> <Link href={`/${path}/send${firstSend ? `/${urlify(firstSend.name)}` : ''}`} passHref legacyBehavior replace>
<Nav.Link className='ps-3' eventKey='send'>SEND</Nav.Link> <Nav.Link className='ps-3' eventKey='send'>SEND</Nav.Link>
</Link> </Link>
</Nav.Item> </Nav.Item>
<Nav.Item> <Nav.Item>
<Link href={`/${path}/receive`} passHref legacyBehavior replace> <Link href={`/${path}/receive${firstRecv ? `/${urlify(firstRecv.name)}` : ''}`} passHref legacyBehavior replace>
<Nav.Link className='ps-3' eventKey='receive'>RECEIVE</Nav.Link> <Nav.Link className='ps-3' eventKey='receive'>RECEIVE</Nav.Link>
</Link> </Link>
</Nav.Item> </Nav.Item>
@ -109,17 +110,11 @@ function WalletSendRecvSelector () {
function WalletProtocolSelector () { function WalletProtocolSelector () {
const walletPath = useWalletPathname() const walletPath = useWalletPathname()
const sendRecvParam = useSendRecvParam() const sendRecvParam = useSendRecvParam()
const selected = useWalletProtocolParam()
const path = `${walletPath}/${sendRecvParam}` const path = `${walletPath}/${sendRecvParam}`
const protocols = useWalletProtocols() const wallet = useWallet()
const selected = useWalletProtocolParam() const protocols = useProtocolTemplates(wallet).filter(p => sendRecvParam === 'send' ? p.send : !p.send)
const router = useRouter()
useEffect(() => {
if (!selected && protocols.length > 0) {
router.replace(`/${path}/${urlify(protocols[0].name)}`, null, { shallow: true })
}
}, [path])
if (protocols.length === 0) { if (protocols.length === 0) {
// TODO(wallet-v2): let user know how to request support if the wallet actually does support sending // TODO(wallet-v2): let user know how to request support if the wallet actually does support sending
@ -179,7 +174,7 @@ function WalletProtocolForm () {
return return
} }
// we just created a new user wallet from a template // we just created a new user wallet from a template
router.replace(`/wallets/${upsert.id}/${sendRecvParam}`, null, { shallow: true }) router.replace(`/wallets/${upsert.id}/${sendRecvParam}/${urlify(protocol.name)}`, null, { shallow: true })
toaster.success('wallet attached', { persistOnNavigate: true }) toaster.success('wallet attached', { persistOnNavigate: true })
}, [upsertWalletProtocol, toaster, wallet, router]) }, [upsertWalletProtocol, toaster, wallet, router])
@ -303,17 +298,6 @@ function useWalletProtocolParam () {
return name ? unurlify(name) : null return name ? unurlify(name) : null
} }
function useWalletProtocols () {
const wallet = useWallet()
const sendRecvParam = useSendRecvParam()
if (!sendRecvParam) return []
const protocolFilter = p => sendRecvParam === 'send' ? p.send : !p.send
return isWallet(wallet)
? wallet.template.protocols.filter(protocolFilter)
: wallet.protocols.filter(protocolFilter)
}
function useSelectedProtocol () { function useSelectedProtocol () {
const wallet = useWallet() const wallet = useWallet()
const sendRecvParam = useSendRecvParam() const sendRecvParam = useSendRecvParam()

View File

@ -1,5 +1,4 @@
import { import {
WALLET,
UPSERT_WALLET_RECEIVE_BLINK, UPSERT_WALLET_RECEIVE_BLINK,
UPSERT_WALLET_RECEIVE_CLN_REST, UPSERT_WALLET_RECEIVE_CLN_REST,
UPSERT_WALLET_RECEIVE_LIGHTNING_ADDRESS, UPSERT_WALLET_RECEIVE_LIGHTNING_ADDRESS,
@ -55,8 +54,7 @@ export function useWalletsQuery () {
Promise.all( Promise.all(
query.data?.wallets.map(w => decryptWallet(w)) query.data?.wallets.map(w => decryptWallet(w))
) )
.then(wallets => wallets.map(protocolCheck)) .then(wallets => wallets.map(server2Client))
.then(wallets => wallets.map(undoFieldAlias))
.then(wallets => { .then(wallets => {
setWallets(wallets) setWallets(wallets)
setError(null) setError(null)
@ -79,7 +77,38 @@ export function useWalletsQuery () {
}), [query, error, wallets]) }), [query, error, wallets])
} }
function protocolCheck (wallet) { function useRefetchOnChange (refetch) {
const { me } = useMe()
const walletsUpdatedAt = useWalletsUpdatedAt()
useEffect(() => {
if (!me?.id) return
refetch()
}, [refetch, me?.id, walletsUpdatedAt])
}
export function useDecryptedWallet (wallet) {
const { decryptWallet, ready } = useWalletDecryption()
const [decryptedWallet, setDecryptedWallet] = useState(server2Client(wallet))
useEffect(() => {
if (!ready || !wallet) return
decryptWallet(wallet)
.then(server2Client)
.then(wallet => setDecryptedWallet(wallet))
.catch(err => {
console.error('failed to decrypt wallet:', err)
})
}, [decryptWallet, wallet, ready])
return decryptedWallet
}
function server2Client (wallet) {
// some protocols require a specific client environment
// e.g. WebLN requires a browser extension
function checkProtocolAvailability (wallet) {
if (isTemplate(wallet)) return wallet if (isTemplate(wallet)) return wallet
const protocols = wallet.protocols.map(protocol => { const protocols = wallet.protocols.map(protocol => {
@ -98,12 +127,12 @@ function protocolCheck (wallet) {
receive: !receiveEnabled ? WalletStatus.DISABLED : wallet.receive, receive: !receiveEnabled ? WalletStatus.DISABLED : wallet.receive,
protocols protocols
} }
} }
function undoFieldAlias ({ id, ...wallet }) {
// Just like for encrypted fields, we have to use a field alias for the name field of templates // Just like for encrypted fields, we have to use a field alias for the name field of templates
// because of https://github.com/graphql/graphql-js/issues/53. // because of https://github.com/graphql/graphql-js/issues/53.
// We undo this here so this only affects the GraphQL layer but not the rest of the code. // We undo this here so this only affects the GraphQL layer but not the rest of the code.
function undoFieldAlias ({ id, ...wallet }) {
if (isTemplate(wallet)) { if (isTemplate(wallet)) {
return { ...wallet, name: id } return { ...wallet, name: id }
} }
@ -112,42 +141,9 @@ function undoFieldAlias ({ id, ...wallet }) {
const { id: templateId, ...template } = wallet.template const { id: templateId, ...template } = wallet.template
return { id, ...wallet, template: { name: templateId, ...template } } return { id, ...wallet, template: { name: templateId, ...template } }
} }
function useRefetchOnChange (refetch) { return wallet ? undoFieldAlias(checkProtocolAvailability(wallet)) : wallet
const { me } = useMe()
const walletsUpdatedAt = useWalletsUpdatedAt()
useEffect(() => {
if (!me?.id) return
refetch()
}, [refetch, me?.id, walletsUpdatedAt])
}
export function useWalletQuery ({ id, name }) {
const { me } = useMe()
const query = useQuery(WALLET, { variables: { id, name }, skip: !me })
const [wallet, setWallet] = useState(null)
const { decryptWallet, ready } = useWalletDecryption()
useEffect(() => {
if (!query.data?.wallet || !ready) return
decryptWallet(query.data?.wallet)
.then(protocolCheck)
.then(undoFieldAlias)
.then(wallet => setWallet(wallet))
.catch(err => {
console.error('failed to decrypt wallet:', err)
})
}, [query.data, decryptWallet, ready])
return useMemo(() => ({
...query,
loading: !wallet,
data: wallet ? { wallet } : null
}), [query, wallet])
} }
export function useWalletProtocolUpsert (wallet, protocol) { export function useWalletProtocolUpsert (wallet, protocol) {

View File

@ -53,3 +53,9 @@ export function useWalletsUpdatedAt () {
const { me } = useMe() const { me } = useMe()
return me?.privates?.walletsUpdatedAt return me?.privates?.walletsUpdatedAt
} }
export function useProtocolTemplates (wallet) {
return useMemo(() => {
return isWallet(wallet) ? wallet.template.protocols : wallet.protocols
}, [wallet])
}

View File

@ -1,6 +1,7 @@
import * as yup from 'yup' import * as yup from 'yup'
import wallets from '@/wallets/lib/wallets.json' import wallets from '@/wallets/lib/wallets.json'
import protocols from '@/wallets/lib/protocols' import protocols from '@/wallets/lib/protocols'
import { SSR } from '@/lib/constants'
function walletJson (name) { function walletJson (name) {
return wallets.find(wallet => wallet.name === name) return wallets.find(wallet => wallet.name === name)
@ -88,7 +89,7 @@ export function protocolFields ({ name, send }) {
export function protocolAvailable ({ name, send }) { export function protocolAvailable ({ name, send }) {
const { isAvailable } = protocol({ name, send }) const { isAvailable } = protocol({ name, send })
if (typeof isAvailable === 'function') { if (!SSR && typeof isAvailable === 'function') {
return isAvailable() return isAvailable()
} }

View File

@ -96,6 +96,8 @@ async function wallet (parent, { id, name }, { me, models }) {
protocols: true protocols: true
} }
}) })
if (!wallet) throw new GqlInputError('wallet not found')
return mapWalletResolveTypes(wallet) return mapWalletResolveTypes(wallet)
} }