stacker.news/pages/wallet/index.js

503 lines
15 KiB
JavaScript
Raw Normal View History

2021-05-06 21:15:22 +00:00
import { useRouter } from 'next/router'
import { Checkbox, Form, Input, InputUserSuggest, SubmitButton } from '@/components/form'
2021-05-06 21:15:22 +00:00
import Link from 'next/link'
import Button from 'react-bootstrap/Button'
2021-10-28 19:59:53 +00:00
import { gql, useMutation, useQuery } from '@apollo/client'
import Qr, { QrSkeleton } from '@/components/qr'
import { CenterLayout } from '@/components/layout'
2021-05-13 13:28:38 +00:00
import InputGroup from 'react-bootstrap/InputGroup'
Wallet Logs (#994) * nwc wallet logs * persist logs in IndexedDB * Potential fix for empty error message * load logs limited to 5m ago from IDB * load logs from past via query param * Add 5m, 1h, 6h links for earlier logs * Show end of log * Clamp to logStart * Add log.module.css * Remove TODO about persistence * Use table for logs * <table> fixes bad format with fixed width and message overflow into start of next row * also using ---start of log--- instead of ---end of log--- now * removed time string in header nav * Rename .header to .logNav * Simply load all logs and remove navigation I realized the code for navigation was most likely premature optimization which even resulted in worse UX: Using the buttons to load logs from 5m, 1h, 6h ago sometimes meant that nothing happened at all since there were no logs from 5m, 1h, 6h ago. That's why I added a time string as "start of logs" so it's at least visible that it changed but that looked bad so I removed it. But all of this was not necessary: I can simply load all logs at once and then the user can scroll around however they like. I was worried that it would be bad for performance to load all logs at once since we might store a lot of logs but as mentioned, that's probably premature optimization. WHEN a lot of logs are stored AND this becomes a problem (What problem even? Slow page load?), THEN we can think about this. If page load ever becomes slow because of loading logs, we could probably simply not load the logs at page load but only when /wallet/logs is visited. But for now, this works fine. * Add follow checkbox * Create WalletLogs component * Embed wallet logs * Remove test error * Fix level padding * Add LNbits logs * Add logs for attaching LND and lnAddr * Use err.message || err.toString?.() consistently * Autowithdrawal logs * Use details from LND error * Don't log test invoice individually * Also refetch logs on error * Remove obsolete and annoying toasts * Replace scrollIntoView with scroll * Use constant embedded max-height * Fix missing width: 100% for embedded logs * Show full payment hash and preimage in logs * Also parse details from LND errors on autowithdrawal failures * Remove TODO * Fix accidental removal of wss:// check * Fix alignment of start marker and show empty if empty * Fix sendPayment loop * Split context in two
2024-04-03 22:27:21 +00:00
import { WithdrawlSkeleton } from '@/pages/withdrawals/[id]'
import { useMe } from '@/components/me'
2023-10-06 01:33:14 +00:00
import { useEffect, useState } from 'react'
2021-09-07 17:52:59 +00:00
import { requestProvider } from 'webln'
2023-07-24 18:35:05 +00:00
import Alert from 'react-bootstrap/Alert'
import { CREATE_WITHDRAWL, SEND_TO_LNADDR } from '@/fragments/wallet'
import { getGetServerSideProps } from '@/api/ssrApollo'
import { amountSchema, lnAddrSchema, withdrawlSchema } from '@/lib/validate'
import Nav from 'react-bootstrap/Nav'
import { BALANCE_LIMIT_MSATS, FAST_POLL_INTERVAL, SSR } from '@/lib/constants'
import { msatsToSats, numWithUnits } from '@/lib/format'
import styles from '@/components/user-header.module.css'
import HiddenWalletSummary from '@/components/hidden-wallet-summary'
import AccordianItem from '@/components/accordian-item'
import { lnAddrOptions } from '@/lib/lnurl'
import useDebounceCallback from '@/components/use-debounce-callback'
import { QrScanner } from '@yudiel/react-qr-scanner'
import CameraIcon from '@/svgs/camera-line.svg'
import { useShowModal } from '@/components/modal'
import { useField } from 'formik'
import { useToast } from '@/components/toast'
import { WalletLimitBanner } from '@/components/banners'
import Plug from '@/svgs/plug.svg'
import { decode } from 'bolt11'
2022-04-21 22:50:02 +00:00
export const getServerSideProps = getGetServerSideProps({ authRequired: true })
2021-05-06 21:15:22 +00:00
export default function Wallet () {
const router = useRouter()
if (router.query.type === 'fund') {
return (
<CenterLayout>
<FundForm />
</CenterLayout>
)
} else if (router.query.type?.includes('withdraw')) {
return (
<CenterLayout>
<WithdrawalForm />
</CenterLayout>
)
} else {
return (
<CenterLayout>
<YouHaveSats />
<WalletLimitBanner />
<WalletForm />
<WalletHistory />
</CenterLayout>
)
}
2021-05-06 21:15:22 +00:00
}
2021-07-15 16:42:02 +00:00
function YouHaveSats () {
const me = useMe()
const limitReached = me?.privates?.sats >= msatsToSats(BALANCE_LIMIT_MSATS)
2021-07-15 16:42:02 +00:00
return (
<h2 className={`${me ? 'visible' : 'invisible'} ${limitReached ? 'text-warning' : 'text-success'}`}>
you have{' '}
<span className='text-monospace'>{me && (
me.privates?.hideWalletBalance
? <HiddenWalletSummary />
: numWithUnits(me.privates?.sats, { abbreviate: false, format: true })
)}
</span>
2021-07-15 16:42:02 +00:00
</h2>
)
}
2021-12-16 20:17:50 +00:00
function WalletHistory () {
return (
Wallet Logs (#994) * nwc wallet logs * persist logs in IndexedDB * Potential fix for empty error message * load logs limited to 5m ago from IDB * load logs from past via query param * Add 5m, 1h, 6h links for earlier logs * Show end of log * Clamp to logStart * Add log.module.css * Remove TODO about persistence * Use table for logs * <table> fixes bad format with fixed width and message overflow into start of next row * also using ---start of log--- instead of ---end of log--- now * removed time string in header nav * Rename .header to .logNav * Simply load all logs and remove navigation I realized the code for navigation was most likely premature optimization which even resulted in worse UX: Using the buttons to load logs from 5m, 1h, 6h ago sometimes meant that nothing happened at all since there were no logs from 5m, 1h, 6h ago. That's why I added a time string as "start of logs" so it's at least visible that it changed but that looked bad so I removed it. But all of this was not necessary: I can simply load all logs at once and then the user can scroll around however they like. I was worried that it would be bad for performance to load all logs at once since we might store a lot of logs but as mentioned, that's probably premature optimization. WHEN a lot of logs are stored AND this becomes a problem (What problem even? Slow page load?), THEN we can think about this. If page load ever becomes slow because of loading logs, we could probably simply not load the logs at page load but only when /wallet/logs is visited. But for now, this works fine. * Add follow checkbox * Create WalletLogs component * Embed wallet logs * Remove test error * Fix level padding * Add LNbits logs * Add logs for attaching LND and lnAddr * Use err.message || err.toString?.() consistently * Autowithdrawal logs * Use details from LND error * Don't log test invoice individually * Also refetch logs on error * Remove obsolete and annoying toasts * Replace scrollIntoView with scroll * Use constant embedded max-height * Fix missing width: 100% for embedded logs * Show full payment hash and preimage in logs * Also parse details from LND errors on autowithdrawal failures * Remove TODO * Fix accidental removal of wss:// check * Fix alignment of start marker and show empty if empty * Fix sendPayment loop * Split context in two
2024-04-03 22:27:21 +00:00
<div className='d-flex flex-column text-center'>
<div>
<Link href='/satistics?inc=invoice,withdrawal' className='text-muted fw-bold text-underline'>
wallet history
</Link>
</div>
</div>
2021-12-16 20:17:50 +00:00
)
}
2021-05-06 21:15:22 +00:00
export function WalletForm () {
return (
2024-01-07 17:00:24 +00:00
<div className='align-items-center text-center pt-5 pb-4'>
<Link href='/wallet?type=fund'>
<Button variant='success'>fund</Button>
</Link>
<span className='mx-3 fw-bold text-muted'>or</span>
<Link href='/wallet?type=withdraw'>
<Button variant='success'>withdraw</Button>
</Link>
2024-01-07 17:00:24 +00:00
<div className='mt-5'>
<Link href='/settings/wallets'>
<Button variant='info'>attach wallets <Plug className='fill-white ms-1' width={16} height={16} /></Button>
</Link>
</div>
</div>
)
2021-05-06 21:15:22 +00:00
}
export function FundForm () {
2021-10-08 14:35:57 +00:00
const me = useMe()
const [showAlert, setShowAlert] = useState(true)
2021-05-06 21:15:22 +00:00
const router = useRouter()
2021-05-13 21:19:51 +00:00
const [createInvoice, { called, error }] = useMutation(gql`
2021-05-06 21:15:22 +00:00
mutation createInvoice($amount: Int!) {
2021-05-11 15:52:50 +00:00
createInvoice(amount: $amount) {
id
}
2021-05-06 21:15:22 +00:00
}`)
2021-10-08 14:35:57 +00:00
useEffect(() => {
2023-07-25 14:14:45 +00:00
setShowAlert(!window.localStorage.getItem('hideLnAddrAlert'))
2021-10-08 14:35:57 +00:00
}, [])
2021-05-13 21:19:51 +00:00
if (called && !error) {
2024-04-16 21:20:13 +00:00
return <QrSkeleton description status='generating' bolt11Info />
2021-05-06 21:15:22 +00:00
}
return (
2021-07-15 16:42:02 +00:00
<>
<YouHaveSats />
<WalletLimitBanner />
<div className='w-100 py-5'>
{me && showAlert &&
<Alert
variant='success' dismissible onClose={() => {
window.localStorage.setItem('hideLnAddrAlert', 'yep')
setShowAlert(false)
}}
>
You can also fund your account via lightning address with <strong>{`${me.name}@stacker.news`}</strong>
</Alert>}
<Form
initial={{
amount: 1000
}}
schema={amountSchema}
onSubmit={async ({ amount }) => {
const { data } = await createInvoice({ variables: { amount: Number(amount) } })
router.push(`/invoices/${data.createInvoice.id}`)
2021-10-08 14:35:57 +00:00
}}
>
<Input
label='amount'
name='amount'
required
autoFocus
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
<SubmitButton variant='success' className='mt-2'>generate invoice</SubmitButton>
</Form>
</div>
2021-12-16 20:17:50 +00:00
<WalletHistory />
2021-07-15 16:42:02 +00:00
</>
2021-05-06 21:15:22 +00:00
)
}
export function WithdrawalForm () {
const router = useRouter()
return (
<div className='w-100 d-flex flex-column align-items-center py-5'>
<YouHaveSats />
<Nav
className={styles.nav}
activeKey={router.query.type}
>
<Nav.Item>
<Link href='/wallet?type=withdraw' passHref legacyBehavior>
<Nav.Link eventKey='withdraw'>invoice</Nav.Link>
</Link>
</Nav.Item>
<Nav.Item>
<Link href='/wallet?type=lnurl-withdraw' passHref legacyBehavior>
<Nav.Link eventKey='lnurl-withdraw'>QR code</Nav.Link>
</Link>
</Nav.Item>
<Nav.Item>
<Link href='/wallet?type=lnaddr-withdraw' passHref legacyBehavior>
<Nav.Link eventKey='lnaddr-withdraw'>lightning address</Nav.Link>
</Link>
</Nav.Item>
</Nav>
<SelectedWithdrawalForm />
</div>
)
}
export function SelectedWithdrawalForm () {
const router = useRouter()
switch (router.query.type) {
case 'withdraw':
return <InvWithdrawal />
case 'lnurl-withdraw':
return <LnWithdrawal />
case 'lnaddr-withdraw':
return <LnAddrWithdrawal />
}
}
export function InvWithdrawal () {
2021-05-13 01:51:37 +00:00
const router = useRouter()
2021-09-07 17:52:59 +00:00
const me = useMe()
2021-05-12 23:04:19 +00:00
2021-10-28 19:59:53 +00:00
const [createWithdrawl, { called, error }] = useMutation(CREATE_WITHDRAWL)
2021-05-12 23:04:19 +00:00
const maxFeeDefault = me?.privates?.withdrawMaxFeeDefault
2022-11-06 17:28:58 +00:00
useEffect(() => {
async function effect () {
try {
const provider = await requestProvider()
const { paymentRequest: invoice } = await provider.makeInvoice({
defaultMemo: `Withdrawal for @${me.name} on SN`,
maximumAmount: Math.max(me.privates?.sats - maxFeeDefault, 0)
2022-11-06 17:28:58 +00:00
})
const { data } = await createWithdrawl({ variables: { invoice, maxFee: maxFeeDefault } })
2022-11-06 17:28:58 +00:00
router.push(`/withdrawals/${data.createWithdrawl.id}`)
} catch (e) {
console.log(e.message)
}
2021-09-07 17:52:59 +00:00
}
2022-11-06 17:28:58 +00:00
effect()
2021-09-07 17:52:59 +00:00
}, [])
2021-05-13 21:19:51 +00:00
if (called && !error) {
return <WithdrawlSkeleton status='sending' />
}
2021-05-12 23:04:19 +00:00
return (
<>
<Form
autoComplete='off'
2021-05-12 23:04:19 +00:00
initial={{
2021-05-13 01:51:37 +00:00
invoice: '',
maxFee: maxFeeDefault
2021-05-12 23:04:19 +00:00
}}
2023-02-08 19:38:04 +00:00
schema={withdrawlSchema}
2021-05-12 23:04:19 +00:00
onSubmit={async ({ invoice, maxFee }) => {
2021-05-13 01:51:37 +00:00
const { data } = await createWithdrawl({ variables: { invoice, maxFee: Number(maxFee) } })
2021-08-19 21:42:21 +00:00
router.push(`/withdrawals/${data.createWithdrawl.id}`)
2021-05-12 23:04:19 +00:00
}}
>
<Input
label='invoice'
name='invoice'
required
autoFocus
2023-05-11 19:34:42 +00:00
clear
append={<InvoiceScanner fieldName='invoice' />}
2021-05-12 23:04:19 +00:00
/>
<Input
label='max fee'
name='maxFee'
required
2021-05-13 21:19:51 +00:00
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
2021-05-12 23:04:19 +00:00
/>
2021-08-19 21:42:21 +00:00
<SubmitButton variant='success' className='mt-2'>withdraw</SubmitButton>
2021-05-12 23:04:19 +00:00
</Form>
</>
)
2021-05-06 21:15:22 +00:00
}
2021-10-28 19:59:53 +00:00
function InvoiceScanner ({ fieldName }) {
const showModal = useShowModal()
const [,, helpers] = useField(fieldName)
const toaster = useToast()
return (
<InputGroup.Text
style={{ cursor: 'pointer' }}
onClick={() => {
showModal(onClose => {
return (
<QrScanner
onDecode={(result) => {
if (result.split('lightning=')[1]) {
helpers.setValue(result.split('lightning=')[1].split(/[&?]/)[0].toLowerCase())
} else if (decode(result.replace(/^lightning:/, ''))) {
helpers.setValue(result.replace(/^lightning:/, '').toLowerCase())
} else {
throw new Error('Not a proper lightning payment request')
}
onClose()
}}
onError={(error) => {
if (error instanceof DOMException) {
console.log(error)
} else {
toaster.danger('qr scan: ' + error?.message || error?.toString?.())
}
onClose()
}}
/>
)
})
}}
>
<CameraIcon
height={20} width={20} fill='var(--bs-body-color)'
/>
</InputGroup.Text>
)
}
2021-10-28 19:59:53 +00:00
function LnQRWith ({ k1, encodedUrl }) {
const router = useRouter()
const query = gql`
{
lnWith(k1: "${k1}") {
withdrawalId
k1
}
}`
const { data } = useQuery(query, SSR ? {} : { pollInterval: FAST_POLL_INTERVAL, nextFetchPolicy: 'cache-and-network' })
2021-10-28 19:59:53 +00:00
if (data?.lnWith?.withdrawalId) {
router.push(`/withdrawals/${data.lnWith.withdrawalId}`)
}
2023-01-18 18:49:20 +00:00
return <Qr value={encodedUrl} status='waiting for you' />
2021-10-28 19:59:53 +00:00
}
export function LnWithdrawal () {
// query for challenge
2022-11-06 17:28:58 +00:00
const [createWith, { data, error }] = useMutation(gql`
mutation createWith {
2021-10-28 19:59:53 +00:00
createWith {
k1
encodedUrl
}
}`)
2023-12-14 17:30:51 +00:00
const toaster = useToast()
2021-10-28 19:59:53 +00:00
2022-11-06 17:28:58 +00:00
useEffect(() => {
2023-12-14 17:30:51 +00:00
createWith().catch(e => {
toaster.danger('withdrawal creation: ' + e?.message || e?.toString?.())
2023-12-14 17:30:51 +00:00
})
}, [createWith, toaster])
2021-10-28 19:59:53 +00:00
2023-12-14 17:30:51 +00:00
if (error) return <QrSkeleton status='error' />
2021-10-28 19:59:53 +00:00
if (!data) {
2023-01-18 18:49:20 +00:00
return <QrSkeleton status='generating' />
2021-10-28 19:59:53 +00:00
}
return <LnQRWith {...data.createWith} />
}
2022-01-23 17:21:55 +00:00
export function LnAddrWithdrawal () {
const me = useMe()
2022-01-23 17:21:55 +00:00
const router = useRouter()
const [sendToLnAddr, { called, error }] = useMutation(SEND_TO_LNADDR)
const defaultOptions = { min: 1 }
const [addrOptions, setAddrOptions] = useState(defaultOptions)
const [formSchema, setFormSchema] = useState(lnAddrSchema())
const maxFeeDefault = me?.privates?.withdrawMaxFeeDefault
2022-01-23 17:21:55 +00:00
2023-10-06 01:33:14 +00:00
const onAddrChange = useDebounceCallback(async (formik, e) => {
2023-10-06 02:14:57 +00:00
if (!e?.target?.value) {
setAddrOptions(defaultOptions)
setFormSchema(lnAddrSchema())
return
}
let options
try {
options = await lnAddrOptions(e.target.value)
setAddrOptions(options)
setFormSchema(lnAddrSchema(options))
} catch (e) {
console.log(e)
setAddrOptions(defaultOptions)
setFormSchema(lnAddrSchema())
}
2023-10-06 20:01:51 +00:00
}, 500, [setAddrOptions, setFormSchema])
2022-01-23 17:21:55 +00:00
return (
<>
{called && !error && <WithdrawlSkeleton status='sending' />}
2022-01-23 17:21:55 +00:00
<Form
// hide/show instead of add/remove from react tree to avoid re-initializing the form state on error
style={{ display: !(called && !error) ? 'block' : 'none' }}
2022-01-23 17:21:55 +00:00
initial={{
addr: '',
amount: 1,
maxFee: maxFeeDefault,
comment: '',
identifier: false,
name: '',
email: ''
2022-01-23 17:21:55 +00:00
}}
schema={formSchema}
onSubmit={async ({ amount, maxFee, ...values }) => {
const { data } = await sendToLnAddr({
variables: {
amount: Number(amount),
maxFee: Number(maxFee),
...values
}
})
2022-01-23 17:21:55 +00:00
router.push(`/withdrawals/${data.sendToLnAddr.id}`)
}}
>
<InputUserSuggest
2022-01-23 17:21:55 +00:00
label='lightning address'
name='addr'
required
autoFocus
onChange={onAddrChange}
transformUser={user => ({ ...user, name: `${user.name}@stacker.news` })}
2023-11-21 23:32:22 +00:00
selectWithTab
filterUsers={(query) => {
const [, domain] = query.split('@')
return !domain || 'stacker.news'.startsWith(domain)
}}
2022-01-23 17:21:55 +00:00
/>
<Input
label='amount'
name='amount'
type='number'
step={10}
2022-01-23 17:21:55 +00:00
required
min={addrOptions.min}
max={addrOptions.max}
2022-01-23 17:21:55 +00:00
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
<Input
label='max fee'
name='maxFee'
type='number'
step={10}
2022-01-23 17:21:55 +00:00
required
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
{(addrOptions?.commentAllowed || addrOptions?.payerData) &&
<div className='my-3 border border-3 rounded'>
<div className='p-3'>
<AccordianItem
show
header={<div style={{ fontWeight: 'bold', fontSize: '92%' }}>attach</div>}
body={
<>
{addrOptions.commentAllowed &&
<Input
as='textarea'
label={<>comment <small className='text-muted ms-2'>optional</small></>}
name='comment'
maxLength={addrOptions.commentAllowed}
/>}
{addrOptions.payerData?.identifier &&
<Checkbox
name='identifier'
required={addrOptions.payerData.identifier.mandatory}
label={
<>your {me?.name}@stacker.news identifier
{!addrOptions.payerData.identifier.mandatory &&
<>{' '}<small className='text-muted ms-2'>optional</small></>}
</>
}
/>}
{addrOptions.payerData?.name &&
<Input
name='name'
required={addrOptions.payerData.name.mandatory}
label={
<>name{!addrOptions.payerData.name.mandatory &&
<>{' '}<small className='text-muted ms-2'>optional</small></>}
</>
}
/>}
{addrOptions.payerData?.email &&
<Input
name='email'
required={addrOptions.payerData.email.mandatory}
label={
<>
email{!addrOptions.payerData.email.mandatory &&
<>{' '}<small className='text-muted ms-2'>optional</small></>}
</>
}
/>}
</>
}
/>
</div>
</div>}
2022-01-23 17:21:55 +00:00
<SubmitButton variant='success' className='mt-2'>send</SubmitButton>
</Form>
</>
)
}