stacker.news/worker/paidAction.js
ekzyis d89a4a429a
Wallet v2 (#2169)
* Migrate vault entries to new schema (#2092)

* Migrate existing vault entries to new schema

* Read+write new vault schema

* Drop VaultEntry table

* Refactor vaultPrismaFragments

* Remove wrong comment

* Remove TODO

* Fix possible race condition on update of vault key

* Remove lib/object.js

* Wallet schema v2 (#2146)

* Add wallet-v2 TODOs

* Update checkWallet

* Wallet list

* Delete almost all wallet v1 code

and add some code for wallet protocol forms

* Define protocol display name in JSON

* Show form per protocol

* Increase max-height of image in form

* Add JSdoc for protocols, form validation

* Use wallet cards again

My wallet list was quite ugly and I couldn't look at it anymore.

* Refactor hooks in wallet provider

* Fix PasswordInput not used

* Read encrypted wallets

* Decrypt wallets

* useWalletQuery now returns decrypted wallets
* Refactor useIndexedDB because its only purpose will be to store the key, so no need for pagination code etc.
* There is still a bug: if the wallet is not decrypted on first render, the form will not see the decrypted value. See TODO.

* Rename protocolJson to protocol

it no longer uses a JSON file

* Fix form not updated with decrypted API key

* Fix wallet template forms

* Fix optional shown as hint

* Rename to mapUserWalletResolveTypes

* Save LNbits send and recv

TODO:

* implement resolvers for other protocols
* fix double update required for trigger?
* add missing validation on server
* add missing network tests
* don't import from wallets/client on server

* Move definitions to lib/wallets.json and lib/protocols

* Fix ProtocolWallet.updated_at not updated by trigger

* Move wallet fragments into wallets/client/fragments/

* move invoice fragments to fragments/invoice.js
* remove some unused fragments that I don't think I also will not use
* move fragments that will be generated in own file

* Move wallet resolvers into wallets/server/resolvers

* Fix missing authorization check on wallet update

* Run all shared code in generic wallet update function

* Fix 'encrypt' flag not set for blink send currency

* Add mutations for all protocols

* Fix macaroon validation

* Fix CLN socket value not set

* Add server-side schema validation

* Fix JSDoc typedef for protocols

* Don't put JSDoc into separate file

* Create test invoices on save

* Also move type resolvers into wallets/server/resolvers

* Fix unconfigured protocols of UserWallet not found

* Fix Blink API key in wallet seed

* Test send payment on save (except LNC)

This does not include LNC because LNC cannot be saved yet

* Check if window.webln is defined on save

* Create new wallets from templates

* Separate protocols in wallets/lib into individual files

* Use justify-content-start for protocol tabs

and larger margin at the top

* Add LNC to client protocols

* Only return wallets from useWallets

* Query decrypted wallets

* Payments with new wallets

* More wallet logos

* Fix TypeError in useIndexedDB

* Add protocol attach docs

* Fix undefined useWalletRecvPrompt import

* Remove outdated TODOs

* First successful zap to new wallets

* Fix walletLogger imports

* Fix sequences

* the sequences for InvoiceForward and DirectPayment were still starting at 1
* when using setval() with two arguments, nextval() will return the second argument+1 (see https://www.postgresql.org/docs/current/functions-sequence.html)

* Rename ProtocolWallet columns

* Remove more outdated TODOs

* Update wallet indicator

* Fix page reset on route change

* Refactor __typename checks into functions

* Refactor protocol selection into own hook

* Add button to detach protocol

* Refetch wallet on save and detach

* Refetch wallets on change

* Always show all templates

* Refactor WalletLink component

* Also put wallet into forms context

* Remove outdated TODOs

* Use useMemo in wallets hooks

* Passphrase modals

* prompt for password if decryption failed
* add button to reveal passphrase on wallet page

TODO:
* remove button if passphrase was revealed or imported
* encrypt wallets with new key on passphrase reveal

* Fix protocol missing as callback dependency

* Encrypt wallets with new key on passphrase export

* Update 'unlock wallets' text

* Rename wallet mutation hooks

* Remove 'removeWallet' mutation

Wallets are automatically deleted when all protocols are deleted

* Passphrase reset

* Use 110px as minimum width for bip39 words

longest bip39 words are 8 characters and they fit into 103px so I rounded up to 110px.

* Also disable passphrase export on save

* Wallet settings

* Fix wallet receive prompt

* Remove unused parameters from postgres function

* Rename UserWallet to Wallet, ProtocolWallet to WalletProtocol

* Use danger variant for button to show passphrase

* Fix inconsistent imports and exports

* Remove outdated TODOs

* wallet logs

* Remove outdated comment

* Make sure wallets are used in priority order

* Separate wallets from templates in reducer

* Fix missing useCallback dependencies

* Refactor with useWalletLogger hook

* Move enabled to WalletProtocol

* Add checkbox to enable/disable protocol

* Fix migration with prod db dump

* Parse Coinos relay URLs

* Skip network tests if only enabled changed

* Allow IndexedDB calls without session

* Add code to migrate old CryptoKey

* first try to use existing CryptoKey before generating a new one
* bump IDB version to delete old object stores and create new ones
* return IDB callbacks with useMemo
* don't delete old IDB right away, wait until next release

* Fix ghost import error

*Sometimes*, I get import errors because it tries to resolve @/wallets/server to wallets/server.js instead of wallets/server/index.js.

For the files in wallets/server, it kind of makes sense because it's a circular import.

But I don't know why the files in worker/ have this problem.

Interestingly, it only seems to happen with walletLogger imports, so I guess its related to its import chain.

Anyway, this commit should make sure this never happens again ...

* Skip wallets queries if not logged in

* Split CUSTOM wallet into NWC and LN_ADDR

* Migrate local wallets

* Link to /wallets/:id/receive if send not supported

* Hide separator if there are no configured wallets

* Save LNC

* Add one-liner to attach LNC

* Update wallet priorities via DnD

* Wallet logs are part of protocol resolvers

* Fix logging to deleted protocol

* Fix trying to fetch logs for template

* also change type to Int so GraphQL layer can catch trying to fetch string IDs as is the case for templates

* Fix embedded flag for wallets logs not set

* Remove TODO

* Decrease max-height for embedded wallet logs on big screens

* Fix missing refetch on wallet priority update

* Set priorities of all wallets in one tx

* Fix nested state update

* Add DragIcon

* DnD mobile support and refactor

* Add CancelButton to wallet settings

* Remount form if path changes

This fixes the following warning in the console:

"""
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
"""

* Support string and object for wallet.image JSON

* Append domain to lightning address inputs

* Remove outdated TODOs

* Add template IDs to wallet JSON

* Fix missing callback dependency

* Implement lightning address save in receive prompt

* Update TODOs

* Fix missing check for enabled

* Pay QR codes with WebLN as anon

* Add logo for NWC

* Fix trying to save logs for template

* Add template logs

* Fix inconsistent margin

* Always throw on missing key

* Remove misleading comment

Wallets are returned even if decryption fails so we can show the unlock page if a wallet is stored as encrypted in the context.

Maybe I should rethink this.

* Check for existing wallets on local wallet migration

* Fix local wallet migration causing duplicates

* Fix protocol reattached on detach due to migration

* Fix form not centered

* Fix ZEUS lightning address domain

* Add placeholder, help, hints etc. to wallet form inputs

* Fix wallet badges not updated

* Remove unused declared variables

* Rename to ATTACH_PAGE

* Fix 500 error if no amount was given to LNURLp endpoint

* Tag log messages with wallet name

* Only skip network tests if we're disabling the wallet

* Rename var to networkTests

* Continue to store key hash in IndexedDB

* Rethink wallet state management

If decryption failed, the function to decrypt the wallets didn't throw but simply returned wallets that were still encrypted.

This was bad because it meant we could not rely on the wallets in the state being decrypted, even though this was the original idea behind the query hooks: hide the details of encryption and decryption inside them.

Because of this, we had to check if the wallets were still encrypted before we ran the wallet migration since we want to check if a protocol already exists.

This commit fixes this by making encryption and decryption always throw (and catching the errors), as well as returning a ready state from hooks. A hook might not be ready because it still needs to load something (in the case of the crypto hooks, it's loading the key from IndexedDB). Callers check that ready state before they call the function returned by the hook.

So now, the wallet migration hook can itself simply check if the hook to encrypt wallets is ready and if the wallets are no longer loading to let callers know if it itself is ready.

Since we also relied on wallets stored as encrypted in the context to show the unlock page, this was also changed by comparing the local and remote key hash.

* Add empty line

* Save new key hash during wallet reset

* Only receive protocol upserts require networkTests param

* Compare key hashes on server on each save

* Delete old code

* Fix card shows attach instead of configure

* Fix empty wallets created during migration

The old schema can contain '' instead of NULL in the columns of wallets for receiving.

* Update reset passphrase text

* Wrap passphrase reset in try/catch

* Fix migrate called multiple times

* Update key hash on migration if not set

* Fetch local wallets in migrate

* Fix missing await on setKey

* Let first device set key hash

* Fix indicator not shown if wallets locked

* Check if IndexedDB is available

* Fix inconsistent WebLN error message

* Disable WebLN if not available

* Remove outdated TODO

* Cursor-based pagination for wallet logs

* Fix log message x-overflow

* Add context to wallet logs

* Wrap errors are warnings in logs

* Rename wallet v2 migrations

* Update wallet status during logging

* Fix wallet logs loading state

The loading state would go from false -> true -> false because it's false when the lazy query wasn't called yet.

* Add wallet search

* Add Alby Go wallet

* Revert "Add Alby Go wallet"

This reverts commit 926c70638f1673756480c848237e52d5889dc037.

* Fix wallet logs sent by client don't update protocol status

* Fix mutation name

* put drag icon on opposite corner

* Add wallets/README.md

* Fix inconsistent case in wallets/README.md

* Fix autoprefixer warning about mixed support

This warning was in the app logs:

app     | Warning
app     |
app     | (31:3) autoprefixer: end value has mixed support, consider using flex-end instead
app     |
app     | Import trace for requested module:
app     | ./styles/wallet.module.css
app     | ./wallets/client/hooks/prompt.js
app     | ./wallets/client/hooks/index.js
app     | ./wallets/client/context/hooks.js
app     | ./wallets/client/context/provider.js
app     | ./wallets/client/context/index.js

* fix effect of wallet indicators on logo

* Fix deleting wallet template logs

* Use name as primary key of WalletTemplate

* Fix wallet_clear_vault trigger not mentioned in README

* Fix wallet receive prompt

Also remove no longer needed templateId from wallets.json and helper functions

* Use findUnique since name is now primary key

* Merge Alby wallets into one

* Remove unused name parameter from WalletsForm component

* Fix number check to decide if wallet or template

* Update wallet encryption on click, not as effect

* add cashu.me and lightning address logos

* add images

* Use recommended typeof to check if IDB available

* Also check if IDB available on delete

* Use constraint triggers

* Add indices on columns used for joins

* Fix inconsistent CLEAR OR REPLACE TRIGGER

* Attach wallet_check_support trigger to WalletProtocol table

* Update wallets/README.md

* Remove debugging code

* Refactor reducer: replace page with status

* Show 'wallets unavailable' if device does not support IndexedDB

* Remove duplicate ELSIF condition

* Fix hasSendWallet

The useSendWallets hook was not checking if the returned send wallets are enabled.

Since the components that used that hook only need to know if there is a send wallet, I replaced the useSendWallets hook with a useHasSendWallet hook.

* Add Cash App wallet

* fix changes loglevel enum

* Fix key init race condition in strict mode if no key exists yet

* Formatting

* Fix key init race condition via transactions in readwrite mode

* Replace Promise.withResolvers with regular promises

* replace generic spinner with our usual

---------

Co-authored-by: k00b <k00b@stacker.news>
2025-07-15 16:36:43 -05:00

477 lines
16 KiB
JavaScript

import { getPaymentFailureStatus, hodlInvoiceCltvDetails, getPaymentOrNotSent } from '@/api/lnd'
import { paidActions } from '@/api/paidAction'
import { walletLogger } from '@/wallets/server/logger'
import { LND_PATHFINDING_TIME_PREF_PPM, LND_PATHFINDING_TIMEOUT_MS, PAID_ACTION_TERMINAL_STATES } from '@/lib/constants'
import { formatSats, msatsToSats, toPositiveNumber } from '@/lib/format'
import { datePivot } from '@/lib/time'
import { Prisma } from '@prisma/client'
import {
cancelHodlInvoice,
getInvoice, parsePaymentRequest,
payViaPaymentRequest, settleHodlInvoice
} from 'ln-service'
import { MIN_SETTLEMENT_CLTV_DELTA } from '@/wallets/server/wrap'
// aggressive finalization retry options
const FINALIZE_OPTIONS = { retryLimit: 2 ** 31 - 1, retryBackoff: false, retryDelay: 5, priority: 1000 }
async function transitionInvoice (jobName,
{ invoiceId, fromState, toState, transition, invoice, onUnexpectedError },
{ models, lnd, boss }
) {
console.group(`${jobName}: transitioning invoice ${invoiceId} from ${fromState} to ${toState}`)
let dbInvoice
try {
const currentDbInvoice = await models.invoice.findUnique({ where: { id: invoiceId } })
console.log('invoice is in state', currentDbInvoice.actionState)
if (PAID_ACTION_TERMINAL_STATES.includes(currentDbInvoice.actionState)) {
console.log('invoice is already in a terminal state, skipping transition')
return
}
if (!Array.isArray(fromState)) {
fromState = [fromState]
}
const lndInvoice = invoice ?? await getInvoice({ id: currentDbInvoice.hash, lnd })
const transitionedInvoice = await models.$transaction(async tx => {
const include = {
user: true,
invoiceForward: {
include: {
invoice: true,
withdrawl: true,
protocol: {
include: {
wallet: true
}
}
}
}
}
// grab optimistic concurrency lock and the invoice
dbInvoice = await tx.invoice.update({
include,
where: {
id: invoiceId,
actionState: {
in: fromState
}
},
data: {
actionState: toState
}
})
// our own optimistic concurrency check
if (!dbInvoice) {
console.log('record not found in our own concurrency check, assuming concurrent worker transitioned it')
return
}
const data = await transition({ lndInvoice, dbInvoice, tx })
if (data) {
return await tx.invoice.update({
include,
where: { id: dbInvoice.id },
data
})
}
return dbInvoice
}, {
isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted,
// we only need to do this because we settleHodlInvoice inside the transaction
// ... and it's prone to timing out
timeout: 60000
})
if (transitionedInvoice) {
console.log('transition succeeded')
return transitionedInvoice
}
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2025') {
console.log('record not found, assuming concurrent worker transitioned it')
return
}
if (e.code === 'P2034') {
console.log('write conflict, assuming concurrent worker is transitioning it')
return
}
}
console.error('unexpected error', e)
onUnexpectedError?.({ error: e, dbInvoice, models, boss })
await boss.send(
jobName,
{ invoiceId },
{ startAfter: datePivot(new Date(), { seconds: 30 }), priority: 1000 })
} finally {
console.groupEnd()
}
}
async function performPessimisticAction ({ lndInvoice, dbInvoice, tx, lnd, boss }) {
const args = { ...dbInvoice.actionArgs, invoiceId: dbInvoice.id }
const context = {
tx,
cost: BigInt(lndInvoice.received_mtokens),
me: dbInvoice.user
}
const sybilFeePercent = await paidActions[dbInvoice.actionType].getSybilFeePercent?.(args, context)
const result = await paidActions[dbInvoice.actionType].perform(args, { ...context, sybilFeePercent })
await tx.invoice.update({
where: { id: dbInvoice.id },
data: {
actionResult: result,
actionError: null
}
})
}
// if we experience an unexpected error when holding an invoice, we need aggressively attempt to cancel it
// store the error in the invoice, nonblocking and outside of this tx, finalizing immediately
function onHeldInvoiceError ({ error, dbInvoice, models, boss }) {
models.invoice.update({
where: { id: dbInvoice.id },
data: {
actionError: error.message
}
}).catch(e => console.error('failed to store action error', e))
boss.send('finalizeHodlInvoice', { hash: dbInvoice.hash }, FINALIZE_OPTIONS)
.catch(e => console.error('failed to finalize', e))
}
export async function paidActionPaid ({ data: { invoiceId, ...args }, models, lnd, boss }) {
const transitionedInvoice = await transitionInvoice('paidActionPaid', {
invoiceId,
fromState: ['HELD', 'PENDING', 'FORWARDED'],
toState: 'PAID',
transition: async ({ lndInvoice, dbInvoice, tx }) => {
if (!lndInvoice.is_confirmed) {
throw new Error('invoice is not confirmed')
}
const updateFields = {
confirmedAt: new Date(lndInvoice.confirmed_at),
confirmedIndex: lndInvoice.confirmed_index,
msatsReceived: BigInt(lndInvoice.received_mtokens)
}
await paidActions[dbInvoice.actionType].onPaid?.({
invoice: { ...dbInvoice, ...updateFields }
}, { models, tx, lnd })
// most paid actions are eligible for a cowboy hat streak
await tx.$executeRaw`
INSERT INTO pgboss.job (name, data)
VALUES ('checkStreak', jsonb_build_object('id', ${dbInvoice.userId}, 'type', 'COWBOY_HAT'))`
return updateFields
},
...args
}, { models, lnd, boss })
if (transitionedInvoice) {
// run non critical side effects in the background
// after the transaction has been committed
paidActions[transitionedInvoice.actionType]
.nonCriticalSideEffects?.({ invoice: transitionedInvoice }, { models, lnd })
.catch(console.error)
}
}
// this performs forward creating the outgoing payment
export async function paidActionForwarding ({ data: { invoiceId, ...args }, models, lnd, boss }) {
const transitionedInvoice = await transitionInvoice('paidActionForwarding', {
invoiceId,
fromState: 'PENDING_HELD',
toState: 'FORWARDING',
transition: async ({ lndInvoice, dbInvoice, tx }) => {
if (!lndInvoice.is_held) {
throw new Error('invoice is not held')
}
const { invoiceForward } = dbInvoice
if (!invoiceForward) {
throw new Error('invoice is not associated with a forward')
}
const { expiryHeight, acceptHeight } = hodlInvoiceCltvDetails(lndInvoice)
const { bolt11, maxFeeMsats } = invoiceForward
const invoice = await parsePaymentRequest({ request: bolt11 })
// maxTimeoutDelta is the number of blocks left for the outgoing payment to settle
const maxTimeoutDelta = toPositiveNumber(expiryHeight) - toPositiveNumber(acceptHeight) - MIN_SETTLEMENT_CLTV_DELTA
if (maxTimeoutDelta - toPositiveNumber(invoice.cltv_delta) < 0) {
// the payment will certainly fail, so we can
// cancel and allow transition from PENDING[_HELD] -> FAILED
boss.send('finalizeHodlInvoice', { hash: dbInvoice.hash }, FINALIZE_OPTIONS)
.catch(e => console.error('failed to finalize', e))
throw new Error('invoice has insufficient cltv delta for forward')
}
// if this is a pessimistic action, we want to perform it now
// ... we don't want it to fail after the outgoing payment is in flight
if (!dbInvoice.actionOptimistic) {
await performPessimisticAction({ lndInvoice, dbInvoice, tx, models, lnd, boss })
}
return {
isHeld: true,
msatsReceived: BigInt(lndInvoice.received_mtokens),
invoiceForward: {
update: {
expiryHeight,
acceptHeight,
withdrawl: {
create: {
hash: invoice.id,
bolt11,
msatsPaying: BigInt(invoice.mtokens),
msatsFeePaying: maxFeeMsats,
autoWithdraw: true,
protocolId: invoiceForward.protocolId,
userId: invoiceForward.protocol.wallet.userId
}
}
}
}
}
},
onUnexpectedError: onHeldInvoiceError,
...args
}, { models, lnd, boss })
// only pay if we successfully transitioned which can only happen once
// we can't do this inside the transaction because it isn't necessarily idempotent
if (transitionedInvoice?.invoiceForward) {
const { bolt11, maxFeeMsats, expiryHeight, acceptHeight } = transitionedInvoice.invoiceForward
// give ourselves at least MIN_SETTLEMENT_CLTV_DELTA blocks to settle the incoming payment
const maxTimeoutHeight = toPositiveNumber(toPositiveNumber(expiryHeight) - MIN_SETTLEMENT_CLTV_DELTA)
console.log('forwarding with max fee', maxFeeMsats, 'max_timeout_height', maxTimeoutHeight,
'accept_height', acceptHeight, 'expiry_height', expiryHeight)
payViaPaymentRequest({
lnd,
request: bolt11,
max_fee_mtokens: String(maxFeeMsats),
pathfinding_timeout: LND_PATHFINDING_TIMEOUT_MS,
confidence: LND_PATHFINDING_TIME_PREF_PPM,
max_timeout_height: maxTimeoutHeight
}).catch(console.error)
}
}
// this finalizes the forward by settling the incoming invoice after the outgoing payment is confirmed
export async function paidActionForwarded ({ data: { invoiceId, withdrawal, ...args }, models, lnd, boss }) {
const transitionedInvoice = await transitionInvoice('paidActionForwarded', {
invoiceId,
fromState: 'FORWARDING',
toState: 'FORWARDED',
transition: async ({ lndInvoice, dbInvoice, tx }) => {
if (!(lndInvoice.is_held || lndInvoice.is_confirmed)) {
throw new Error('invoice is not held')
}
const { hash, msatsPaying, createdAt } = dbInvoice.invoiceForward.withdrawl
const { payment, is_confirmed: isConfirmed } = withdrawal ??
await getPaymentOrNotSent({ id: hash, lnd, createdAt })
if (!isConfirmed) {
throw new Error('payment is not confirmed')
}
// settle the invoice, allowing us to transition to PAID
await settleHodlInvoice({ secret: payment.secret, lnd })
return {
preimage: payment.secret,
invoiceForward: {
update: {
withdrawl: {
update: {
status: 'CONFIRMED',
msatsPaid: msatsPaying,
msatsFeePaid: BigInt(payment.fee_mtokens),
preimage: payment.secret
}
}
}
}
}
},
...args
}, { models, lnd, boss })
if (transitionedInvoice) {
const { withdrawl, protocol } = transitionedInvoice.invoiceForward
const logger = walletLogger({
models,
protocolId: protocol.id,
userId: protocol.wallet.userId,
invoiceId: transitionedInvoice.id,
withdrawalId: withdrawl.id
})
logger.ok(`↙ payment received: ${formatSats(msatsToSats(Number(withdrawl.msatsPaid)))}`)
}
return transitionedInvoice
}
// when the pending forward fails, we need to cancel the incoming invoice
export async function paidActionFailedForward ({ data: { invoiceId, withdrawal: pWithdrawal, ...args }, models, lnd, boss }) {
let message
const transitionedInvoice = await transitionInvoice('paidActionFailedForward', {
invoiceId,
fromState: 'FORWARDING',
toState: 'FAILED_FORWARD',
transition: async ({ lndInvoice, dbInvoice, tx }) => {
if (!(lndInvoice.is_held || lndInvoice.is_cancelled)) {
throw new Error('invoice is not held')
}
const { hash, createdAt } = dbInvoice.invoiceForward.withdrawl
const withdrawal = pWithdrawal ?? await getPaymentOrNotSent({ id: hash, lnd, createdAt })
if (!(withdrawal?.is_failed || withdrawal?.notSent)) {
throw new Error('payment has not failed')
}
// cancel to transition to FAILED ... this is really important we do not transition unless this call succeeds
// which once it does succeed will ensure we will try to cancel the held invoice until it actually cancels
await boss.send('finalizeHodlInvoice', { hash: dbInvoice.hash }, FINALIZE_OPTIONS)
const { status, message: failureMessage } = getPaymentFailureStatus(withdrawal)
message = failureMessage
return {
invoiceForward: {
update: {
withdrawl: {
update: {
status
}
}
}
}
}
},
...args
}, { models, lnd, boss })
if (transitionedInvoice) {
const { withdrawl, protocol } = transitionedInvoice.invoiceForward
const logger = walletLogger({
models,
protocolId: protocol.id,
userId: protocol.wallet.userId,
invoiceId: transitionedInvoice.id,
withdrawalId: withdrawl.id
})
logger.warn(`incoming payment failed: ${message}`)
}
return transitionedInvoice
}
export async function paidActionHeld ({ data: { invoiceId, ...args }, models, lnd, boss }) {
return await transitionInvoice('paidActionHeld', {
invoiceId,
fromState: 'PENDING_HELD',
toState: 'HELD',
transition: async ({ lndInvoice, dbInvoice, tx }) => {
// XXX allow both held and confirmed invoices to do this transition
// because it's possible for a prior settleHodlInvoice to have succeeded but
// timeout and rollback the transaction, leaving the invoice in a pending_held state
if (!(lndInvoice.is_held || lndInvoice.is_confirmed)) {
throw new Error('invoice is not held')
}
if (dbInvoice.invoiceForward) {
throw new Error('invoice is associated with a forward')
}
// make sure settled or cancelled in 60 seconds to minimize risk of force closures
const expiresAt = new Date(Math.min(dbInvoice.expiresAt, datePivot(new Date(), { seconds: 60 })))
boss.send('finalizeHodlInvoice', { hash: dbInvoice.hash }, { startAfter: expiresAt, ...FINALIZE_OPTIONS })
.catch(e => console.error('failed to finalize', e))
// perform the action now that we have the funds
await performPessimisticAction({ lndInvoice, dbInvoice, tx, models, lnd, boss })
// settle the invoice, allowing us to transition to PAID
await settleHodlInvoice({ secret: dbInvoice.preimage, lnd })
return {
isHeld: true,
msatsReceived: BigInt(lndInvoice.received_mtokens)
}
},
onUnexpectedError: onHeldInvoiceError,
...args
}, { models, lnd, boss })
}
export async function paidActionCanceling ({ data: { invoiceId, ...args }, models, lnd, boss }) {
const transitionedInvoice = await transitionInvoice('paidActionCanceling', {
invoiceId,
fromState: ['HELD', 'PENDING', 'PENDING_HELD', 'FAILED_FORWARD'],
toState: 'CANCELING',
transition: async ({ lndInvoice, dbInvoice, tx }) => {
if (lndInvoice.is_confirmed) {
throw new Error('invoice is confirmed already')
}
await cancelHodlInvoice({ id: dbInvoice.hash, lnd })
},
...args
}, { models, lnd, boss })
if (transitionedInvoice) {
if (transitionedInvoice.invoiceForward) {
const { protocol, bolt11 } = transitionedInvoice.invoiceForward
const logger = walletLogger({
models,
protocolId: protocol.id,
userId: protocol.wallet.userId,
invoiceId: transitionedInvoice.id
})
const decoded = await parsePaymentRequest({ request: bolt11 })
logger.info(`invoice for ${formatSats(msatsToSats(decoded.mtokens))} canceled by payer`)
}
}
return transitionedInvoice
}
export async function paidActionFailed ({ data: { invoiceId, ...args }, models, lnd, boss }) {
return await transitionInvoice('paidActionFailed', {
invoiceId,
// any of these states can transition to FAILED
fromState: ['PENDING', 'PENDING_HELD', 'HELD', 'FAILED_FORWARD', 'CANCELING'],
toState: 'FAILED',
transition: async ({ lndInvoice, dbInvoice, tx }) => {
if (!lndInvoice.is_canceled) {
throw new Error('invoice is not cancelled')
}
await paidActions[dbInvoice.actionType].onFail?.({ invoice: dbInvoice }, { models, tx, lnd })
return {
cancelled: true,
cancelledAt: new Date()
}
},
...args
}, { models, lnd, boss })
}