* wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
249 lines
7.3 KiB
JavaScript
249 lines
7.3 KiB
JavaScript
import { useCallback, useMemo } from 'react'
|
|
import { useMe } from './me'
|
|
import { gql, useApolloClient, useMutation } from '@apollo/client'
|
|
import { useWebLN } from './webln'
|
|
import { FAST_POLL_INTERVAL, JIT_INVOICE_TIMEOUT_MS } from '@/lib/constants'
|
|
import { INVOICE } from '@/fragments/wallet'
|
|
import Invoice from '@/components/invoice'
|
|
import { useFeeButton } from './fee-button'
|
|
import { useShowModal } from './modal'
|
|
|
|
export class InvoiceCanceledError extends Error {
|
|
constructor (hash) {
|
|
super(`invoice canceled: ${hash}`)
|
|
this.name = 'InvoiceCanceledError'
|
|
}
|
|
}
|
|
|
|
export class WebLnNotEnabledError extends Error {
|
|
constructor () {
|
|
super('no enabled WebLN provider found')
|
|
this.name = 'WebLnNotEnabledError'
|
|
}
|
|
}
|
|
|
|
export class InvoiceExpiredError extends Error {
|
|
constructor (hash) {
|
|
super(`invoice expired: ${hash}`)
|
|
this.name = 'InvoiceExpiredError'
|
|
}
|
|
}
|
|
|
|
export const useInvoice = () => {
|
|
const client = useApolloClient()
|
|
|
|
const [createInvoice] = useMutation(gql`
|
|
mutation createInvoice($amount: Int!, $expireSecs: Int!) {
|
|
createInvoice(amount: $amount, hodlInvoice: true, expireSecs: $expireSecs) {
|
|
id
|
|
bolt11
|
|
hash
|
|
hmac
|
|
expiresAt
|
|
satsRequested
|
|
}
|
|
}`)
|
|
const [cancelInvoice] = useMutation(gql`
|
|
mutation cancelInvoice($hash: String!, $hmac: String!) {
|
|
cancelInvoice(hash: $hash, hmac: $hmac) {
|
|
id
|
|
}
|
|
}
|
|
`)
|
|
|
|
const create = useCallback(async amount => {
|
|
const { data, error } = await createInvoice({ variables: { amount, expireSecs: JIT_INVOICE_TIMEOUT_MS / 1000 } })
|
|
if (error) {
|
|
throw error
|
|
}
|
|
const invoice = data.createInvoice
|
|
return invoice
|
|
}, [createInvoice])
|
|
|
|
const isInvoice = useCallback(async ({ id }, that) => {
|
|
const { data, error } = await client.query({ query: INVOICE, fetchPolicy: 'network-only', variables: { id } })
|
|
if (error) {
|
|
throw error
|
|
}
|
|
const { hash, cancelled } = data.invoice
|
|
|
|
if (cancelled) {
|
|
throw new InvoiceCanceledError(hash)
|
|
}
|
|
|
|
return that(data.invoice)
|
|
}, [client])
|
|
|
|
const waitController = useMemo(() => {
|
|
const controller = new AbortController()
|
|
const signal = controller.signal
|
|
controller.wait = async ({ id }, waitFor = inv => (inv.satsReceived > 0)) => {
|
|
return await new Promise((resolve, reject) => {
|
|
const interval = setInterval(async () => {
|
|
try {
|
|
const paid = await isInvoice({ id }, waitFor)
|
|
if (paid) {
|
|
resolve()
|
|
clearInterval(interval)
|
|
signal.removeEventListener('abort', abort)
|
|
} else {
|
|
console.info(`invoice #${id}: waiting for payment ...`)
|
|
}
|
|
} catch (err) {
|
|
reject(err)
|
|
clearInterval(interval)
|
|
signal.removeEventListener('abort', abort)
|
|
}
|
|
}, FAST_POLL_INTERVAL)
|
|
|
|
const abort = () => {
|
|
console.info(`invoice #${id}: stopped waiting`)
|
|
resolve()
|
|
clearInterval(interval)
|
|
signal.removeEventListener('abort', abort)
|
|
}
|
|
signal.addEventListener('abort', abort)
|
|
})
|
|
}
|
|
|
|
controller.stop = () => controller.abort()
|
|
|
|
return controller
|
|
}, [isInvoice])
|
|
|
|
const cancel = useCallback(async ({ hash, hmac }) => {
|
|
if (!hash || !hmac) {
|
|
throw new Error('missing hash or hmac')
|
|
}
|
|
|
|
console.log('canceling invoice:', hash)
|
|
const inv = await cancelInvoice({ variables: { hash, hmac } })
|
|
return inv
|
|
}, [cancelInvoice])
|
|
|
|
return { create, waitUntilPaid: waitController.wait, stopWaiting: waitController.stop, cancel }
|
|
}
|
|
|
|
export const useWebLnPayment = () => {
|
|
const invoice = useInvoice()
|
|
const provider = useWebLN()
|
|
|
|
const waitForWebLnPayment = useCallback(async ({ id, bolt11 }, waitFor) => {
|
|
if (!provider) {
|
|
throw new WebLnNotEnabledError()
|
|
}
|
|
try {
|
|
return await new Promise((resolve, reject) => {
|
|
// can't use await here since we might pay JIT invoices and sendPaymentAsync is not supported yet.
|
|
// see https://www.webln.guide/building-lightning-apps/webln-reference/webln.sendpaymentasync
|
|
provider.sendPayment(bolt11)
|
|
// JIT invoice payments will never resolve here
|
|
// since they only get resolved after settlement which can't happen here
|
|
.then(resolve)
|
|
.catch(reject)
|
|
invoice.waitUntilPaid({ id }, waitFor)
|
|
.then(resolve)
|
|
.catch(reject)
|
|
})
|
|
} catch (err) {
|
|
console.error('WebLN payment failed:', err)
|
|
throw err
|
|
} finally {
|
|
invoice.stopWaiting()
|
|
}
|
|
}, [provider, invoice])
|
|
|
|
return waitForWebLnPayment
|
|
}
|
|
|
|
export const useQrPayment = () => {
|
|
const invoice = useInvoice()
|
|
const showModal = useShowModal()
|
|
|
|
const waitForQrPayment = useCallback(async (inv, webLnError,
|
|
{
|
|
keepOpen = true,
|
|
cancelOnClose = true,
|
|
persistOnNavigate = false,
|
|
waitFor = inv => inv?.satsReceived > 0
|
|
} = {}
|
|
) => {
|
|
return await new Promise((resolve, reject) => {
|
|
let paid
|
|
const cancelAndReject = async (onClose) => {
|
|
if (!paid && cancelOnClose) {
|
|
await invoice.cancel(inv).catch(console.error)
|
|
reject(new InvoiceCanceledError(inv?.hash))
|
|
}
|
|
resolve()
|
|
}
|
|
showModal(onClose =>
|
|
<Invoice
|
|
id={inv.id}
|
|
modal
|
|
description
|
|
status='loading'
|
|
successVerb='received'
|
|
webLn={false}
|
|
webLnError={webLnError}
|
|
waitFor={waitFor}
|
|
onPayment={() => { paid = true; onClose(); resolve() }}
|
|
poll
|
|
/>,
|
|
{ keepOpen, persistOnNavigate, onClose: cancelAndReject })
|
|
})
|
|
}, [invoice])
|
|
|
|
return waitForQrPayment
|
|
}
|
|
|
|
export const usePayment = () => {
|
|
const me = useMe()
|
|
const feeButton = useFeeButton()
|
|
const invoice = useInvoice()
|
|
const waitForWebLnPayment = useWebLnPayment()
|
|
const waitForQrPayment = useQrPayment()
|
|
|
|
const waitForPayment = useCallback(async (invoice) => {
|
|
let webLnError
|
|
try {
|
|
return await waitForWebLnPayment(invoice)
|
|
} catch (err) {
|
|
if (err instanceof InvoiceCanceledError || err instanceof InvoiceExpiredError) {
|
|
// bail since qr code payment will also fail
|
|
throw err
|
|
}
|
|
webLnError = err
|
|
}
|
|
return await waitForQrPayment(invoice, webLnError)
|
|
}, [waitForWebLnPayment, waitForQrPayment])
|
|
|
|
const request = useCallback(async (amount) => {
|
|
amount ??= feeButton?.total
|
|
const free = feeButton?.free
|
|
const balance = me ? me.privates.sats : 0
|
|
|
|
// if user has enough funds in their custodial wallet or action is free, never prompt for payment
|
|
// XXX this will probably not work as intended for deposits < balance
|
|
// which means you can't always fund your custodial wallet with attached wallets ...
|
|
// but should this even be the case?
|
|
const insufficientFunds = balance < amount
|
|
if (free || !insufficientFunds) return [{ hash: null, hmac: null }, null]
|
|
|
|
const inv = await invoice.create(amount)
|
|
|
|
await waitForPayment(inv)
|
|
|
|
const cancel = () => invoice.cancel(inv).catch(console.error)
|
|
return [inv, cancel]
|
|
}, [me, feeButton?.total, invoice, waitForPayment])
|
|
|
|
const cancel = useCallback(({ hash, hmac }) => {
|
|
if (hash && hmac) {
|
|
invoice.cancel({ hash, hmac }).catch(console.error)
|
|
}
|
|
}, [invoice])
|
|
|
|
return { request, cancel }
|
|
}
|