2024-03-20 00:37:31 +00:00
|
|
|
import serialize from '@/api/resolvers/serial.js'
|
2024-01-08 22:37:58 +00:00
|
|
|
import {
|
2024-02-14 23:31:25 +00:00
|
|
|
getInvoice, getPayment, cancelHodlInvoice, deletePayment,
|
2024-01-08 22:37:58 +00:00
|
|
|
subscribeToInvoices, subscribeToPayments, subscribeToInvoice
|
|
|
|
} from 'ln-service'
|
2024-03-25 23:47:23 +00:00
|
|
|
import { notifyDeposit, notifyWithdrawal } from '@/lib/webPush'
|
2024-08-13 14:48:30 +00:00
|
|
|
import { INVOICE_RETENTION_DAYS, LND_PATHFINDING_TIMEOUT_MS } from '@/lib/constants'
|
2024-03-20 00:37:31 +00:00
|
|
|
import { datePivot, sleep } from '@/lib/time.js'
|
2024-01-10 15:50:42 +00:00
|
|
|
import retry from 'async-retry'
|
2024-04-16 18:59:46 +00:00
|
|
|
import { addWalletLog } from '@/api/resolvers/wallet'
|
|
|
|
import { msatsToSats, numWithUnits } from '@/lib/format'
|
2024-08-13 14:48:30 +00:00
|
|
|
import {
|
|
|
|
paidActionPaid, paidActionForwarded,
|
|
|
|
paidActionFailedForward, paidActionHeld, paidActionFailed,
|
|
|
|
paidActionForwarding,
|
|
|
|
paidActionCanceling
|
|
|
|
} from './paidAction.js'
|
2022-01-17 17:41:17 +00:00
|
|
|
|
2024-01-08 22:37:58 +00:00
|
|
|
export async function subscribeToWallet (args) {
|
|
|
|
await subscribeToDeposits(args)
|
|
|
|
await subscribeToWithdrawals(args)
|
|
|
|
}
|
|
|
|
|
2024-01-10 15:50:42 +00:00
|
|
|
// lnd subscriptions can fail, so they need to be retried
|
|
|
|
function subscribeForever (subscribe) {
|
|
|
|
retry(async bail => {
|
|
|
|
let sub
|
|
|
|
try {
|
|
|
|
return await new Promise((resolve, reject) => {
|
2024-04-02 19:36:00 +00:00
|
|
|
sub = subscribe(resolve, bail)
|
2024-01-10 15:50:42 +00:00
|
|
|
if (!sub) {
|
2024-01-20 22:57:52 +00:00
|
|
|
return bail(new Error('function passed to subscribeForever must return a subscription object or promise'))
|
|
|
|
}
|
|
|
|
if (sub.then) {
|
|
|
|
// sub is promise
|
|
|
|
sub.then(sub => sub.on('error', reject))
|
|
|
|
} else {
|
|
|
|
sub.on('error', reject)
|
2024-01-10 15:50:42 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
} catch (error) {
|
2024-01-07 17:00:24 +00:00
|
|
|
console.error(error)
|
2024-01-10 15:50:42 +00:00
|
|
|
throw new Error('error subscribing - trying again')
|
|
|
|
} finally {
|
|
|
|
sub?.removeAllListeners()
|
|
|
|
}
|
|
|
|
},
|
|
|
|
// retry every .1-10 seconds forever
|
|
|
|
{ forever: true, minTimeout: 100, maxTimeout: 10000, onRetry: e => console.error(e.message) })
|
|
|
|
}
|
|
|
|
|
2024-01-08 22:37:58 +00:00
|
|
|
const logEvent = (name, args) => console.log(`event ${name} triggered with args`, args)
|
|
|
|
const logEventError = (name, error) => console.error(`error running ${name}`, error)
|
|
|
|
|
|
|
|
async function subscribeToDeposits (args) {
|
|
|
|
const { models, lnd } = args
|
|
|
|
|
2024-01-20 22:57:52 +00:00
|
|
|
subscribeForever(async () => {
|
|
|
|
const [lastConfirmed] = await models.$queryRaw`
|
2024-01-08 22:37:58 +00:00
|
|
|
SELECT "confirmedIndex"
|
|
|
|
FROM "Invoice"
|
|
|
|
ORDER BY "confirmedIndex" DESC NULLS LAST
|
|
|
|
LIMIT 1`
|
2024-01-10 15:50:42 +00:00
|
|
|
const sub = subscribeToInvoices({ lnd, confirmed_after: lastConfirmed?.confirmedIndex })
|
|
|
|
|
|
|
|
sub.on('invoice_updated', async (inv) => {
|
|
|
|
try {
|
2024-08-13 14:48:30 +00:00
|
|
|
logEvent('invoice_updated', inv)
|
2024-01-10 15:50:42 +00:00
|
|
|
if (inv.secret) {
|
|
|
|
await checkInvoice({ data: { hash: inv.id }, ...args })
|
|
|
|
} else {
|
|
|
|
// this is a HODL invoice. We need to use SubscribeToInvoice which has is_held transitions
|
|
|
|
// https://api.lightning.community/api/lnd/invoices/subscribe-single-invoice
|
|
|
|
// SubscribeToInvoices is only for invoice creation and settlement transitions
|
|
|
|
// https://api.lightning.community/api/lnd/lightning/subscribe-invoices
|
|
|
|
subscribeToHodlInvoice({ hash: inv.id, ...args })
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
logEventError('invoice_updated', error)
|
2024-01-08 22:37:58 +00:00
|
|
|
}
|
2024-01-10 15:50:42 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
return sub
|
2024-01-08 22:37:58 +00:00
|
|
|
})
|
2022-01-17 17:41:17 +00:00
|
|
|
|
2024-07-01 17:02:29 +00:00
|
|
|
// check pending deposits as a redundancy in case we failed to rehcord
|
2024-01-08 22:37:58 +00:00
|
|
|
// an invoice_updated event
|
|
|
|
await checkPendingDeposits(args)
|
|
|
|
}
|
|
|
|
|
2024-01-10 15:50:42 +00:00
|
|
|
function subscribeToHodlInvoice (args) {
|
|
|
|
const { lnd, hash } = args
|
|
|
|
|
|
|
|
subscribeForever((resolve, reject) => {
|
|
|
|
const sub = subscribeToInvoice({ id: hash, lnd })
|
|
|
|
|
|
|
|
sub.on('invoice_updated', async (inv) => {
|
|
|
|
logEvent('hodl_invoice_updated', inv)
|
|
|
|
try {
|
2024-08-13 14:48:30 +00:00
|
|
|
await checkInvoice({ data: { hash: inv.id }, ...args })
|
|
|
|
// after settle or confirm we can stop listening for updates
|
|
|
|
if (inv.is_confirmed || inv.is_canceled) {
|
2024-01-10 15:50:42 +00:00
|
|
|
resolve()
|
2024-01-08 22:37:58 +00:00
|
|
|
}
|
2024-01-10 15:50:42 +00:00
|
|
|
} catch (error) {
|
|
|
|
logEventError('hodl_invoice_updated', error)
|
|
|
|
reject(error)
|
|
|
|
}
|
2024-01-08 22:37:58 +00:00
|
|
|
})
|
2024-01-10 15:50:42 +00:00
|
|
|
|
|
|
|
return sub
|
|
|
|
})
|
2024-01-08 22:37:58 +00:00
|
|
|
}
|
2022-01-17 17:41:17 +00:00
|
|
|
|
2024-07-01 17:02:29 +00:00
|
|
|
export async function checkInvoice ({ data: { hash }, boss, models, lnd }) {
|
2024-01-08 22:37:58 +00:00
|
|
|
const inv = await getInvoice({ id: hash, lnd })
|
2023-08-31 02:48:49 +00:00
|
|
|
|
2024-01-08 22:37:58 +00:00
|
|
|
// invoice could be created by LND but wasn't inserted into the database yet
|
|
|
|
// this is expected and the function will be called again with the updates
|
2024-08-13 14:48:30 +00:00
|
|
|
const dbInv = await models.invoice.findUnique({
|
|
|
|
where: { hash },
|
|
|
|
include: {
|
|
|
|
invoiceForward: {
|
|
|
|
include: {
|
|
|
|
withdrawl: true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2024-01-08 22:37:58 +00:00
|
|
|
if (!dbInv) {
|
|
|
|
console.log('invoice not found in database', hash)
|
|
|
|
return
|
|
|
|
}
|
2023-08-31 02:48:49 +00:00
|
|
|
|
2024-01-08 22:37:58 +00:00
|
|
|
if (inv.is_confirmed) {
|
2024-07-01 17:02:29 +00:00
|
|
|
if (dbInv.actionType) {
|
2024-08-13 14:48:30 +00:00
|
|
|
return await paidActionPaid({ data: { invoiceId: dbInv.id }, models, lnd, boss })
|
2024-07-01 17:02:29 +00:00
|
|
|
}
|
|
|
|
|
2024-01-08 22:37:58 +00:00
|
|
|
// NOTE: confirm invoice prevents double confirmations (idempotent)
|
|
|
|
// ALSO: is_confirmed and is_held are mutually exclusive
|
|
|
|
// that is, a hold invoice will first be is_held but not is_confirmed
|
|
|
|
// and once it's settled it will be is_confirmed but not is_held
|
2024-04-10 00:49:20 +00:00
|
|
|
const [[{ confirm_invoice: code }]] = await serialize([
|
2024-03-19 20:43:29 +00:00
|
|
|
models.$queryRaw`SELECT confirm_invoice(${inv.id}, ${Number(inv.received_mtokens)})`,
|
2024-01-08 22:37:58 +00:00
|
|
|
models.invoice.update({ where: { hash }, data: { confirmedIndex: inv.confirmed_index } })
|
2024-04-10 00:49:20 +00:00
|
|
|
], { models })
|
2024-01-08 22:37:58 +00:00
|
|
|
|
2024-02-16 18:27:15 +00:00
|
|
|
// don't send notifications for JIT invoices
|
2024-01-08 22:37:58 +00:00
|
|
|
if (dbInv.preimage) return
|
2024-03-19 20:43:29 +00:00
|
|
|
if (code === 0) {
|
2024-03-19 22:43:04 +00:00
|
|
|
notifyDeposit(dbInv.userId, { comment: dbInv.comment, ...inv })
|
2024-03-19 20:43:29 +00:00
|
|
|
}
|
|
|
|
|
2024-01-08 22:37:58 +00:00
|
|
|
return await boss.send('nip57', { hash })
|
2023-11-21 23:32:22 +00:00
|
|
|
}
|
2023-08-31 02:48:49 +00:00
|
|
|
|
2024-01-10 15:50:42 +00:00
|
|
|
if (inv.is_held) {
|
2024-07-01 17:02:29 +00:00
|
|
|
if (dbInv.actionType) {
|
2024-08-13 14:48:30 +00:00
|
|
|
if (dbInv.invoiceForward) {
|
|
|
|
if (dbInv.invoiceForward.withdrawl) {
|
|
|
|
// transitions when held are dependent on the withdrawl status
|
|
|
|
return await checkWithdrawal({ data: { hash: dbInv.invoiceForward.withdrawl.hash }, models, lnd, boss })
|
|
|
|
}
|
|
|
|
return await paidActionForwarding({ data: { invoiceId: dbInv.id }, models, lnd, boss })
|
|
|
|
}
|
|
|
|
return await paidActionHeld({ data: { invoiceId: dbInv.id }, models, lnd, boss })
|
2024-07-01 17:02:29 +00:00
|
|
|
}
|
2024-02-16 18:27:15 +00:00
|
|
|
// First query makes sure that after payment, JIT invoices are settled
|
2024-02-01 16:05:16 +00:00
|
|
|
// within 60 seconds or they will be canceled to minimize risk of
|
|
|
|
// force closures or wallets banning us.
|
|
|
|
// Second query is basically confirm_invoice without setting confirmed_at
|
2024-01-10 15:50:42 +00:00
|
|
|
// and without setting the user balance
|
|
|
|
// those will be set when the invoice is settled by user action
|
2024-02-01 16:05:16 +00:00
|
|
|
const expiresAt = new Date(Math.min(dbInv.expiresAt, datePivot(new Date(), { seconds: 60 })))
|
2024-04-10 00:49:20 +00:00
|
|
|
return await serialize([
|
2024-02-01 16:05:16 +00:00
|
|
|
models.$queryRaw`
|
|
|
|
INSERT INTO pgboss.job (name, data, retrylimit, retrybackoff, startafter)
|
|
|
|
VALUES ('finalizeHodlInvoice', jsonb_build_object('hash', ${hash}), 21, true, ${expiresAt})`,
|
|
|
|
models.invoice.update({
|
|
|
|
where: { hash },
|
|
|
|
data: {
|
|
|
|
msatsReceived: Number(inv.received_mtokens),
|
|
|
|
expiresAt,
|
|
|
|
isHeld: true
|
|
|
|
}
|
2024-04-10 00:49:20 +00:00
|
|
|
})
|
|
|
|
], { models })
|
2024-01-10 15:50:42 +00:00
|
|
|
}
|
|
|
|
|
2023-11-21 23:32:22 +00:00
|
|
|
if (inv.is_canceled) {
|
2024-07-01 17:02:29 +00:00
|
|
|
if (dbInv.actionType) {
|
2024-08-13 14:48:30 +00:00
|
|
|
return await paidActionFailed({ data: { invoiceId: dbInv.id }, models, lnd, boss })
|
2024-07-01 17:02:29 +00:00
|
|
|
}
|
|
|
|
|
2024-04-10 00:49:20 +00:00
|
|
|
return await serialize(
|
2023-11-21 23:32:22 +00:00
|
|
|
models.invoice.update({
|
|
|
|
where: {
|
|
|
|
hash: inv.id
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
cancelled: true
|
|
|
|
}
|
2024-04-10 00:49:20 +00:00
|
|
|
}), { models }
|
|
|
|
)
|
2023-11-21 23:32:22 +00:00
|
|
|
}
|
2024-01-08 22:37:58 +00:00
|
|
|
}
|
2023-08-31 02:48:49 +00:00
|
|
|
|
2024-01-08 22:37:58 +00:00
|
|
|
async function subscribeToWithdrawals (args) {
|
|
|
|
const { lnd } = args
|
2023-08-31 02:48:49 +00:00
|
|
|
|
2024-01-08 22:37:58 +00:00
|
|
|
// https://www.npmjs.com/package/ln-service#subscribetopayments
|
2024-01-10 15:50:42 +00:00
|
|
|
subscribeForever(() => {
|
|
|
|
const sub = subscribeToPayments({ lnd })
|
|
|
|
|
|
|
|
sub.on('confirmed', async (payment) => {
|
|
|
|
logEvent('confirmed', payment)
|
|
|
|
try {
|
|
|
|
await checkWithdrawal({ data: { hash: payment.id }, ...args })
|
|
|
|
} catch (error) {
|
|
|
|
logEventError('confirmed', error)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
sub.on('failed', async (payment) => {
|
|
|
|
logEvent('failed', payment)
|
|
|
|
try {
|
|
|
|
await checkWithdrawal({ data: { hash: payment.id }, ...args })
|
|
|
|
} catch (error) {
|
|
|
|
logEventError('failed', error)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
return sub
|
2024-01-08 22:37:58 +00:00
|
|
|
})
|
2023-08-31 02:48:49 +00:00
|
|
|
|
2024-01-08 22:37:58 +00:00
|
|
|
// check pending withdrawals since they might have been paid while worker was down
|
|
|
|
await checkPendingWithdrawals(args)
|
2022-01-17 17:41:17 +00:00
|
|
|
}
|
|
|
|
|
2024-08-13 14:48:30 +00:00
|
|
|
export async function checkWithdrawal ({ data: { hash }, boss, models, lnd }) {
|
|
|
|
const dbWdrwl = await models.withdrawl.findFirst({
|
|
|
|
where: {
|
|
|
|
hash
|
|
|
|
},
|
|
|
|
include: {
|
|
|
|
wallet: true,
|
|
|
|
invoiceForward: {
|
|
|
|
orderBy: { createdAt: 'desc' },
|
|
|
|
include: {
|
|
|
|
invoice: true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2024-01-08 22:37:58 +00:00
|
|
|
if (!dbWdrwl) {
|
|
|
|
// [WARNING] LND paid an invoice that wasn't created via the SN GraphQL API.
|
|
|
|
// >>> an adversary might be draining our funds right now <<<
|
|
|
|
console.error('unexpected outgoing payment detected:', hash)
|
|
|
|
// TODO: log this in Slack
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-13 14:48:30 +00:00
|
|
|
// already recorded and no invoiceForward to handle
|
|
|
|
if (dbWdrwl.status && dbWdrwl.invoiceForward.length === 0) return
|
|
|
|
|
2023-11-21 23:32:22 +00:00
|
|
|
let wdrwl
|
2024-08-13 14:48:30 +00:00
|
|
|
let notSent = false
|
2023-11-21 23:32:22 +00:00
|
|
|
try {
|
|
|
|
wdrwl = await getPayment({ id: hash, lnd })
|
|
|
|
} catch (err) {
|
2024-08-13 14:48:30 +00:00
|
|
|
if (err[1] === 'SentPaymentNotFound' &&
|
|
|
|
dbWdrwl.createdAt < datePivot(new Date(), { milliseconds: -LND_PATHFINDING_TIMEOUT_MS * 2 })) {
|
|
|
|
// if the payment is older than 2x timeout, but not found in LND, we can assume it errored before lnd stored it
|
|
|
|
notSent = true
|
2023-11-21 23:32:22 +00:00
|
|
|
} else {
|
2024-08-13 14:48:30 +00:00
|
|
|
throw err
|
2022-01-17 17:41:17 +00:00
|
|
|
}
|
2023-11-21 23:32:22 +00:00
|
|
|
}
|
2022-01-17 17:41:17 +00:00
|
|
|
|
2023-11-21 23:32:22 +00:00
|
|
|
if (wdrwl?.is_confirmed) {
|
2024-08-13 14:48:30 +00:00
|
|
|
if (dbWdrwl.invoiceForward.length > 0) {
|
|
|
|
return await paidActionForwarded({ data: { invoiceId: dbWdrwl.invoiceForward[0].invoice.id }, models, lnd, boss })
|
|
|
|
}
|
|
|
|
|
2023-11-21 23:32:22 +00:00
|
|
|
const fee = Number(wdrwl.payment.fee_mtokens)
|
|
|
|
const paid = Number(wdrwl.payment.mtokens) - fee
|
2024-04-10 00:49:20 +00:00
|
|
|
const [{ confirm_withdrawl: code }] = await serialize(
|
|
|
|
models.$queryRaw`SELECT confirm_withdrawl(${dbWdrwl.id}::INTEGER, ${paid}, ${fee})`,
|
|
|
|
{ models }
|
|
|
|
)
|
2024-03-25 23:47:23 +00:00
|
|
|
if (code === 0) {
|
|
|
|
notifyWithdrawal(dbWdrwl.userId, wdrwl)
|
2024-04-30 01:39:31 +00:00
|
|
|
if (dbWdrwl.wallet) {
|
|
|
|
// this was an autowithdrawal
|
2024-08-13 14:48:30 +00:00
|
|
|
const message = `autowithdrawal of ${
|
|
|
|
numWithUnits(msatsToSats(paid), { abbreviate: false })} with ${
|
|
|
|
numWithUnits(msatsToSats(fee), { abbreviate: false })} as fee`
|
2024-08-13 14:53:44 +00:00
|
|
|
await addWalletLog({ wallet: dbWdrwl.wallet, level: 'SUCCESS', message }, { models })
|
2024-04-30 01:39:31 +00:00
|
|
|
}
|
2024-04-16 18:59:46 +00:00
|
|
|
}
|
2024-08-13 14:48:30 +00:00
|
|
|
} else if (wdrwl?.is_failed || notSent) {
|
|
|
|
if (dbWdrwl.invoiceForward.length > 0) {
|
|
|
|
return await paidActionFailedForward({ data: { invoiceId: dbWdrwl.invoiceForward[0].invoice.id }, models, lnd, boss })
|
|
|
|
}
|
|
|
|
|
2024-04-16 18:59:46 +00:00
|
|
|
let status = 'UNKNOWN_FAILURE'; let message = 'unknown failure'
|
2023-11-21 23:32:22 +00:00
|
|
|
if (wdrwl?.failed.is_insufficient_balance) {
|
|
|
|
status = 'INSUFFICIENT_BALANCE'
|
2024-04-16 18:59:46 +00:00
|
|
|
message = "you didn't have enough sats"
|
2023-11-21 23:32:22 +00:00
|
|
|
} else if (wdrwl?.failed.is_invalid_payment) {
|
|
|
|
status = 'INVALID_PAYMENT'
|
2024-04-16 18:59:46 +00:00
|
|
|
message = 'invalid payment'
|
2023-11-21 23:32:22 +00:00
|
|
|
} else if (wdrwl?.failed.is_pathfinding_timeout) {
|
|
|
|
status = 'PATHFINDING_TIMEOUT'
|
2024-04-16 18:59:46 +00:00
|
|
|
message = 'no route found'
|
2023-11-21 23:32:22 +00:00
|
|
|
} else if (wdrwl?.failed.is_route_not_found) {
|
|
|
|
status = 'ROUTE_NOT_FOUND'
|
2024-04-16 18:59:46 +00:00
|
|
|
message = 'no route found'
|
2022-01-17 17:41:17 +00:00
|
|
|
}
|
2024-01-08 22:37:58 +00:00
|
|
|
|
2024-04-30 01:39:31 +00:00
|
|
|
const [{ reverse_withdrawl: code }] = await serialize(
|
|
|
|
models.$queryRaw`
|
2024-04-10 00:49:20 +00:00
|
|
|
SELECT reverse_withdrawl(${dbWdrwl.id}::INTEGER, ${status}::"WithdrawlStatus")`,
|
|
|
|
{ models }
|
2024-01-08 22:37:58 +00:00
|
|
|
)
|
2024-04-16 18:59:46 +00:00
|
|
|
|
2024-04-30 01:39:31 +00:00
|
|
|
if (code === 0 && dbWdrwl.wallet) {
|
2024-04-16 18:59:46 +00:00
|
|
|
// add error into log for autowithdrawal
|
2024-04-30 01:39:31 +00:00
|
|
|
await addWalletLog({
|
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: dbWdrwl.wallet,
|
2024-04-16 18:59:46 +00:00
|
|
|
level: 'ERROR',
|
|
|
|
message: 'autowithdrawal failed: ' + message
|
2024-08-13 14:53:44 +00:00
|
|
|
}, { models })
|
2024-04-16 18:59:46 +00:00
|
|
|
}
|
2022-01-17 17:41:17 +00:00
|
|
|
}
|
|
|
|
}
|
2023-11-09 17:50:43 +00:00
|
|
|
|
2024-02-14 23:31:25 +00:00
|
|
|
export async function autoDropBolt11s ({ models, lnd }) {
|
|
|
|
const retention = `${INVOICE_RETENTION_DAYS} days`
|
|
|
|
|
|
|
|
// This query will update the withdrawls and return what the hash and bol11 values were before the update
|
|
|
|
const invoices = await models.$queryRaw`
|
|
|
|
WITH to_be_updated AS (
|
|
|
|
SELECT id, hash, bolt11
|
|
|
|
FROM "Withdrawl"
|
|
|
|
WHERE "userId" IN (SELECT id FROM users WHERE "autoDropBolt11s")
|
|
|
|
AND now() > created_at + interval '${retention}'
|
|
|
|
AND hash IS NOT NULL
|
2024-08-13 14:48:30 +00:00
|
|
|
AND status IS NOT NULL
|
2024-02-14 23:31:25 +00:00
|
|
|
), updated_rows AS (
|
|
|
|
UPDATE "Withdrawl"
|
|
|
|
SET hash = NULL, bolt11 = NULL
|
|
|
|
FROM to_be_updated
|
|
|
|
WHERE "Withdrawl".id = to_be_updated.id)
|
|
|
|
SELECT * FROM to_be_updated;`
|
|
|
|
|
|
|
|
if (invoices.length > 0) {
|
|
|
|
for (const invoice of invoices) {
|
|
|
|
try {
|
|
|
|
await deletePayment({ id: invoice.hash, lnd })
|
|
|
|
} catch (error) {
|
|
|
|
console.error(`Error removing invoice with hash ${invoice.hash}:`, error)
|
|
|
|
await models.withdrawl.update({
|
|
|
|
where: { id: invoice.id },
|
|
|
|
data: { hash: invoice.hash, bolt11: invoice.bolt11 }
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-11-09 17:50:43 +00:00
|
|
|
}
|
2024-01-08 22:37:58 +00:00
|
|
|
|
2024-02-16 18:27:15 +00:00
|
|
|
// The callback subscriptions above will NOT get called for JIT invoices that are already paid.
|
2024-01-08 22:37:58 +00:00
|
|
|
// So we manually cancel the HODL invoice here if it wasn't settled by user action
|
2024-08-13 14:48:30 +00:00
|
|
|
export async function finalizeHodlInvoice ({ data: { hash }, models, lnd, boss, ...args }) {
|
2024-01-08 22:37:58 +00:00
|
|
|
const inv = await getInvoice({ id: hash, lnd })
|
|
|
|
if (inv.is_confirmed) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-13 14:48:30 +00:00
|
|
|
const dbInv = await models.invoice.findUnique({
|
|
|
|
where: { hash },
|
|
|
|
include: {
|
|
|
|
invoiceForward: {
|
|
|
|
include: {
|
|
|
|
withdrawl: true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
if (!dbInv) {
|
|
|
|
console.log('invoice not found in database', hash)
|
|
|
|
return
|
|
|
|
}
|
2024-02-01 16:05:16 +00:00
|
|
|
|
2024-08-13 14:48:30 +00:00
|
|
|
// if this is an actionType we need to cancel conditionally
|
|
|
|
if (dbInv.actionType) {
|
|
|
|
return await paidActionCanceling({ data: { invoiceId: dbInv.id }, models, lnd, boss })
|
|
|
|
}
|
|
|
|
|
|
|
|
await cancelHodlInvoice({ id: hash, lnd })
|
2024-02-01 16:05:16 +00:00
|
|
|
// sync LND invoice status with invoice status in database
|
|
|
|
await checkInvoice({ data: { hash }, models, lnd, ...args })
|
2024-01-08 22:37:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function checkPendingDeposits (args) {
|
|
|
|
const { models } = args
|
|
|
|
const pendingDeposits = await models.invoice.findMany({ where: { confirmedAt: null, cancelled: false } })
|
|
|
|
for (const d of pendingDeposits) {
|
|
|
|
try {
|
2024-08-13 14:48:30 +00:00
|
|
|
await checkInvoice({ data: { hash: d.hash }, ...args })
|
2024-01-08 22:37:58 +00:00
|
|
|
await sleep(10)
|
|
|
|
} catch {
|
|
|
|
console.error('error checking invoice', d.hash)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function checkPendingWithdrawals (args) {
|
|
|
|
const { models } = args
|
|
|
|
const pendingWithdrawals = await models.withdrawl.findMany({ where: { status: null } })
|
|
|
|
for (const w of pendingWithdrawals) {
|
|
|
|
try {
|
2024-08-13 14:48:30 +00:00
|
|
|
await checkWithdrawal({ data: { hash: w.hash }, ...args })
|
2024-01-08 22:37:58 +00:00
|
|
|
await sleep(10)
|
2024-08-13 14:48:30 +00:00
|
|
|
} catch (err) {
|
|
|
|
console.error('error checking withdrawal', w.hash, err)
|
2024-01-08 22:37:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|