Skip to content

Commit

Permalink
Expose WebLN interface via React Context (#749)
Browse files Browse the repository at this point in the history
* Add LNbits card

* Save LNbits Provider in WebLN context

* Check LNbits connection on save

* refactor: put LNbitsProvider into own file

* Pay invoices using WebLN provider from context

* Remove deprecated FIXME

* Try WebLN provider first

* Fix unhandled promise rejection

* Fix this in sendPayment

* Be optimistic regarding WebLN zaps

This wraps the WebLN payment promise with Apollo cache updates.

We will be optimistics and assume that the payment will succeed and update the cache accordingly.

When we notice that the payment failed, we undo this update.

* Bold strike on WebLN zap

If lightning strike animation is disabled, toaster will be used.

* Rename undo variable to amount

* Fix zap undo

* Add NWC card

* Attempt to check NWC connection using info event

* Fix NaN on zap

Third argument of update is reserved for context

* Fix TypeError in catch of QR code

* Add basic NWC payments

* Wrap LNbits getInfo with try/catch

* EOSE is enough to check NWC connection

* refactor: Wrap WebLN providers into own context

I should have done this earlier

* Show red indicator on error

* Fix useEffect return value

* Fix wrong usage of pubkey

The event pubkey is derived from the secret. Doesn't make sense to manually set it. It's also the wrong pubkey: we're not the wallet service.

* Use p tag in NWC request

* Add comment about required filter field

* Aesthetic changes to NWC sendPayment

* Add TODO about receipt verification

* Fix WebLN attempted again after error

* Fix undefined name

* Add code to mock NWC relay

* Revert "Bold strike on WebLN zap"

This reverts commit a9eb27d.

* Fix update undo

* Fix lightning strike before payment

* WIP: Wrap WebLN payments with toasts

* add toasts for pending, error, success
* while pending, invoice can be canceled
* there are still some race conditions between payiny the invoice / error on payment and invoice cancellation

* Fix invoice poll using stale value from cache

* Remove unnecessary if

* Make sure that pay_invoice is declared as supported

* Check if WebLN provider is enabled before calling sendPayment

* Fix bad retry

If WebLN payments failed due to insufficient balances, the promise resolved and thus the action was retried but failed immediately since the invoice (still) wasn't paid.

* Fix cache undo update

* Fix no cache update after QR payment

* refactor: Use fragments to undo cache updates

* Remove console.log

* Small changes to NWC relay mocking

* Return SendPaymentResponse

See https://www.webln.guide/building-lightning-apps/webln-reference/webln.sendpayment

* Also undo cache update on retry failure

* Disable NWC mocking

* Fix initialValue not set

But following warning is now shown in console:

"""
Warning: A component is changing a controlled input to be uncontrolled.
This is likely caused by the value changing from a defined to undefined, which should not happen.
Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
"""

* Remove comment since only relevant for blastr (mutiny relay)

* Remove TODO

* Fix duplicate cache update

* Fix QR modal not closed after payment

* Ignore lnbits variable unused

* Use single relay connection for all NWC events

* Fix missing timer and subscription cleanup

* Remove TODO

Confirmed that nostr-tools verifies events and filters for us.

See https://github.com/nbd-wtf/nostr-tools/blob/master/abstract-relay.ts#L161

* Fix switch from controlled to uncontrolled input

* Show 'configure' on error

* Use budgetable instead of async

* Remove EOSE listener

Only nostr.mutinywallet.com didn't respond with info events due to implementation-specific reasons. This is no longer the case.

* Use invoice expiry for NWC timeout

I don't think there was a specific reason why I used 60 seconds initially.

* Validate LNbits config on save

* Validate NWC config on save

* Also show unattach if configuration is invalid

If unattach is only shown if configuration is valid, resetting the configuration is not possible while it's invalid. So we're stuck with a red wallet indicator.

* Fix detection of WebLN payment

It depended on a Apollo cache update function being available. But that is not the case for every WebLN payment.

* Fix formik bag lost

* Use payment instead of zap in toast

* autoscale capture svc by response time

* docs and changes for testing lnbits locally

* Rename configJSON to config

Naming of config object was inconsistent with saveConfig function which was annoying.

Also fixed other inconsistencies between LNbits and NWC provider.

* Allow setting of default payment provider

* Update TODO comment about provider priority

The list 'paymentMethods' is not used yet but is already implemented for future iterations.

* Add wallet security disclaimer

* Update labels

---------

Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
  • Loading branch information
3 people committed Feb 8, 2024
1 parent 6adb57c commit 310011f
Show file tree
Hide file tree
Showing 20 changed files with 1,145 additions and 53 deletions.
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
17 changes: 17 additions & 0 deletions components/banners.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,20 @@ export function WalletLimitBanner () {
</Alert>
)
}

export function WalletSecurityBanner () {
return (
<Alert className={styles.banner} key='info' variant='warning'>
<Alert.Heading>
Wallet Security Disclaimer
</Alert.Heading>
<p className='mb-1'>
Your wallet's credentials are stored in the browser and never go to the server.<br />
However, you should definitely <strong>set a budget in your wallet</strong>.
</p>
<p>
Also, for the time being, you will have to reenter your credentials on other devices.
</p>
</Alert>
)
}
19 changes: 19 additions & 0 deletions components/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -961,3 +961,22 @@ export function DatePicker ({ fromName, toName, noForm, onChange, when, from, to
/>
)
}

function Client (Component) {
return ({ 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 <Component {...props} />
}
}

export const ClientInput = Client(Input)
export const ClientCheckbox = Client(Checkbox)
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

0 comments on commit 310011f

Please sign in to comment.