371e7417ce
* 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>
174 lines
6.7 KiB
JavaScript
174 lines
6.7 KiB
JavaScript
import { useApolloClient, useLazyQuery, useMutation } from '@apollo/client'
|
|
import { useCallback, useState } from 'react'
|
|
import { InvoiceCanceledError, InvoiceExpiredError, useQrPayment, useWalletPayment } from './payment'
|
|
import { GET_PAID_ACTION } from '@/fragments/paidAction'
|
|
|
|
/*
|
|
this is just like useMutation with a few changes:
|
|
1. pays an invoice returned by the mutation
|
|
2. takes an onPaid and onPayError callback, and additional options for payment behavior
|
|
- namely forceWaitForPayment which will always wait for the invoice to be paid
|
|
- and persistOnNavigate which will keep the invoice in the cache after navigation
|
|
3. onCompleted behaves a little differently, but analogously to useMutation, ie clientside side effects
|
|
of completion can still rely on it
|
|
a. it's called before the invoice is paid for optimistic updates
|
|
b. it's called after the invoice is paid for pessimistic updates
|
|
4. we return a payError field in the result object if the invoice fails to pay
|
|
*/
|
|
export function usePaidMutation (mutation,
|
|
{ onCompleted, ...options } = {}) {
|
|
options.optimisticResponse = addOptimisticResponseExtras(options.optimisticResponse)
|
|
const [mutate, result] = useMutation(mutation, options)
|
|
const [getPaidAction] = useLazyQuery(GET_PAID_ACTION, {
|
|
fetchPolicy: 'network-only'
|
|
})
|
|
const waitForWalletPayment = useWalletPayment()
|
|
const waitForQrPayment = useQrPayment()
|
|
const client = useApolloClient()
|
|
// innerResult is used to store/control the result of the mutation when innerMutate runs
|
|
const [innerResult, setInnerResult] = useState(result)
|
|
|
|
const waitForPayment = useCallback(async (invoice, { alwaysShowQROnFailure = false, persistOnNavigate = false, waitFor }) => {
|
|
let walletError
|
|
const start = Date.now()
|
|
try {
|
|
return await waitForWalletPayment(invoice, waitFor)
|
|
} catch (err) {
|
|
if (
|
|
(!alwaysShowQROnFailure && Date.now() - start > 1000) ||
|
|
err instanceof InvoiceCanceledError ||
|
|
err instanceof InvoiceExpiredError) {
|
|
// bail since qr code payment will also fail
|
|
// also bail if the payment took more than 1 second
|
|
throw err
|
|
}
|
|
walletError = err
|
|
}
|
|
return await waitForQrPayment(invoice, walletError, { persistOnNavigate, waitFor })
|
|
}, [waitForWalletPayment, waitForQrPayment])
|
|
|
|
const innerMutate = useCallback(async ({
|
|
onCompleted: innerOnCompleted, ...innerOptions
|
|
} = {}) => {
|
|
innerOptions.optimisticResponse = addOptimisticResponseExtras(innerOptions.optimisticResponse)
|
|
let { data, ...rest } = await mutate(innerOptions)
|
|
|
|
// use the most inner callbacks/options if they exist
|
|
const { onPaid, onPayError, forceWaitForPayment, persistOnNavigate, update } = { ...options, ...innerOptions }
|
|
const ourOnCompleted = innerOnCompleted || onCompleted
|
|
|
|
// get invoice without knowing the mutation name
|
|
if (Object.values(data).length !== 1) {
|
|
throw new Error('usePaidMutation: exactly one mutation at a time is supported')
|
|
}
|
|
const response = Object.values(data)[0]
|
|
const invoice = response?.invoice
|
|
|
|
// if the mutation returns an invoice, pay it
|
|
if (invoice) {
|
|
// adds payError, escalating to a normal error if the invoice is not canceled or
|
|
// has an actionError
|
|
const addPayError = (e, rest) => ({
|
|
...rest,
|
|
payError: e,
|
|
error: e instanceof InvoiceCanceledError && e.actionError ? e : undefined
|
|
})
|
|
|
|
// should we wait for the invoice to be paid?
|
|
if (response?.paymentMethod === 'OPTIMISTIC' && !forceWaitForPayment) {
|
|
// onCompleted is called before the invoice is paid for optimistic updates
|
|
ourOnCompleted?.(data)
|
|
// don't wait to pay the invoice
|
|
waitForPayment(invoice, { persistOnNavigate }).then(() => {
|
|
onPaid?.(client.cache, { data })
|
|
}).catch(e => {
|
|
console.error('usePaidMutation: failed to pay invoice', e)
|
|
// onPayError is called after the invoice fails to pay
|
|
// useful for updating invoiceActionState to FAILED
|
|
onPayError?.(e, client.cache, { data })
|
|
setInnerResult(r => addPayError(e, r))
|
|
})
|
|
} else {
|
|
// the action is pessimistic
|
|
try {
|
|
// wait for the invoice to be paid
|
|
await waitForPayment(invoice, { alwaysShowQROnFailure: true, persistOnNavigate, waitFor: inv => inv?.actionState === 'PAID' })
|
|
if (!response.result) {
|
|
// if the mutation didn't return any data, ie pessimistic, we need to fetch it
|
|
const { data: { paidAction } } = await getPaidAction({ variables: { invoiceId: parseInt(invoice.id) } })
|
|
// create new data object
|
|
data = { [Object.keys(data)[0]]: paidAction }
|
|
// we need to run update functions on mutations now that we have the data
|
|
update?.(client.cache, { data })
|
|
}
|
|
ourOnCompleted?.(data)
|
|
onPaid?.(client.cache, { data })
|
|
} catch (e) {
|
|
console.error('usePaidMutation: failed to pay invoice', e)
|
|
onPayError?.(e, client.cache, { data })
|
|
rest = addPayError(e, rest)
|
|
}
|
|
}
|
|
} else {
|
|
// fee credits paid for it
|
|
ourOnCompleted?.(data)
|
|
onPaid?.(client.cache, { data })
|
|
}
|
|
|
|
setInnerResult({ data, ...rest })
|
|
return { data, ...rest }
|
|
}, [mutate, options, waitForPayment, onCompleted, client.cache, getPaidAction, setInnerResult])
|
|
|
|
return [innerMutate, innerResult]
|
|
}
|
|
|
|
// all paid actions need these fields and they're easy to forget
|
|
function addOptimisticResponseExtras (optimisticResponse) {
|
|
if (!optimisticResponse) return optimisticResponse
|
|
const key = Object.keys(optimisticResponse)[0]
|
|
optimisticResponse[key] = { invoice: null, paymentMethod: 'OPTIMISTIC', ...optimisticResponse[key] }
|
|
return optimisticResponse
|
|
}
|
|
|
|
// most paid actions have the same cache modifications
|
|
// these let us preemptively update the cache before a query updates it
|
|
export const paidActionCacheMods = {
|
|
update: (cache, { data }) => {
|
|
const response = Object.values(data)[0]
|
|
if (!response?.invoice) return
|
|
const { invoice } = response
|
|
|
|
cache.modify({
|
|
id: `Invoice:${invoice.id}`,
|
|
fields: {
|
|
actionState: () => 'PENDING'
|
|
}
|
|
})
|
|
},
|
|
onPayError: (e, cache, { data }) => {
|
|
const response = Object.values(data)[0]
|
|
if (!response?.invoice) return
|
|
const { invoice } = response
|
|
|
|
cache.modify({
|
|
id: `Invoice:${invoice.id}`,
|
|
fields: {
|
|
actionState: () => 'FAILED'
|
|
}
|
|
})
|
|
},
|
|
onPaid: (cache, { data }) => {
|
|
const response = Object.values(data)[0]
|
|
if (!response?.invoice) return
|
|
const { invoice } = response
|
|
|
|
cache.modify({
|
|
id: `Invoice:${invoice.id}`,
|
|
fields: {
|
|
actionState: () => 'PAID',
|
|
confirmedAt: () => new Date().toISOString()
|
|
}
|
|
})
|
|
}
|
|
}
|