Skip to content

Commit

Permalink
Inject wallet logger interface
Browse files Browse the repository at this point in the history
  • Loading branch information
ekzyis committed Oct 24, 2024
1 parent 7e70938 commit cfacf42
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 39 deletions.
46 changes: 35 additions & 11 deletions api/resolvers/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,18 @@ function injectResolvers (resolvers) {
}
}

// wallet in shape of db row
const wallet = {
field: w.walletField,
type: w.walletType,
userId: me?.id
}
const logger = walletLogger({ wallet, models })

return await upsertWallet({
wallet: { field: w.walletField, type: w.walletType },
testCreateInvoice: (data) => w.testCreateInvoice(data, { me, models })
wallet,
testCreateInvoice: (data) =>
w.testCreateInvoice(data, { logger, me, models })
}, { settings, data, priorityOnly }, { me, models })
}
}
Expand Down Expand Up @@ -618,16 +627,32 @@ const resolvers = {

export default injectResolvers(resolvers)

export const addWalletLog = async ({ wallet, level, message }, { models }) => {
try {
await models.walletLog.create({ data: { userId: wallet.userId, wallet: wallet.type, level, message } })
} catch (err) {
console.error('error creating wallet log:', err)
export const walletLogger = ({ wallet, models }) => {
// server implementation of wallet logger interface on client
const log = (level) => async message => {
try {
await models.walletLog.create({
data: {
userId: wallet.userId,
wallet: wallet.type,
level,
message
}
})
} catch (err) {
console.error('error creating wallet log:', err)
}
}

return {
ok: (...message) => log('SUCCESS')(message.join(' ')),
info: (...message) => log('INFO')(message.join(' ')),
error: (...message) => log('ERROR')(message.join(' '))
}
}

async function upsertWallet (
{ wallet, testCreateInvoice }, { settings, data, priorityOnly }, { me, models }) {
{ wallet, testCreateInvoice }, { settings, data, priorityOnly }, { logger, me, models }) {
if (!me) {
throw new GqlAuthenticationError()
}
Expand All @@ -639,9 +664,8 @@ async function upsertWallet (
} catch (err) {
console.error(err)
const message = 'failed to create test invoice: ' + (err.message || err.toString?.())
wallet = { ...wallet, userId: me.id }
await addWalletLog({ wallet, level: 'ERROR', message }, { models })
await addWalletLog({ wallet, level: 'INFO', message: 'receives disabled' }, { models })
await logger.error(message)
await logger.info('receives disabled')
throw new GqlInputError(message)
}
}
Expand Down
10 changes: 5 additions & 5 deletions wallets/nwc/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export async function nwcCall ({ nwcUrl, method, params }, { logger, timeout } =
const { relayUrl, walletPubkey, secret } = parseNwcUrl(nwcUrl)

const relay = await Relay.connect(relayUrl, { timeout })
logger?.ok(`connected to ${relayUrl}`)
await logger?.ok(`connected to ${relayUrl}`)

try {
const payload = { method, params }
Expand All @@ -63,17 +63,17 @@ export async function nwcCall ({ nwcUrl, method, params }, { logger, timeout } =

await relay.publish(request, { timeout })

logger?.info(`published ${method} request`)
await logger?.info(`published ${method} request`)

logger?.info('waiting for response ...')
await logger?.info('waiting for response ...')

const [response] = await subscription

if (!response) {
throw new Error('no response')
}

logger?.ok('response received')
await logger?.ok('response received')

if (!verifyEvent(response)) throw new Error('invalid response: failed to verify')

Expand All @@ -86,7 +86,7 @@ export async function nwcCall ({ nwcUrl, method, params }, { logger, timeout } =
throw new Error('invalid response: missing error or result')
} finally {
relay?.close()
logger?.info(`closed connection to ${relayUrl}`)
await logger?.info(`closed connection to ${relayUrl}`)
}
}

Expand Down
12 changes: 7 additions & 5 deletions wallets/nwc/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { withTimeout } from '@/lib/time'
import { nwcCall, supportedMethods } from 'wallets/nwc'
export * from 'wallets/nwc'

export async function testCreateInvoice ({ nwcUrlRecv }) {
export async function testCreateInvoice ({ nwcUrlRecv }, { logger }) {
const timeout = 15_000

const supported = await supportedMethods(nwcUrlRecv, { timeout })
const supported = await supportedMethods(nwcUrlRecv, { logger, timeout })

const supports = (method) => supported.includes(method)

Expand All @@ -20,12 +20,14 @@ export async function testCreateInvoice ({ nwcUrlRecv }) {
}
}

return await withTimeout(createInvoice({ msats: 1000, expiry: 1 }, { nwcUrlRecv }), timeout)
return await withTimeout(
createInvoice({ msats: 1000, expiry: 1 }, { logger, nwcUrlRecv }),
timeout)
}

export async function createInvoice (
{ msats, description, expiry },
{ nwcUrlRecv }) {
{ logger, nwcUrlRecv }) {
const result = await nwcCall({
nwcUrl: nwcUrlRecv,
method: 'make_invoice',
Expand All @@ -34,6 +36,6 @@ export async function createInvoice (
description,
expiry
}
})
}, { logger })
return result.invoice
}
18 changes: 7 additions & 11 deletions wallets/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import * as lnAddr from 'wallets/lightning-address/server'
import * as lnbits from 'wallets/lnbits/server'
import * as nwc from 'wallets/nwc/server'
import * as phoenixd from 'wallets/phoenixd/server'
import { addWalletLog } from '@/api/resolvers/wallet'
import walletDefs from 'wallets/server'
import { parsePaymentRequest } from 'ln-service'
import { toPositiveNumber } from '@/lib/validate'
import { PAID_ACTION_TERMINAL_STATES } from '@/lib/constants'
import { withTimeout } from '@/lib/time'
import { walletLogger } from '@/api/resolvers/wallet'
export default [lnd, cln, lnAddr, lnbits, nwc, phoenixd]

const MAX_PENDING_INVOICES_PER_WALLET = 25
Expand All @@ -31,6 +31,8 @@ export async function createInvoice (userId, { msats, description, descriptionHa
msats = toPositiveNumber(msats)

for (const wallet of wallets) {
const logger = walletLogger({ wallet, models })

const w = walletDefs.find(w => w.walletType === wallet.type)
try {
const { walletType, walletField, createInvoice } = w
Expand Down Expand Up @@ -94,21 +96,15 @@ export async function createInvoice (userId, { msats, description, descriptionHa
throw new Error(`invoice has a different satoshi amount ${bolt11.mtokens} !== ${msats}`)
}

await addWalletLog({
wallet,
level: 'INFO',
message: `wallet does not support msats so we floored ${msats} msats to nearest sat ${BigInt(bolt11.mtokens)} msats`
}, { models })
await logger.info(
`wallet does not support msats so we floored ${msats} msats to nearest sat ${BigInt(bolt11.mtokens)} msats`
)
}

return { invoice, wallet }
} catch (error) {
console.error(error)
await addWalletLog({
wallet,
level: 'ERROR',
message: `creating invoice for ${description ?? ''} failed: ` + error
}, { models })
await logger.error(`creating invoice for ${description ?? ''} failed: ` + error)
}
}

Expand Down
12 changes: 5 additions & 7 deletions worker/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { notifyDeposit, notifyWithdrawal } from '@/lib/webPush'
import { INVOICE_RETENTION_DAYS, LND_PATHFINDING_TIMEOUT_MS } from '@/lib/constants'
import { datePivot, sleep } from '@/lib/time.js'
import retry from 'async-retry'
import { addWalletLog } from '@/api/resolvers/wallet'
import { msatsToSats, numWithUnits } from '@/lib/format'
import {
paidActionPaid, paidActionForwarded,
Expand All @@ -16,6 +15,7 @@ import {
paidActionCanceling
} from './paidAction.js'
import { getPaymentFailureStatus } from '@/api/lnd/index.js'
import { walletLogger } from '@/api/resolvers/wallet.js'

export async function subscribeToWallet (args) {
await subscribeToDeposits(args)
Expand Down Expand Up @@ -287,6 +287,8 @@ export async function checkWithdrawal ({ data: { hash, withdrawal, invoice }, bo
}
}

const logger = walletLogger({ models, wallet: dbWdrwl.wallet })

if (wdrwl?.is_confirmed) {
if (dbWdrwl.invoiceForward.length > 0) {
return await paidActionForwarded({ data: { invoiceId: dbWdrwl.invoiceForward[0].invoice.id, withdrawal: wdrwl, invoice }, models, lnd, boss })
Expand All @@ -310,7 +312,7 @@ export async function checkWithdrawal ({ data: { hash, withdrawal, invoice }, bo
const message = `autowithdrawal of ${
numWithUnits(msatsToSats(paid), { abbreviate: false })} with ${
numWithUnits(msatsToSats(fee), { abbreviate: false })} as fee`
await addWalletLog({ wallet: dbWdrwl.wallet, level: 'SUCCESS', message }, { models })
await logger.ok(message)
}
}
} else if (wdrwl?.is_failed || notSent) {
Expand All @@ -328,11 +330,7 @@ export async function checkWithdrawal ({ data: { hash, withdrawal, invoice }, bo

if (code === 0 && dbWdrwl.wallet) {
// add error into log for autowithdrawal
await addWalletLog({
wallet: dbWdrwl.wallet,
level: 'ERROR',
message: 'autowithdrawal failed: ' + message
}, { models })
await logger.error('autowithdrawal failed: ' + message)
}
}
}
Expand Down

0 comments on commit cfacf42

Please sign in to comment.