2024-07-01 17:02:29 +00:00
|
|
|
import { useCallback, useMemo } from 'react'
|
2024-05-28 17:18:54 +00:00
|
|
|
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 {
|
2024-07-04 17:30:42 +00:00
|
|
|
constructor (hash, actionError) {
|
|
|
|
super(actionError ?? `invoice canceled: ${hash}`)
|
2024-05-28 17:18:54 +00:00
|
|
|
this.name = 'InvoiceCanceledError'
|
2024-07-04 17:30:42 +00:00
|
|
|
this.hash = hash
|
2024-07-09 18:10:41 +00:00
|
|
|
this.actionError = actionError
|
2024-05-28 17:18:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-01 17:02:29 +00:00
|
|
|
export const useInvoice = () => {
|
2024-05-28 17:18:54 +00:00
|
|
|
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])
|
|
|
|
|
2024-07-01 17:02:29 +00:00
|
|
|
const isInvoice = useCallback(async ({ id }, that) => {
|
|
|
|
const { data, error } = await client.query({ query: INVOICE, fetchPolicy: 'network-only', variables: { id } })
|
2024-05-28 17:18:54 +00:00
|
|
|
if (error) {
|
|
|
|
throw error
|
|
|
|
}
|
2024-07-04 17:30:42 +00:00
|
|
|
const { hash, cancelled, actionError } = data.invoice
|
2024-07-01 17:02:29 +00:00
|
|
|
|
2024-07-04 17:30:42 +00:00
|
|
|
if (cancelled || actionError) {
|
|
|
|
throw new InvoiceCanceledError(hash, actionError)
|
2024-05-28 17:18:54 +00:00
|
|
|
}
|
2024-07-01 17:02:29 +00:00
|
|
|
|
|
|
|
return that(data.invoice)
|
2024-05-28 17:18:54 +00:00
|
|
|
}, [client])
|
|
|
|
|
2024-07-01 17:02:29 +00:00
|
|
|
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)
|
2024-05-28 17:18:54 +00:00
|
|
|
clearInterval(interval)
|
2024-07-01 17:02:29 +00:00
|
|
|
signal.removeEventListener('abort', abort)
|
2024-05-28 17:18:54 +00:00
|
|
|
}
|
2024-07-01 17:02:29 +00:00
|
|
|
}, FAST_POLL_INTERVAL)
|
|
|
|
|
|
|
|
const abort = () => {
|
|
|
|
console.info(`invoice #${id}: stopped waiting`)
|
|
|
|
resolve()
|
2024-05-28 17:18:54 +00:00
|
|
|
clearInterval(interval)
|
2024-07-01 17:02:29 +00:00
|
|
|
signal.removeEventListener('abort', abort)
|
2024-05-28 17:18:54 +00:00
|
|
|
}
|
2024-07-01 17:02:29 +00:00
|
|
|
signal.addEventListener('abort', abort)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
controller.stop = () => controller.abort()
|
|
|
|
|
|
|
|
return controller
|
|
|
|
}, [isInvoice])
|
2024-05-28 17:18:54 +00:00
|
|
|
|
|
|
|
const cancel = useCallback(async ({ hash, hmac }) => {
|
2024-07-01 17:02:29 +00:00
|
|
|
if (!hash || !hmac) {
|
|
|
|
throw new Error('missing hash or hmac')
|
|
|
|
}
|
|
|
|
|
|
|
|
console.log('canceling invoice:', hash)
|
2024-05-28 17:18:54 +00:00
|
|
|
const inv = await cancelInvoice({ variables: { hash, hmac } })
|
|
|
|
return inv
|
|
|
|
}, [cancelInvoice])
|
|
|
|
|
2024-07-01 17:02:29 +00:00
|
|
|
return { create, waitUntilPaid: waitController.wait, stopWaiting: waitController.stop, cancel }
|
2024-05-28 17:18:54 +00:00
|
|
|
}
|
|
|
|
|
2024-07-01 17:02:29 +00:00
|
|
|
export const useWebLnPayment = () => {
|
2024-05-28 17:18:54 +00:00
|
|
|
const invoice = useInvoice()
|
|
|
|
const provider = useWebLN()
|
|
|
|
|
2024-07-01 17:02:29 +00:00
|
|
|
const waitForWebLnPayment = useCallback(async ({ id, bolt11 }, waitFor) => {
|
2024-05-28 17:18:54 +00:00
|
|
|
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)
|
2024-07-01 17:02:29 +00:00
|
|
|
invoice.waitUntilPaid({ id }, waitFor)
|
2024-05-28 17:18:54 +00:00
|
|
|
.then(resolve)
|
|
|
|
.catch(reject)
|
|
|
|
})
|
|
|
|
} catch (err) {
|
|
|
|
console.error('WebLN payment failed:', err)
|
|
|
|
throw err
|
2024-07-01 17:02:29 +00:00
|
|
|
} finally {
|
|
|
|
invoice.stopWaiting()
|
2024-05-28 17:18:54 +00:00
|
|
|
}
|
|
|
|
}, [provider, invoice])
|
|
|
|
|
|
|
|
return waitForWebLnPayment
|
|
|
|
}
|
|
|
|
|
2024-07-01 17:02:29 +00:00
|
|
|
export const useQrPayment = () => {
|
2024-05-28 17:18:54 +00:00
|
|
|
const invoice = useInvoice()
|
|
|
|
const showModal = useShowModal()
|
|
|
|
|
2024-07-01 17:02:29 +00:00
|
|
|
const waitForQrPayment = useCallback(async (inv, webLnError,
|
|
|
|
{
|
|
|
|
keepOpen = true,
|
|
|
|
cancelOnClose = true,
|
|
|
|
persistOnNavigate = false,
|
|
|
|
waitFor = inv => inv?.satsReceived > 0
|
|
|
|
} = {}
|
|
|
|
) => {
|
2024-05-28 17:18:54 +00:00
|
|
|
return await new Promise((resolve, reject) => {
|
|
|
|
let paid
|
|
|
|
const cancelAndReject = async (onClose) => {
|
2024-07-01 17:02:29 +00:00
|
|
|
if (!paid && cancelOnClose) {
|
|
|
|
await invoice.cancel(inv).catch(console.error)
|
|
|
|
reject(new InvoiceCanceledError(inv?.hash))
|
|
|
|
}
|
|
|
|
resolve()
|
2024-05-28 17:18:54 +00:00
|
|
|
}
|
|
|
|
showModal(onClose =>
|
|
|
|
<Invoice
|
2024-07-01 17:02:29 +00:00
|
|
|
id={inv.id}
|
2024-05-28 17:18:54 +00:00
|
|
|
modal
|
2024-07-01 17:02:29 +00:00
|
|
|
description
|
|
|
|
status='loading'
|
2024-05-28 17:18:54 +00:00
|
|
|
successVerb='received'
|
|
|
|
webLn={false}
|
|
|
|
webLnError={webLnError}
|
2024-07-01 17:02:29 +00:00
|
|
|
waitFor={waitFor}
|
2024-07-04 17:30:42 +00:00
|
|
|
onCanceled={inv => { onClose(); reject(new InvoiceCanceledError(inv?.hash, inv?.actionError)) }}
|
2024-05-28 17:18:54 +00:00
|
|
|
onPayment={() => { paid = true; onClose(); resolve() }}
|
|
|
|
poll
|
|
|
|
/>,
|
2024-07-01 17:02:29 +00:00
|
|
|
{ keepOpen, persistOnNavigate, onClose: cancelAndReject })
|
2024-05-28 17:18:54 +00:00
|
|
|
})
|
|
|
|
}, [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 }
|
|
|
|
}
|