stacker.news/components/item-act.js

412 lines
12 KiB
JavaScript
Raw Normal View History

2023-07-24 18:35:05 +00:00
import Button from 'react-bootstrap/Button'
import InputGroup from 'react-bootstrap/InputGroup'
Allow zapping, posting and commenting without funds or an account (#336) * Add anon zaps * Add anon comments and posts (link, discussion, poll) * Use payment hash instead of invoice id as proof of payment Our invoice IDs can be enumerated. So there is a - even though very rare - chance that an attacker could find a paid invoice which is not used yet and use it for himself. Random payment hashes prevent this. Also, since we delete invoices after use, using database IDs as proof of payments are not suitable. If a user tells us an invoice ID after we deleted it, we can no longer tell if the invoice was paid or not since the LN node only knows about payment hashes but nothing about the database IDs. * Allow pay per invoice for stackers The modal which pops up if the stacker does not have enough sats now has two options: "fund wallet" and "pay invoice" * Fix onSuccess called twice For some reason, when calling `showModal`, `useMemo` in modal.js and the code for the modal component (here: <Invoice>) is called twice. This leads to the `onSuccess` callback being called twice and one failing since the first one deletes the invoice. * Keep invoice modal open if focus is lost * Skip anon user during trust calculation * Add error handling * Skip 'invoice not found' errors * Remove duplicate insufficient funds handling * Fix insufficient funds error detection * Fix invoice amount for comments * Allow pay per invoice for bounty and job posts * Also strike on payment after short press * Fix unexpected token 'export' * Fix eslint * Remove unused id param * Fix comment copy-paste error * Rename to useInvoiceable * Fix unexpected token 'export' * Fix onConfirmation called at every render * Add invoice HMAC This prevents entities which know the invoice hash (like all LN nodes on the payment path) from using the invoice hash on SN. Only the user which created the invoice knows the HMAC and thus can use the invoice hash. * make anon posting less hidden, add anon info button explainer * Fix anon users can't zap other anon users * Always show repeat and contacts on action error * Keep track of modal stack * give anon an icon * add generic date pivot helper * make anon user's invoices expire in 5 minutes * fix forgotten find and replace * use datePivot more places * add sat amounts to invoices * reduce anon invoice expiration to 3 minutes * don't abbreviate * Fix [object Object] as error message Any errors thrown here are already objects of shape { message: string } * Fix empty invoice creation attempts I stumbled across this while checking if anons can edit their items. I monkey patched the code to make it possible (so they can see the 'edit' button) and tried to edit an item but I got this error: Variable "$amount" of required type "Int!" was not provided. I fixed this even though this function should never be called without an amount anyway. It will return a sane error in that case now. * anon func mods, e.g. inv limits * anon tips should be denormalized * remove redundant meTotalSats * correct overlay zap text for anon * exclude anon from trust graph before algo runs * remove balance limit on anon * give anon a bio and remove cowboy hat/top stackers; * make anon hat appear on profile * concat hash and hmac and call it a token * Fix localStorage cleared because error were swallowed * fix qr layout shift * restyle fund error modal * Catch invoice errors in fund error modal * invoice check backoff * anon info typo * make invoice expiration times have saner defaults * add comma to anon info * use builtin copy input label --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
2023-08-11 23:50:57 +00:00
import React, { useState, useRef, useEffect, useCallback } from 'react'
import { Form, Input, SubmitButton } from './form'
2021-09-12 16:55:38 +00:00
import { useMe } from './me'
import UpBolt from '@/svgs/bolt.svg'
import { amountSchema } from '@/lib/validate'
import { gql, useApolloClient, useMutation } from '@apollo/client'
2023-12-27 02:27:52 +00:00
import { payOrLoginError, useInvoiceModal } from './invoice'
import { TOAST_DEFAULT_DELAY_MS, useToast, withToastFlow } from './toast'
2023-12-27 02:27:52 +00:00
import { useLightning } from './lightning'
import { nextTip } from './upvote'
2021-09-10 18:55:36 +00:00
2023-05-14 23:33:49 +00:00
const defaultTips = [100, 1000, 10000, 100000]
2023-05-14 23:11:31 +00:00
const Tips = ({ setOValue }) => {
const tips = [...getCustomTips(), ...defaultTips].sort((a, b) => a - b)
return tips.map(num =>
2023-05-14 23:11:31 +00:00
<Button
size='sm'
2023-07-24 18:35:05 +00:00
className={`${num > 1 ? 'ms-2' : ''} mb-2`}
2023-05-14 23:11:31 +00:00
key={num}
onClick={() => { setOValue(num) }}
>
<UpBolt
2023-07-24 18:35:05 +00:00
className='me-1'
2023-05-14 23:11:31 +00:00
width={14}
height={14}
/>{num}
</Button>)
}
2023-07-25 14:14:45 +00:00
const getCustomTips = () => JSON.parse(window.localStorage.getItem('custom-tips')) || []
2023-05-14 23:11:31 +00:00
const addCustomTip = (amount) => {
2023-05-14 23:33:49 +00:00
if (defaultTips.includes(amount)) return
2023-05-14 23:11:31 +00:00
let customTips = Array.from(new Set([amount, ...getCustomTips()]))
if (customTips.length > 3) {
customTips = customTips.slice(0, 3)
}
2023-07-25 14:14:45 +00:00
window.localStorage.setItem('custom-tips', JSON.stringify(customTips))
2023-05-14 23:11:31 +00:00
}
2023-12-27 02:27:52 +00:00
export default function ItemAct ({ onClose, itemId, down, children }) {
2021-09-10 18:55:36 +00:00
const inputRef = useRef(null)
2021-09-12 16:55:38 +00:00
const me = useMe()
2022-12-09 20:13:31 +00:00
const [oValue, setOValue] = useState()
2023-12-27 02:27:52 +00:00
const strike = useLightning()
const toaster = useToast()
const client = useApolloClient()
2021-09-10 18:55:36 +00:00
useEffect(() => {
inputRef.current?.focus()
}, [onClose, itemId])
2021-09-10 18:55:36 +00:00
const [act, actUpdate] = useAct()
2023-12-26 22:51:47 +00:00
const onSubmit = useCallback(async ({ amount, hash, hmac }, { update }) => {
if (!me) {
const storageKey = `TIP-item:${itemId}`
const existingAmount = Number(window.localStorage.getItem(storageKey) || '0')
window.localStorage.setItem(storageKey, existingAmount + amount)
}
await act({
variables: {
id: itemId,
sats: Number(amount),
2023-12-26 22:51:47 +00:00
act: down ? 'DONT_LIKE_THIS' : 'TIP',
hash,
hmac
},
update
})
// only strike when zap undos not enabled
// due to optimistic UX on zap undos
if (!me || !me.privates.zapUndos) await strike()
addCustomTip(Number(amount))
onClose()
}, [me, act, down, itemId, strike])
const onSubmitWithUndos = withToastFlow(toaster)(
(values, args) => {
const { flowId } = args
let canceled
const sats = values.amount
const insufficientFunds = me?.privates?.sats < sats
const invoiceAttached = values.hash && values.hmac
if (insufficientFunds && !invoiceAttached) throw new Error('insufficient funds')
// payments from external wallets already have their own flow
// and we don't want to show undo toasts for them
const skipToastFlow = invoiceAttached
// update function for optimistic UX
const update = () => {
const fragment = {
id: `Item:${itemId}`,
fragment: gql`
fragment ItemMeSats on Item {
path
sats
meSats
meDontLikeSats
}
`
}
const item = client.cache.readFragment(fragment)
const optimisticResponse = {
act: {
id: itemId, sats, path: item.path, act: down ? 'DONT_LIKE_THIS' : 'TIP'
}
}
actUpdate(client.cache, { data: optimisticResponse })
return () => client.cache.writeFragment({ ...fragment, data: item })
}
let undoUpdate
return {
skipToastFlow,
flowId,
type: 'zap',
pendingMessage: `${down ? 'down' : ''}zapped ${sats} sats`,
onPending: async () => {
if (skipToastFlow) {
return onSubmit(values, { flowId, ...args, update: null })
}
await strike()
onClose()
return new Promise((resolve, reject) => {
undoUpdate = update()
setTimeout(() => {
if (canceled) return resolve()
onSubmit(values, { flowId, ...args, update: null })
.then(resolve)
.catch((err) => {
undoUpdate()
reject(err)
})
}, TOAST_DEFAULT_DELAY_MS)
})
},
onUndo: () => {
canceled = true
undoUpdate?.()
},
hideSuccess: true,
hideError: true,
timeout: TOAST_DEFAULT_DELAY_MS
}
}
)
Allow zapping, posting and commenting without funds or an account (#336) * Add anon zaps * Add anon comments and posts (link, discussion, poll) * Use payment hash instead of invoice id as proof of payment Our invoice IDs can be enumerated. So there is a - even though very rare - chance that an attacker could find a paid invoice which is not used yet and use it for himself. Random payment hashes prevent this. Also, since we delete invoices after use, using database IDs as proof of payments are not suitable. If a user tells us an invoice ID after we deleted it, we can no longer tell if the invoice was paid or not since the LN node only knows about payment hashes but nothing about the database IDs. * Allow pay per invoice for stackers The modal which pops up if the stacker does not have enough sats now has two options: "fund wallet" and "pay invoice" * Fix onSuccess called twice For some reason, when calling `showModal`, `useMemo` in modal.js and the code for the modal component (here: <Invoice>) is called twice. This leads to the `onSuccess` callback being called twice and one failing since the first one deletes the invoice. * Keep invoice modal open if focus is lost * Skip anon user during trust calculation * Add error handling * Skip 'invoice not found' errors * Remove duplicate insufficient funds handling * Fix insufficient funds error detection * Fix invoice amount for comments * Allow pay per invoice for bounty and job posts * Also strike on payment after short press * Fix unexpected token 'export' * Fix eslint * Remove unused id param * Fix comment copy-paste error * Rename to useInvoiceable * Fix unexpected token 'export' * Fix onConfirmation called at every render * Add invoice HMAC This prevents entities which know the invoice hash (like all LN nodes on the payment path) from using the invoice hash on SN. Only the user which created the invoice knows the HMAC and thus can use the invoice hash. * make anon posting less hidden, add anon info button explainer * Fix anon users can't zap other anon users * Always show repeat and contacts on action error * Keep track of modal stack * give anon an icon * add generic date pivot helper * make anon user's invoices expire in 5 minutes * fix forgotten find and replace * use datePivot more places * add sat amounts to invoices * reduce anon invoice expiration to 3 minutes * don't abbreviate * Fix [object Object] as error message Any errors thrown here are already objects of shape { message: string } * Fix empty invoice creation attempts I stumbled across this while checking if anons can edit their items. I monkey patched the code to make it possible (so they can see the 'edit' button) and tried to edit an item but I got this error: Variable "$amount" of required type "Int!" was not provided. I fixed this even though this function should never be called without an amount anyway. It will return a sane error in that case now. * anon func mods, e.g. inv limits * anon tips should be denormalized * remove redundant meTotalSats * correct overlay zap text for anon * exclude anon from trust graph before algo runs * remove balance limit on anon * give anon a bio and remove cowboy hat/top stackers; * make anon hat appear on profile * concat hash and hmac and call it a token * Fix localStorage cleared because error were swallowed * fix qr layout shift * restyle fund error modal * Catch invoice errors in fund error modal * invoice check backoff * anon info typo * make invoice expiration times have saner defaults * add comma to anon info * use builtin copy input label --------- Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
2023-08-11 23:50:57 +00:00
2021-09-10 18:55:36 +00:00
return (
<Form
initial={{
amount: me?.privates?.tipDefault || defaultTips[0],
default: false
}}
2023-02-08 19:38:04 +00:00
schema={amountSchema}
invoiceable
onSubmit={me?.privates?.zapUndos ? onSubmitWithUndos : onSubmit}
2021-09-10 18:55:36 +00:00
>
<Input
label='amount'
name='amount'
2023-05-14 23:24:45 +00:00
type='number'
innerRef={inputRef}
overrideValue={oValue}
required
autoFocus
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
<div>
2023-05-14 23:11:31 +00:00
<Tips setOValue={setOValue} />
</div>
2023-12-20 00:15:08 +00:00
{children}
<div className='d-flex'>
2023-12-20 00:15:08 +00:00
<SubmitButton variant={down ? 'danger' : 'success'} className='ms-auto mt-1 px-4' value='TIP'>{down && 'down'}zap</SubmitButton>
</div>
</Form>
2021-09-10 18:55:36 +00:00
)
}
2023-12-26 22:51:47 +00:00
export function useAct ({ onUpdate } = {}) {
const me = useMe()
const update = useCallback((cache, args) => {
const { data: { act: { id, sats, path, act } } } = args
cache.modify({
id: `Item:${id}`,
fields: {
sats (existingSats = 0) {
if (act === 'TIP') {
return existingSats + sats
}
return existingSats
},
meSats: me
? (existingSats = 0) => {
if (act === 'TIP') {
return existingSats + sats
}
return existingSats
}
: undefined,
meDontLikeSats: me
? (existingSats = 0) => {
if (act === 'DONT_LIKE_THIS') {
return existingSats + sats
}
return existingSats
}
: undefined
}
})
if (act === 'TIP') {
// update all ancestors
path.split('.').forEach(aId => {
if (Number(aId) === Number(id)) return
cache.modify({
id: `Item:${aId}`,
fields: {
commentSats (existingCommentSats = 0) {
return existingCommentSats + sats
}
}
})
})
onUpdate && onUpdate(cache, args)
}
}, [!!me, onUpdate])
const [act] = useMutation(
2023-12-26 22:51:47 +00:00
gql`
mutation act($id: ID!, $sats: Int!, $act: String, $hash: String, $hmac: String) {
act(id: $id, sats: $sats, act: $act, hash: $hash, hmac: $hmac) {
id
sats
path
act
}
}`, { update }
)
return [act, update]
2023-12-26 22:51:47 +00:00
}
2023-12-27 02:27:52 +00:00
export function useZap () {
const update = useCallback((cache, args) => {
2023-12-27 16:15:18 +00:00
const { data: { act: { id, sats, path } } } = args
2023-12-27 02:27:52 +00:00
// determine how much we increased existing sats by by checking the
// difference between result sats and meSats
// if it's negative, skip the cache as it's an out of order update
// if it's positive, add it to sats and commentSats
const item = cache.readFragment({
id: `Item:${id}`,
fragment: gql`
fragment ItemMeSats on Item {
meSats
}
`
})
const satsDelta = sats - item.meSats
if (satsDelta > 0) {
cache.modify({
id: `Item:${id}`,
fields: {
sats (existingSats = 0) {
return existingSats + satsDelta
},
meSats: () => {
return sats
}
}
})
// update all ancestors
path.split('.').forEach(aId => {
if (Number(aId) === Number(id)) return
cache.modify({
id: `Item:${aId}`,
fields: {
commentSats (existingCommentSats = 0) {
return existingCommentSats + satsDelta
}
}
})
})
}
}, [])
const [zap] = useMutation(
gql`
2023-12-27 16:15:18 +00:00
mutation idempotentAct($id: ID!, $sats: Int!) {
act(id: $id, sats: $sats, idempotent: true) {
2023-12-27 02:27:52 +00:00
id
sats
path
}
}`
2023-12-27 02:27:52 +00:00
)
const toaster = useToast()
const strike = useLightning()
const [act] = useAct()
const client = useApolloClient()
2023-12-27 02:27:52 +00:00
Expose WebLN interface via React Context (#749) * 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 a9eb27daec0cd2ef30b56294b05e0056fb5b4184. * 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>
2024-02-08 18:33:13 +00:00
const invoiceableAct = useInvoiceModal(
async ({ hash, hmac }, { variables, ...apolloArgs }) => {
await act({ variables: { ...variables, hash, hmac }, ...apolloArgs })
2023-12-27 02:27:52 +00:00
strike()
}, [act, strike])
const zapWithUndos = withToastFlow(toaster)(
({ variables, optimisticResponse, update, flowId }) => {
const { id: itemId, amount } = variables
let canceled
// update function for optimistic UX
const _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 })
}
let undoUpdate
return {
flowId,
tag: itemId,
type: 'zap',
pendingMessage: `zapped ${amount} sats`,
onPending: () =>
new Promise((resolve, reject) => {
undoUpdate = _update()
setTimeout(
() => {
if (canceled) return resolve()
zap({ variables, optimisticResponse, update: null }).then(resolve).catch((err) => {
undoUpdate()
reject(err)
})
},
TOAST_DEFAULT_DELAY_MS
)
}),
onUndo: () => {
// we can't simply clear the timeout on cancel since
// the onPending promise would never settle in that case
canceled = true
undoUpdate?.()
},
hideSuccess: true,
hideError: true,
timeout: TOAST_DEFAULT_DELAY_MS
}
}
)
2023-12-27 02:27:52 +00:00
return useCallback(async ({ item, me }) => {
const meSats = (item?.meSats || 0)
// add current sats to next tip since idempotent zaps use desired total zap not difference
const sats = meSats + nextTip(meSats, { ...me?.privates })
2023-12-27 02:27:52 +00:00
const variables = { id: item.id, sats, act: 'TIP', amount: sats - meSats }
const insufficientFunds = me?.privates.sats < (sats - meSats)
Expose WebLN interface via React Context (#749) * 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 a9eb27daec0cd2ef30b56294b05e0056fb5b4184. * 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>
2024-02-08 18:33:13 +00:00
const optimisticResponse = { act: { path: item.path, ...variables } }
const flowId = (+new Date()).toString(16)
const zapArgs = { variables, optimisticResponse: insufficientFunds ? null : optimisticResponse, update, flowId }
2023-12-27 02:27:52 +00:00
try {
if (insufficientFunds) throw new Error('insufficient funds')
strike()
if (me?.privates?.zapUndos) {
await zapWithUndos(zapArgs)
} else {
await zap(zapArgs)
}
2023-12-27 02:27:52 +00:00
} catch (error) {
if (payOrLoginError(error)) {
// call non-idempotent version
const amount = sats - meSats
Expose WebLN interface via React Context (#749) * 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 a9eb27daec0cd2ef30b56294b05e0056fb5b4184. * 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>
2024-02-08 18:33:13 +00:00
optimisticResponse.act.amount = amount
try {
Expose WebLN interface via React Context (#749) * 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 a9eb27daec0cd2ef30b56294b05e0056fb5b4184. * 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>
2024-02-08 18:33:13 +00:00
await invoiceableAct({ amount }, {
variables: { ...variables, sats: amount },
optimisticResponse,
update,
flowId
Expose WebLN interface via React Context (#749) * 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 a9eb27daec0cd2ef30b56294b05e0056fb5b4184. * 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>
2024-02-08 18:33:13 +00:00
})
} catch (error) {}
2023-12-27 02:27:52 +00:00
return
}
console.error(error)
toaster.danger('zap: ' + error?.message || error?.toString?.())
2023-12-27 02:27:52 +00:00
}
})
}