stacker.news/components/payment.js

254 lines
7.5 KiB
JavaScript
Raw Normal View History

backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
import { useCallback, useMemo } from 'react'
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
import { useMe } from './me'
import { gql, useApolloClient, useMutation } from '@apollo/client'
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
import { useWallet } from 'wallets'
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
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, actionError) {
super(actionError ?? `invoice canceled: ${hash}`)
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
this.name = 'InvoiceCanceledError'
this.hash = hash
2024-07-09 18:10:41 +00:00
this.actionError = actionError
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
}
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
export class NoAttachedWalletError extends Error {
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
constructor () {
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
super('no attached wallet found')
this.name = 'NoAttachedWalletError'
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
}
export class InvoiceExpiredError extends Error {
constructor (hash) {
super(`invoice expired: ${hash}`)
this.name = 'InvoiceExpiredError'
}
}
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
export const useInvoice = () => {
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
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])
backend payment optimism (#1195) * 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>
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 } })
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
if (error) {
throw error
}
const { hash, cancelled, actionError, actionState } = data.invoice
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
if (cancelled || actionError) {
throw new InvoiceCanceledError(hash, actionError)
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
// write to cache if paid
if (actionState === 'PAID') {
client.writeQuery({ query: INVOICE, variables: { id }, data: { invoice: data.invoice } })
}
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
return that(data.invoice)
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}, [client])
backend payment optimism (#1195) * 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>
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?.actionState === 'PAID') => {
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
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)
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
clearInterval(interval)
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
signal.removeEventListener('abort', abort)
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
}, FAST_POLL_INTERVAL)
const abort = () => {
console.info(`invoice #${id}: stopped waiting`)
resolve()
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
clearInterval(interval)
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
signal.removeEventListener('abort', abort)
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
signal.addEventListener('abort', abort)
})
}
controller.stop = () => controller.abort()
return controller
}, [isInvoice])
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
const cancel = useCallback(async ({ hash, hmac }) => {
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
if (!hash || !hmac) {
throw new Error('missing hash or hmac')
}
console.log('canceling invoice:', hash)
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
const inv = await cancelInvoice({ variables: { hash, hmac } })
return inv
}, [cancelInvoice])
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
return { create, waitUntilPaid: waitController.wait, stopWaiting: waitController.stop, cancel }
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
export const useWalletPayment = () => {
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
const invoice = useInvoice()
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
const wallet = useWallet()
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
const waitForWalletPayment = useCallback(async ({ id, bolt11 }, waitFor) => {
if (!wallet) {
throw new NoAttachedWalletError()
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
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
wallet.sendPayment(bolt11).catch(reject)
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
invoice.waitUntilPaid({ id }, waitFor)
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
.then(resolve)
.catch(reject)
})
} catch (err) {
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
console.error('payment failed:', err)
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
throw err
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
} finally {
invoice.stopWaiting()
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
}, [wallet, invoice])
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
return waitForWalletPayment
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
export const useQrPayment = () => {
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
const invoice = useInvoice()
const showModal = useShowModal()
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
const waitForQrPayment = useCallback(async (inv, walletError,
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
{
keepOpen = true,
cancelOnClose = true,
persistOnNavigate = false,
waitFor = inv => inv?.satsReceived > 0
} = {}
) => {
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
return await new Promise((resolve, reject) => {
let paid
const cancelAndReject = async (onClose) => {
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
if (!paid && cancelOnClose) {
await invoice.cancel(inv).catch(console.error)
reject(new InvoiceCanceledError(inv?.hash))
}
resolve()
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
showModal(onClose =>
<Invoice
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
id={inv.id}
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
modal
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
description
status='loading'
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
successVerb='received'
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
useWallet={false}
walletError={walletError}
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
waitFor={waitFor}
onCanceled={inv => { onClose(); reject(new InvoiceCanceledError(inv?.hash, inv?.actionError)) }}
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
onPayment={() => { paid = true; onClose(); resolve() }}
poll
/>,
backend payment optimism (#1195) * 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>
2024-07-01 17:02:29 +00:00
{ keepOpen, persistOnNavigate, onClose: cancelAndReject })
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
})
}, [invoice])
return waitForQrPayment
}
export const usePayment = () => {
Account Switching (#644) * WIP: Account switching * Fix empty USER query ANON_USER_ID was undefined and thus the query for @anon had no variables. * Apply multiAuthMiddleware in /api/graphql * Fix 'you must be logged in' query error on switch to anon * Add smart 'switch account' button "smart" means that it only shows if there are accounts to which one can switch * Fix multiAuth not set in backend * Comment fixes, minor changes * Use fw-bold instead of 'selected' * Close dropdown and offcanvas Inside a dropdown, we can rely on autoClose but need to wrap the buttons with <Dropdown.Item> for that to work. For the offcanvas, we need to pass down handleClose. * Use button to add account * Some pages require hard reload on account switch * Reinit settings form on account switch * Also don't refetch WalletHistory * Formatting * Use width: fit-content for standalone SignUpButton * Remove unused className * Use fw-bold and text-underline on selected * Fix inconsistent padding of login buttons * Fix duplicate redirect from /settings on anon switch * Never throw during refetch * Throw errors which extend GraphQLError * Only use meAnonSats if logged out * Use reactive variable for meAnonSats The previous commit broke the UI update after anon zaps because we actually updated item.meSats in the cache and not item.meAnonSats. Updating item.meAnonSats was not possible because it's a local field. For that, one needs to use reactive variables. We do this now and thus also don't need the useEffect hack in item-info.js anymore. * Switch to new user * Fix missing cleanup during logout If we logged in but never switched to any other account, the 'multi_auth.user-id' cookie was not set. This meant that during logout, the other 'multi_auth.*' cookies were not deleted. This broke the account switch modal. This is fixed by setting the 'multi_auth.user-id' cookie on login. Additionally, we now cleanup if cookie pointer OR session is set (instead of only if both are set). * Fix comments in middleware * Remove unnecessary effect dependencies setState is stable and thus only noise in effect dependencies * Show but disable unavailable auth methods * make signup button consistent with others * Always reload page on switch * refine account switch styling * logout barrier --------- Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-09-12 18:05:11 +00:00
const { me } = useMe()
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
const feeButton = useFeeButton()
const invoice = useInvoice()
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
const waitForWalletPayment = useWalletPayment()
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
const waitForQrPayment = useQrPayment()
const waitForPayment = useCallback(async (invoice) => {
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
let walletError
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
try {
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
return await waitForWalletPayment(invoice)
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
} catch (err) {
if (err instanceof InvoiceCanceledError || err instanceof InvoiceExpiredError) {
// bail since qr code payment will also fail
throw err
}
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
walletError = err
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
}
Wallet definitions with uniform interface (#1243) * wip: Use uniform interface for wallets * Fix import error * Update wallet logging + other stuff * add canPay and canSend to wallet definition * rename 'default payment method' to 'enabled' and add enable + disable method * Set canPay, canReceive in useWallet * Enable wallet if just configured * Don't pass logger to sendPayment * Add logging to attach & detach * Add schema to wallet def * Add NWC wallet * Fix unused isDefault saved in config * Fix enableWallet * wrong storage key was used * broke if wallets with no configs existed * Run validation during save * Use INFO level for 'wallet disabled' message * Pass config with spread operator * Support help, optional, hint in wallet fields * wip: Add LNC * Fix 20s page load for /settings/wallets.json?nodata=true For some reason, if nodata is passed (which is the case if going back), the page takes 20s to load. * Fix extremely slow page load for LNC import I noticed that the combination of ``` import { Form, PasswordInput, SubmitButton } from '@/components/form' ``` in components/wallet/lnc.js and the dynamic import via `await import` in components/wallet/index.js caused extremely slow page loads. * Use normal imports * Revert "Fix 20s page load for /settings/wallets.json?nodata=true" This reverts commit deb476b3a966569fefcfdf4082d6b64f90fbd0a2. Not using the dynamic import for LNC fixed the slow page load with ?nodata=true. * Remove follow and show recent logs first * Fix position of log start marker * Add FIXMEs for LNC I can't get LNC to connect. It just hangs forever on lnc.connect(). See FIXMEs. * Remove logger.error since already handled in useWallet * Don't require destructuring to pass props to input * wip: Add LND autowithdrawals * receiving wallets need to export 'server' object field * don't print macaroon error stack * fix missing wallet logs order update * mark autowithdrawl settings as required * fix server wallet logs deletion * remove canPay and canReceive since it was confusing where it is available TODO * also use numeric priority for sending wallets to be consistent with how status for receiving wallets is determined * define createInvoice function in wallet definition * consistent wallet logs: sending wallets use 'wallet attached'+'wallet enabled/disabled' whereas receiving wallets use 'wallet created/updated' * see FIXMEs * Fix TypeError * Fix sendPayment called with empty config * removed useEffect such that config is available on first render * fix hydration error using dynamic import without SSR * Fix confusing UX around enabled * Remove FIXMEs Rebase on master seemed to have fixed these, weird * Use same error format in toast and wallet log * Fix usage of conditional hooks in useConfig * Fix isConfigured * Fix delete wallet logs on server * Fix wallet logs refetch onError does not exist on client.mutate * Fix TypeError in isConfigured if no enabled wallet found * Only include local/server config if required * Fix another hydration error * Fix server config not updated after save or detach * Also use 'enabled' for server wallets * Fix wallet logs not updated after server delete * Consistent logs between local and server wallets * 'wallet attached' on create * 'wallet updated' on config updates * 'wallet enabled' and 'wallet disabled' if checkbox changed * 'wallet detached' on delete * Also enable server wallets on create * Disable checkbox if not configured yet * Move all validation schema into lib/validate * Implement drag & drop w/o persistence * Use dynamic import for WalletCard This fixes a lot of issues with hydration * Save order as priority * Fix autowithdrawSettings not applied Form requires config in flat format but mutation requires autowithdraw settings in a separate 'settings' field. I have decided that config will be in flat form format. It will be transformed into mutation format during save. * Save dedicated enabled flag for server wallets * wallet table now contains boolean column 'enabled' * 'priority' is now a number everywhere * use consistent order between how autowithdrawals are attempted and server wallets cards * Fix onCanceled missing * Fix typo * Fix noisy changes in lib/validate I moved the schema for lnbits, nwc and lnc out of lib/validate only to put them back in there later. This commit should make the changeset cleaner by removing noise. * Split arguments into [value,] config, context * Run lnbits url.replace in validate and sendPayment * Remove unnecessary WALLETS_QUERY * Generate wallet mutation from fields * Generate wallet resolver from fields * Fix import inconsistency between app and worker * Use wallet.createInvoice for autowithdrawals * Fix success autowithdrawal log * Fix wallet security banner shown for server wallets * Add autowithdrawal to lightning address * Add optional wallet short name for logging * Fix draggable * Fix autowithdraw loop * Add missing hints * Add CLN autowithdrawal * Detach wallets and delete logs on logout * Remove Wallet in lib/constants * Use inject function for resolvers and typeDefs * Fix priority ignored when fetching enabled wallet * Fix draggable false on first page load due to SSR * Use touches instead of dnd on mobile Browsers don't support drag events for touch devices. To have a consistent implementation for desktop and mobile, we would need to use mousedown/touchstart, mouseup/touchend and mousemove/touchmove. For now, this commit makes changing the order possible on touch devices with simple touches. * Fix duplicate CLN error * Fix autowithdraw priority order * Fix error per invalid bip39 word * Update LNC code * remove LNC FIXMEs Mhh, I guess the TURN server was down or something? It now magically works. Or maybe it only works once per mnemonic? * also removed the lnc.lnd.lightning.getInfo() call since we don't ask and need permission for this RPC for payments. * setting a password does not work though. It fails with 'The password provided is not valid' which is triggered at https://github.com/lightninglabs/lnc-web/blob/main/lib/util/credentialStore.ts#L81. * Fix order if wallet with no priority exists * Use common sort * Add link to lnbits.com * Add example wallet def * Remove TODOs TODO in components/wallet-logger.js was handled. I don't see a need for the TODO in lib/wallet.js anymore. This function will only be called with the wallet of type LIGHTNING_ADDRESS anyway. * Remove console.log * Toast priority save errors * Fix leaking relay connections * Remove 'tor or clearnet' hint for LN addresses * Remove React dependency from wallet definitions * Generate resolver name from walletField * Move wallets into top level directory wallet/ * Put wallets into own folder * Fix generateMutation * remove resolverName property from wallet defs * move function into lib/wallet * use function in generateMutation on client to fix wrongly generated mutation * Separate client and server imports by files * wallets now consist of an index.js, a client.js and a server.js file * client.js is imported on the client and contains the client portion * server.js is imported on the server and contains the server porition * both reexport index.js so everything in index.js can be shared by client and server * every wallet contains a client.js file since they are all imported on the client to show the cards * client.js of every wallet is reexported as an array in wallets/client.js * server.js of every wallet is reexported as an array in wallets/server.js FIXME: for some reason, worker does not properly import the default export of wallets/server.js * Fix worker import of wallets/server * Fix wallet.server usage * I removed wallet.server in a previous commit * the client couldn't determine which wallet was stored on the server since all server specific fields were set in server.js * walletType and walletField are now set in index.js * walletType is now used to determine if a wallet is stored on the server * also included some formatting changes * Fix w.default usage Since package.json with { "type": "module" } was added, this is no longer needed. * Fix id access in walletPrioritySort * Fix autowithdrawal error log * Generate validation schema for LNbits * Generate validation schema for NWC * Rename to torAllowed * Generate validation schema for LNC * Generate validation schema for LND * Generate validation schema for LnAddr * Remove stringTypes * Generate validation schema for CLN * Make clear that message belongs to test * validate.message was used in tandem with validate.test * it might be confused as the message if the validation for validate.type failed * now validate.test can be a function or an object of { test, message } shape which matches Yup.test * Remove validate.schema as a trap door * make lnc work * Return null if no wallet was found * Revert code around schema generation * Transform autowithdrawSchemaMembers into an object * Rename schema to yupSchema * Fix missing required for LNbits adminKey * Support formik form-level validation * Fix missing addWalletLog import * Fix missing space after = * fix merge conflict resolution mistake * remove non-custodial* badges * create guides for attaching wallets in sndev * Use built-in formik validation or Yup schema but not both * Rename: validate -> testConnectClient, testConnect -> testConnectServer * make lnaddr autowithdraw work in dev * move ATTACH docs to ./wallets and add lnaddr doc * Fix missing rename: yupSchema -> fieldValidation * Remove unused context * Add documentation how to add wallets --------- Co-authored-by: keyan <keyan.kousha+huumn@gmail.com> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-07-20 22:51:46 +00:00
return await waitForQrPayment(invoice, walletError)
}, [waitForWalletPayment, waitForQrPayment])
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
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 }
}