Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose WebLN interface via React Context #749

Merged
merged 77 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from 71 commits
Commits
Show all changes
77 commits
Select commit Hold shift + click to select a range
3177672
Add LNbits card
ekzyis Dec 26, 2023
3e8af2f
Save LNbits Provider in WebLN context
ekzyis Dec 26, 2023
7ad058f
Check LNbits connection on save
ekzyis Jan 14, 2024
76ba4d7
refactor: put LNbitsProvider into own file
ekzyis Jan 14, 2024
8ef1159
Pay invoices using WebLN provider from context
ekzyis Jan 14, 2024
9cd32b5
Remove deprecated FIXME
ekzyis Jan 14, 2024
632b1bf
Try WebLN provider first
ekzyis Jan 16, 2024
d62cfbe
Fix unhandled promise rejection
ekzyis Jan 17, 2024
860c54a
Fix this in sendPayment
ekzyis Jan 18, 2024
c9e7ba0
Be optimistic regarding WebLN zaps
ekzyis Jan 18, 2024
8f0e974
Bold strike on WebLN zap
ekzyis Jan 18, 2024
e93b9cb
Rename undo variable to amount
ekzyis Jan 18, 2024
c63b4a7
Fix zap undo
ekzyis Jan 18, 2024
0f7f1a5
Add NWC card
ekzyis Jan 19, 2024
d659ff2
Attempt to check NWC connection using info event
ekzyis Jan 20, 2024
19031bd
Fix NaN on zap
ekzyis Jan 20, 2024
b7039f9
Fix TypeError in catch of QR code
ekzyis Jan 20, 2024
1b4cf78
Add basic NWC payments
ekzyis Jan 20, 2024
08d0dca
Wrap LNbits getInfo with try/catch
ekzyis Jan 20, 2024
0951adc
EOSE is enough to check NWC connection
ekzyis Jan 20, 2024
bfdbe4e
refactor: Wrap WebLN providers into own context
ekzyis Jan 21, 2024
28c63f6
Show red indicator on error
ekzyis Jan 22, 2024
408f20a
Fix useEffect return value
ekzyis Jan 22, 2024
2da2fc4
Fix wrong usage of pubkey
ekzyis Jan 22, 2024
0b4684a
Use p tag in NWC request
ekzyis Jan 22, 2024
b3f3f96
Add comment about required filter field
ekzyis Jan 22, 2024
0c01294
Aesthetic changes to NWC sendPayment
ekzyis Jan 22, 2024
e3d01b6
Add TODO about receipt verification
ekzyis Jan 22, 2024
d11d79b
Fix WebLN attempted again after error
ekzyis Jan 22, 2024
335fc76
Fix undefined name
ekzyis Jan 22, 2024
7a063d7
Add code to mock NWC relay
ekzyis Jan 22, 2024
7307217
Revert "Bold strike on WebLN zap"
ekzyis Jan 22, 2024
5ce7912
Fix update undo
ekzyis Jan 22, 2024
2eca9eb
Fix lightning strike before payment
ekzyis Jan 22, 2024
7c7f652
WIP: Wrap WebLN payments with toasts
ekzyis Jan 22, 2024
17c455a
Fix invoice poll using stale value from cache
ekzyis Jan 27, 2024
ecbdec0
Remove unnecessary if
ekzyis Jan 29, 2024
c479ca1
Make sure that pay_invoice is declared as supported
ekzyis Jan 30, 2024
3fdd978
Check if WebLN provider is enabled before calling sendPayment
ekzyis Jan 31, 2024
4239568
Fix bad retry
ekzyis Jan 31, 2024
c23f7f1
Fix cache undo update
ekzyis Jan 31, 2024
477eb5c
Fix no cache update after QR payment
ekzyis Jan 31, 2024
9f5dcb7
refactor: Use fragments to undo cache updates
ekzyis Jan 31, 2024
263a056
Remove console.log
ekzyis Jan 31, 2024
01de653
Small changes to NWC relay mocking
ekzyis Jan 31, 2024
af733aa
Return SendPaymentResponse
ekzyis Jan 31, 2024
49abf98
Also undo cache update on retry failure
ekzyis Jan 31, 2024
acf6135
Disable NWC mocking
ekzyis Jan 31, 2024
7aef8c7
Fix initialValue not set
ekzyis Jan 31, 2024
46ecb77
Remove comment since only relevant for blastr (mutiny relay)
ekzyis Feb 1, 2024
dcf4856
Remove TODO
ekzyis Feb 1, 2024
7d454ef
Fix duplicate cache update
ekzyis Feb 1, 2024
036787b
Fix QR modal not closed after payment
ekzyis Feb 1, 2024
aac5d2e
Ignore lnbits variable unused
ekzyis Feb 1, 2024
c91f9f2
Use single relay connection for all NWC events
ekzyis Feb 2, 2024
2865ca4
Fix missing timer and subscription cleanup
ekzyis Feb 2, 2024
c106eaa
Remove TODO
ekzyis Feb 2, 2024
a2f6181
Fix switch from controlled to uncontrolled input
ekzyis Feb 2, 2024
c1f41c5
Show 'configure' on error
ekzyis Feb 2, 2024
4a084c1
Use budgetable instead of async
ekzyis Feb 3, 2024
8db4cd1
Remove EOSE listener
ekzyis Feb 4, 2024
1664450
Use invoice expiry for NWC timeout
ekzyis Feb 4, 2024
a330f93
Merge branch 'master' into 533-webln
huumn Feb 6, 2024
6252b25
Validate LNbits config on save
ekzyis Feb 7, 2024
1046116
Validate NWC config on save
ekzyis Feb 7, 2024
b38377b
Also show unattach if configuration is invalid
ekzyis Feb 7, 2024
19c725e
Fix detection of WebLN payment
ekzyis Feb 7, 2024
cc6c460
Fix formik bag lost
ekzyis Feb 7, 2024
ac347c7
Use payment instead of zap in toast
ekzyis Feb 7, 2024
08401e9
autoscale capture svc by response time
huumn Feb 6, 2024
838fab2
docs and changes for testing lnbits locally
huumn Feb 7, 2024
f397352
Merge branch 'master' into 533-webln
huumn Feb 8, 2024
4873c2f
Rename configJSON to config
ekzyis Feb 8, 2024
4b95add
Allow setting of default payment provider
ekzyis Feb 8, 2024
998a600
Update TODO comment about provider priority
ekzyis Feb 8, 2024
7a55913
Add wallet security disclaimer
ekzyis Feb 8, 2024
4c0aa5a
Update labels
ekzyis Feb 8, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ node_modules/
.DS_Store
*.pem
/*.sql
lnbits/

# debug
npm-debug.log*
Expand Down
14 changes: 14 additions & 0 deletions components/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -961,3 +961,17 @@ export function DatePicker ({ fromName, toName, noForm, onChange, when, from, to
/>
)
}

export function ClientInput ({ initialValue, ...props }) {
// This component can be used for Formik fields
// where the initial value is not available on first render.
// Example: value is stored in localStorage which is fetched
// after first render using an useEffect hook.
const [,, helpers] = useField(props)

useEffect(() => {
helpers.setValue(initialValue)
}, [initialValue])

return <Input {...props} />
}
152 changes: 132 additions & 20 deletions components/invoice.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useState, useCallback, useEffect } from 'react'
import { useMutation, useQuery } from '@apollo/client'
import { useApolloClient, useMutation, useQuery } from '@apollo/client'
import { Button } from 'react-bootstrap'
import { gql } from 'graphql-tag'
import { numWithUnits } from '../lib/format'
Expand All @@ -12,13 +12,17 @@ import { useShowModal } from './modal'
import Countdown from './countdown'
import PayerData from './payer-data'
import Bolt11Info from './bolt11-info'
import { useWebLN } from './webln'

export function Invoice ({ invoice, modal, onPayment, info, successVerb }) {
export function Invoice ({ invoice, modal, onPayment, info, successVerb, webLn }) {
const [expired, setExpired] = useState(new Date(invoice.expiredAt) <= new Date())

// if webLn was not passed, use true by default
if (webLn === undefined) webLn = true

let variant = 'default'
let status = 'waiting for you'
let webLn = true

if (invoice.cancelled) {
variant = 'failed'
status = 'cancelled'
Expand Down Expand Up @@ -118,7 +122,7 @@ const JITInvoice = ({ invoice: { id, hash, hmac, expiresAt }, onPayment, onCance

return (
<>
<Invoice invoice={data.invoice} modal onPayment={onPayment} successVerb='received' />
<Invoice invoice={data.invoice} modal onPayment={onPayment} successVerb='received' webLn={false} />
{retry
? (
<>
Expand Down Expand Up @@ -161,6 +165,7 @@ export const useInvoiceable = (onSubmit, options = defaultOptions) => {
mutation createInvoice($amount: Int!) {
createInvoice(amount: $amount, hodlInvoice: true, expireSecs: 180) {
id
bolt11
hash
hmac
expiresAt
Expand All @@ -175,8 +180,13 @@ export const useInvoiceable = (onSubmit, options = defaultOptions) => {
`)

const showModal = useShowModal()
const provider = useWebLN()
const client = useApolloClient()
const pollInvoice = (id) => client.query({ query: INVOICE, fetchPolicy: 'no-cache', variables: { id } })

const onSubmitWrapper = useCallback(async ({ cost, ...formValues }, ...submitArgs) => {
const onSubmitWrapper = useCallback(async (
{ cost, ...formValues },
{ variables, optimisticResponse, update, ...submitArgs }) => {
// some actions require a session
if (!me && options.requireSession) {
throw new Error('you must be logged in')
Expand All @@ -189,7 +199,9 @@ export const useInvoiceable = (onSubmit, options = defaultOptions) => {
// attempt action for the first time
if (!cost || (me && !options.forceInvoice)) {
try {
return await onSubmit(formValues, ...submitArgs)
const insufficientFunds = me?.privates.sats < cost
return await onSubmit(formValues,
{ ...submitArgs, variables, optimisticsResponse: insufficientFunds ? null : optimisticResponse })
} catch (error) {
if (!payOrLoginError(error) || !cost) {
// can't handle error here - bail
Expand All @@ -205,27 +217,52 @@ export const useInvoiceable = (onSubmit, options = defaultOptions) => {
}
const inv = data.createInvoice

// If this is a zap, we need to manually be optimistic to have a consistent
// UX across custodial and WebLN zaps since WebLN zaps don't call GraphQL
// mutations which implement optimistic responses natively.
// Therefore, we check if this is a zap and then wrap the WebLN payment logic
// with manual cache update calls.
const itemId = optimisticResponse?.act?.id
const isZap = !!itemId
let _update
if (isZap && update) {
_update = () => {
const fragment = {
id: `Item:${itemId}`,
fragment: gql`
fragment ItemMeSats on Item {
sats
meSats
}
`
}
const item = client.cache.readFragment(fragment)
update(client.cache, { data: optimisticResponse })
// undo function
return () => client.cache.writeFragment({ ...fragment, data: item })
}
}

// wait until invoice is paid or modal is closed
let modalClose
await new Promise((resolve, reject) => {
showModal(onClose => {
modalClose = onClose
return (
<JITInvoice
invoice={inv}
onPayment={resolve}
/>
)
}, { keepOpen: true, onClose: reject })
const { modalOnClose, webLn, gqlCacheUpdateUndo } = await waitForPayment({
invoice: inv,
showModal,
provider,
pollInvoice,
gqlCacheUpdate: _update
})

const retry = () => onSubmit({ hash: inv.hash, hmac: inv.hmac, ...formValues }, ...submitArgs)
const retry = () => onSubmit(
{ hash: inv.hash, hmac: inv.hmac, ...formValues },
// unset update function since we already ran an cache update if we paid using WebLN
{ ...submitArgs, variables, update: webLn ? null : undefined })
// first retry
try {
const ret = await retry()
modalClose()
modalOnClose?.()
return ret
} catch (error) {
gqlCacheUpdateUndo?.()
console.error('retry error:', error)
}

Expand All @@ -245,16 +282,91 @@ export const useInvoiceable = (onSubmit, options = defaultOptions) => {
}}
onRetry={async () => {
resolve(await retry())
onClose()
}}
/>
)
}, { keepOpen: true, onClose: cancelAndReject })
})
}, [onSubmit, createInvoice, !!me])
}, [onSubmit, provider, createInvoice, !!me])

return onSubmitWrapper
}

const INVOICE_CANCELED_ERROR = 'invoice was canceled'
const waitForPayment = async ({ invoice, showModal, provider, pollInvoice, gqlCacheUpdate }) => {
if (provider.enabled) {
try {
return await waitForWebLNPayment({ provider, invoice, pollInvoice, gqlCacheUpdate })
} catch (err) {
const INVOICE_CANCELED_ERROR = 'invoice was canceled'
// check for errors which mean that QR code will also fail
if (err.message === INVOICE_CANCELED_ERROR) {
throw err
}
}
}

// QR code as fallback
return await new Promise((resolve, reject) => {
showModal(onClose => {
return (
<JITInvoice
invoice={invoice}
onPayment={() => resolve({ modalOnClose: onClose })}
/>
)
}, { keepOpen: true, onClose: reject })
})
}

const waitForWebLNPayment = async ({ provider, invoice, pollInvoice, gqlCacheUpdate }) => {
let undoUpdate
try {
// try WebLN provider first
return await new Promise((resolve, reject) => {
// be optimistic and pretend zap was already successful for consistent zapping UX
undoUpdate = gqlCacheUpdate?.()
// can't use await here since we might be paying HODL invoices
// and sendPaymentAsync is not supported yet.
// see https://www.webln.guide/building-lightning-apps/webln-reference/webln.sendpaymentasync
provider.sendPayment(invoice)
// WebLN payment will never resolve here for HODL invoices
// since they only get resolved after settlement which can't happen here
.then(() => resolve({ webLn: true, gqlCacheUpdateUndo: undoUpdate }))
.catch(err => {
clearInterval(interval)
reject(err)
})
const interval = setInterval(async () => {
try {
const { data, error } = await pollInvoice(invoice.id)
if (error) {
clearInterval(interval)
return reject(error)
}
const { invoice: inv } = data
if (inv.isHeld && inv.satsReceived) {
clearInterval(interval)
resolve({ webLn: true, gqlCacheUpdateUndo: undoUpdate })
}
if (inv.cancelled) {
clearInterval(interval)
reject(new Error(INVOICE_CANCELED_ERROR))
}
} catch (err) {
clearInterval(interval)
reject(err)
}
}, 1000)
})
} catch (err) {
undoUpdate?.()
console.error('WebLN payment failed:', err)
throw err
}
}

export const useInvoiceModal = (onPayment, deps) => {
const onPaymentMemo = useCallback(onPayment, deps)
return useInvoiceable(onPaymentMemo, { replaceModal: true })
Expand Down
26 changes: 13 additions & 13 deletions components/item-act.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,9 @@ export function useZap () {
const strike = useLightning()
const [act] = useAct()

const showInvoiceModal = useInvoiceModal(
async ({ hash, hmac }, { variables }) => {
await act({ variables: { ...variables, hash, hmac } })
const invoiceableAct = useInvoiceModal(
async ({ hash, hmac }, { variables, ...apolloArgs }) => {
await act({ variables: { ...variables, hash, hmac }, ...apolloArgs })
strike()
}, [act, strike])

Expand All @@ -254,22 +254,22 @@ export function useZap () {
}

const variables = { id: item.id, sats, act: 'TIP' }
const insufficientFunds = me?.privates.sats < sats
const optimisticResponse = { act: { path: item.path, ...variables } }
try {
await zap({
variables,
optimisticResponse: {
act: {
path: item.path,
...variables
}
}
})
if (!insufficientFunds) strike()
await zap({ variables, optimisticResponse: insufficientFunds ? null : optimisticResponse })
} catch (error) {
if (payOrLoginError(error)) {
// call non-idempotent version
const amount = sats - meSats
optimisticResponse.act.amount = amount
try {
await showInvoiceModal({ amount }, { variables: { ...variables, sats: amount } })
await invoiceableAct({ amount }, {
variables: { ...variables, sats: amount },
optimisticResponse,
update
})
} catch (error) {}
return
}
Expand Down
10 changes: 7 additions & 3 deletions components/qr.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
import QRCode from 'qrcode.react'
import { CopyInput, InputSkeleton } from './form'
import InvoiceStatus from './invoice-status'
import { requestProvider } from 'webln'
import { useEffect } from 'react'
import { useWebLN } from './webln'
import { useToast } from './toast'

export default function Qr ({ asIs, value, webLn, statusVariant, description, status }) {
const qrValue = asIs ? value : 'lightning:' + value.toUpperCase()

const provider = useWebLN()
const toaster = useToast()

useEffect(() => {
async function effect () {
if (webLn) {
try {
const provider = await requestProvider()
await provider.sendPayment(value)
} catch (e) {
console.log(e.message)
console.log(e?.message)
toaster.danger(`${provider.name}: ${e?.message}`)
}
}
}
Expand Down
4 changes: 0 additions & 4 deletions components/upvote.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import LongPressable from 'react-longpressable'
import Overlay from 'react-bootstrap/Overlay'
import Popover from 'react-bootstrap/Popover'
import { useShowModal } from './modal'
import { useLightning } from './lightning'
import { numWithUnits } from '../lib/format'
import { Dropdown } from 'react-bootstrap'

Expand Down Expand Up @@ -111,7 +110,6 @@ export default function UpVote ({ item, className }) {

const [act] = useAct()
const zap = useZap()
const strike = useLightning()

const disabled = useMemo(() => item?.mine || item?.meForward || item?.deletedAt,
[item?.mine, item?.meForward, item?.deletedAt])
Expand Down Expand Up @@ -168,8 +166,6 @@ export default function UpVote ({ item, className }) {
setTipShow(true)
}

strike()

zap({ item, me })
}
: () => showModal(onClose => <ItemAct onClose={onClose} itemId={item.id} act={act} />)
Expand Down
7 changes: 4 additions & 3 deletions components/wallet-card.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import CancelButton from './cancel-button'
import { SubmitButton } from './form'

export function WalletCard ({ title, badges, provider, enabled }) {
const isConfigured = enabled === true || enabled === false
return (
<Card className={styles.card}>
<div className={`${styles.indicator} ${enabled ? styles.success : styles.disabled}`} />
<div className={`${styles.indicator} ${enabled === true ? styles.success : enabled === false ? styles.error : styles.disabled}`} />
<Card.Body>
<Card.Title>{title}</Card.Title>
<Card.Subtitle className='mt-2'>
Expand All @@ -23,7 +24,7 @@ export function WalletCard ({ title, badges, provider, enabled }) {
{provider &&
<Link href={`/settings/wallets/${provider}`}>
<Card.Footer className={styles.attach}>
{enabled
{isConfigured
? <>configure<Gear width={14} height={14} /></>
: <>attach<Plug width={14} height={14} /></>}
</Card.Footer>
Expand All @@ -40,7 +41,7 @@ export function WalletButtonBar ({
return (
<div className={`mt-3 ${className}`}>
<div className='d-flex justify-content-between'>
{enabled &&
{enabled !== undefined &&
<Button onClick={onDelete} variant='grey-medium'>{deleteText}</Button>}
{children}
<div className='d-flex align-items-center ms-auto'>
Expand Down