stacker.news/pages/withdraw.js

389 lines
12 KiB
JavaScript
Raw Normal View History

import { getGetServerSideProps } from '@/api/ssrApollo'
import { CenterLayout } from '@/components/layout'
2021-05-06 16:15:22 -05:00
import Link from 'next/link'
import { useRouter } from 'next/router'
import { InputGroup, Nav } from 'react-bootstrap'
import styles from '@/components/user-header.module.css'
2021-10-28 14:59:53 -05:00
import { gql, useMutation, useQuery } from '@apollo/client'
import { CREATE_WITHDRAWL, SEND_TO_LNADDR } from '@/fragments/wallet'
import { requestProvider } from 'webln'
import { useEffect, useState } from 'react'
import { useMe } from '@/components/me'
import { WithdrawlSkeleton } from './withdrawals/[id]'
import { Checkbox, Form, Input, InputUserSuggest, SubmitButton } from '@/components/form'
import { lnAddrSchema, withdrawlSchema } from '@/lib/validate'
import { useShowModal } from '@/components/modal'
import { useField } from 'formik'
import { useToast } from '@/components/toast'
import { Scanner } from '@yudiel/react-qr-scanner'
import { decode } from 'bolt11'
import CameraIcon from '@/svgs/camera-line.svg'
import { FAST_POLL_INTERVAL, SSR } from '@/lib/constants'
import Qr, { QrSkeleton } from '@/components/qr'
import useDebounceCallback from '@/components/use-debounce-callback'
import { lnAddrOptions } from '@/lib/lnurl'
import AccordianItem from '@/components/accordian-item'
import { numWithUnits } from '@/lib/format'
2022-04-21 17:50:02 -05:00
export const getServerSideProps = getGetServerSideProps({ authRequired: true })
2021-05-06 16:15:22 -05:00
export default function Withdraw () {
2021-07-15 11:42:02 -05:00
return (
<CenterLayout>
<WithdrawForm />
</CenterLayout>
2021-07-15 11:42:02 -05:00
)
}
function WithdrawForm () {
const router = useRouter()
const { me } = useMe()
return (
<div className='w-100 d-flex flex-column align-items-center py-5'>
<h2 className='text-start ms-1 ms-md-3'>
<div className='text-monospace'>
{numWithUnits(me?.privates?.sats - me?.privates?.credits, { abbreviate: false, format: true, unitSingular: 'sats', unitPlural: 'sats' })}
</div>
</h2>
<Nav
className={styles.nav}
activeKey={router.query.type ?? 'invoice'}
>
<Nav.Item>
<Link href='/withdraw' passHref legacyBehavior>
<Nav.Link eventKey='invoice'>invoice</Nav.Link>
</Link>
</Nav.Item>
<Nav.Item>
<Link href='/withdraw?type=lnurl' passHref legacyBehavior>
<Nav.Link eventKey='lnurl'>QR code</Nav.Link>
</Link>
</Nav.Item>
<Nav.Item>
<Link href='/withdraw?type=lnaddr' passHref legacyBehavior>
<Nav.Link eventKey='lnaddr'>lightning address</Nav.Link>
</Link>
</Nav.Item>
</Nav>
<SelectedWithdrawalForm />
</div>
)
}
export function SelectedWithdrawalForm () {
const router = useRouter()
switch (router.query.type) {
case 'lnurl':
return <LnurlWithdrawal />
case 'lnaddr':
return <LnAddrWithdrawal />
default:
return <InvWithdrawal />
}
}
export function InvWithdrawal () {
2021-05-12 20:51:37 -05:00
const router = useRouter()
Account Switching (#644) * WIP: Account switching * Fix empty USER query ANON_USER_ID was undefined and thus the query for @anon had no variables. * Apply multiAuthMiddleware in /api/graphql * Fix 'you must be logged in' query error on switch to anon * Add smart 'switch account' button "smart" means that it only shows if there are accounts to which one can switch * Fix multiAuth not set in backend * Comment fixes, minor changes * Use fw-bold instead of 'selected' * Close dropdown and offcanvas Inside a dropdown, we can rely on autoClose but need to wrap the buttons with <Dropdown.Item> for that to work. For the offcanvas, we need to pass down handleClose. * Use button to add account * Some pages require hard reload on account switch * Reinit settings form on account switch * Also don't refetch WalletHistory * Formatting * Use width: fit-content for standalone SignUpButton * Remove unused className * Use fw-bold and text-underline on selected * Fix inconsistent padding of login buttons * Fix duplicate redirect from /settings on anon switch * Never throw during refetch * Throw errors which extend GraphQLError * Only use meAnonSats if logged out * Use reactive variable for meAnonSats The previous commit broke the UI update after anon zaps because we actually updated item.meSats in the cache and not item.meAnonSats. Updating item.meAnonSats was not possible because it's a local field. For that, one needs to use reactive variables. We do this now and thus also don't need the useEffect hack in item-info.js anymore. * Switch to new user * Fix missing cleanup during logout If we logged in but never switched to any other account, the 'multi_auth.user-id' cookie was not set. This meant that during logout, the other 'multi_auth.*' cookies were not deleted. This broke the account switch modal. This is fixed by setting the 'multi_auth.user-id' cookie on login. Additionally, we now cleanup if cookie pointer OR session is set (instead of only if both are set). * Fix comments in middleware * Remove unnecessary effect dependencies setState is stable and thus only noise in effect dependencies * Show but disable unavailable auth methods * make signup button consistent with others * Always reload page on switch * refine account switch styling * logout barrier --------- Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-09-12 20:05:11 +02:00
const { me } = useMe()
2021-05-12 18:04:19 -05:00
2021-10-28 14:59:53 -05:00
const [createWithdrawl, { called, error }] = useMutation(CREATE_WITHDRAWL)
2021-05-12 18:04:19 -05:00
const maxFeeDefault = me?.privates?.withdrawMaxFeeDefault
2022-11-06 11:28:58 -06: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 11:28:58 -06:00
})
const { data } = await createWithdrawl({ variables: { invoice, maxFee: maxFeeDefault } })
2022-11-06 11:28:58 -06:00
router.push(`/withdrawals/${data.createWithdrawl.id}`)
} catch (e) {
console.log(e.message)
}
2021-09-07 12:52:59 -05:00
}
2022-11-06 11:28:58 -06:00
effect()
2021-09-07 12:52:59 -05:00
}, [])
2021-05-13 16:19:51 -05:00
if (called && !error) {
return <WithdrawlSkeleton status='sending' />
}
2021-05-12 18:04:19 -05:00
return (
<>
<Form
autoComplete='off'
2021-05-12 18:04:19 -05:00
initial={{
2021-05-12 20:51:37 -05:00
invoice: '',
maxFee: maxFeeDefault
2021-05-12 18:04:19 -05:00
}}
2023-02-08 13:38:04 -06:00
schema={withdrawlSchema}
2021-05-12 18:04:19 -05:00
onSubmit={async ({ invoice, maxFee }) => {
2021-05-12 20:51:37 -05:00
const { data } = await createWithdrawl({ variables: { invoice, maxFee: Number(maxFee) } })
2021-08-19 16:42:21 -05:00
router.push(`/withdrawals/${data.createWithdrawl.id}`)
2021-05-12 18:04:19 -05:00
}}
>
<Input
label='invoice'
name='invoice'
required
autoFocus
2023-05-11 14:34:42 -05:00
clear
append={<InvoiceScanner fieldName='invoice' />}
2021-05-12 18:04:19 -05:00
/>
<Input
label='max fee'
name='maxFee'
required
2021-05-13 16:19:51 -05:00
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
2021-05-12 18:04:19 -05:00
/>
<div className='d-flex justify-content-end mt-4'>
<SubmitButton variant='success'>withdraw</SubmitButton>
</div>
2021-05-12 18:04:19 -05:00
</Form>
</>
)
2021-05-06 16:15:22 -05:00
}
2021-10-28 14:59:53 -05:00
function InvoiceScanner ({ fieldName }) {
const showModal = useShowModal()
const [,, helpers] = useField(fieldName)
const toaster = useToast()
return (
<InputGroup.Text
style={{ cursor: 'pointer' }}
onClick={() => {
showModal(onClose => {
return (
2024-10-12 17:48:38 -05:00
<Scanner
formats={['qr_code']}
onScan={([{ rawValue: result }]) => {
result = result.toLowerCase()
if (result.split('lightning=')[1]) {
2024-10-12 17:48:38 -05:00
helpers.setValue(result.split('lightning=')[1].split(/[&?]/)[0])
} else if (decode(result.replace(/^lightning:/, ''))) {
2024-10-12 17:48:38 -05:00
helpers.setValue(result.replace(/^lightning:/, ''))
} else {
throw new Error('Not a proper lightning payment request')
}
onClose()
}}
2024-10-12 17:48:38 -05:00
styles={{
video: {
aspectRatio: '1 / 1'
}
}}
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 14:59:53 -05: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 14:59:53 -05:00
if (data?.lnWith?.withdrawalId) {
router.push(`/withdrawals/${data.lnWith.withdrawalId}`)
}
2023-01-18 12:49:20 -06:00
return <Qr value={encodedUrl} status='waiting for you' />
2021-10-28 14:59:53 -05:00
}
export function LnurlWithdrawal () {
2021-10-28 14:59:53 -05:00
// query for challenge
2022-11-06 11:28:58 -06:00
const [createWith, { data, error }] = useMutation(gql`
mutation createWith {
2021-10-28 14:59:53 -05:00
createWith {
k1
encodedUrl
}
}`)
2023-12-14 11:30:51 -06:00
const toaster = useToast()
2021-10-28 14:59:53 -05:00
2022-11-06 11:28:58 -06:00
useEffect(() => {
2023-12-14 11:30:51 -06:00
createWith().catch(e => {
toaster.danger('withdrawal creation: ' + e?.message || e?.toString?.())
2023-12-14 11:30:51 -06:00
})
}, [createWith, toaster])
2021-10-28 14:59:53 -05:00
2023-12-14 11:30:51 -06:00
if (error) return <QrSkeleton status='error' />
2021-10-28 14:59:53 -05:00
if (!data) {
2023-01-18 12:49:20 -06:00
return <QrSkeleton status='generating' />
2021-10-28 14:59:53 -05:00
}
return <LnQRWith {...data.createWith} />
}
2022-01-23 11:21:55 -06:00
export function LnAddrWithdrawal () {
Account Switching (#644) * WIP: Account switching * Fix empty USER query ANON_USER_ID was undefined and thus the query for @anon had no variables. * Apply multiAuthMiddleware in /api/graphql * Fix 'you must be logged in' query error on switch to anon * Add smart 'switch account' button "smart" means that it only shows if there are accounts to which one can switch * Fix multiAuth not set in backend * Comment fixes, minor changes * Use fw-bold instead of 'selected' * Close dropdown and offcanvas Inside a dropdown, we can rely on autoClose but need to wrap the buttons with <Dropdown.Item> for that to work. For the offcanvas, we need to pass down handleClose. * Use button to add account * Some pages require hard reload on account switch * Reinit settings form on account switch * Also don't refetch WalletHistory * Formatting * Use width: fit-content for standalone SignUpButton * Remove unused className * Use fw-bold and text-underline on selected * Fix inconsistent padding of login buttons * Fix duplicate redirect from /settings on anon switch * Never throw during refetch * Throw errors which extend GraphQLError * Only use meAnonSats if logged out * Use reactive variable for meAnonSats The previous commit broke the UI update after anon zaps because we actually updated item.meSats in the cache and not item.meAnonSats. Updating item.meAnonSats was not possible because it's a local field. For that, one needs to use reactive variables. We do this now and thus also don't need the useEffect hack in item-info.js anymore. * Switch to new user * Fix missing cleanup during logout If we logged in but never switched to any other account, the 'multi_auth.user-id' cookie was not set. This meant that during logout, the other 'multi_auth.*' cookies were not deleted. This broke the account switch modal. This is fixed by setting the 'multi_auth.user-id' cookie on login. Additionally, we now cleanup if cookie pointer OR session is set (instead of only if both are set). * Fix comments in middleware * Remove unnecessary effect dependencies setState is stable and thus only noise in effect dependencies * Show but disable unavailable auth methods * make signup button consistent with others * Always reload page on switch * refine account switch styling * logout barrier --------- Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-09-12 20:05:11 +02:00
const { me } = useMe()
2022-01-23 11:21:55 -06: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 11:21:55 -06:00
2023-10-05 20:33:14 -05:00
const onAddrChange = useDebounceCallback(async (formik, e) => {
2023-10-05 21:14:57 -05: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 15:01:51 -05:00
}, 500, [setAddrOptions, setFormSchema])
2022-01-23 11:21:55 -06:00
return (
<>
{called && !error && <WithdrawlSkeleton status='sending' />}
2022-01-23 11:21:55 -06: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 11:21:55 -06:00
initial={{
addr: '',
amount: 1,
maxFee: maxFeeDefault,
comment: '',
identifier: false,
name: '',
email: ''
2022-01-23 11:21:55 -06:00
}}
schema={formSchema}
onSubmit={async ({ amount, maxFee, ...values }) => {
const { data } = await sendToLnAddr({
variables: {
amount: Number(amount),
maxFee: Number(maxFee),
...values
}
})
2022-01-23 11:21:55 -06:00
router.push(`/withdrawals/${data.sendToLnAddr.id}`)
}}
>
<InputUserSuggest
2022-01-23 11:21:55 -06:00
label='lightning address'
name='addr'
required
autoFocus
onChange={onAddrChange}
transformUser={user => ({ ...user, name: `${user.name}@stacker.news` })}
2023-11-21 17:32:22 -06:00
selectWithTab
filterUsers={(query) => {
const [, domain] = query.split('@')
return !domain || 'stacker.news'.startsWith(domain)
}}
2022-01-23 11:21:55 -06:00
/>
<Input
label='amount'
name='amount'
type='number'
step={10}
2022-01-23 11:21:55 -06:00
required
min={addrOptions.min}
max={addrOptions.max}
2022-01-23 11:21:55 -06:00
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
<Input
label='max fee'
name='maxFee'
type='number'
step={10}
2022-01-23 11:21:55 -06: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>}
<div className='d-flex justify-content-end mt-4'>
<SubmitButton variant='success'>send</SubmitButton>
</div>
2022-01-23 11:21:55 -06:00
</Form>
</>
)
}