stacker.news/pages/api/lnurlp/[username]/pay.js

43 lines
1.4 KiB
JavaScript
Raw Normal View History

2021-10-07 18:37:59 +00:00
import models from '../../../../api/models'
import lnd from '../../../../api/lnd'
import { createInvoice } from 'ln-service'
import { lnurlPayDescriptionHashForUser } from '../../../../lib/lnurl'
2022-01-09 16:50:51 +00:00
import serialize from '../../../../api/resolvers/serial'
2021-10-07 18:37:59 +00:00
export default async ({ query: { username, amount } }, res) => {
const user = await models.user.findUnique({ where: { name: username } })
if (!user) {
return res.status(400).json({ status: 'ERROR', reason: `user @${username} does not exist` })
}
if (!amount || amount < 1000) {
return res.status(400).json({ status: 'ERROR', reason: 'amount must be >=1000 msats' })
}
// generate invoice
const expiresAt = new Date(new Date().setHours(new Date().getHours() + 3))
2021-10-07 20:36:12 +00:00
const description = `${amount} msats for @${user.name} on stacker.news`
const descriptionHash = lnurlPayDescriptionHashForUser(username)
2021-10-07 18:37:59 +00:00
try {
const invoice = await createInvoice({
description,
2021-10-07 20:36:12 +00:00
description_hash: descriptionHash,
2021-10-07 18:37:59 +00:00
lnd,
mtokens: amount,
expires_at: expiresAt
})
2022-01-09 16:50:51 +00:00
await serialize(models,
models.$queryRaw`SELECT * FROM create_invoice(${invoice.id}, ${invoice.request},
2022-01-09 17:22:43 +00:00
${expiresAt}, ${Number(amount)}, ${user.id})`)
2021-10-07 18:37:59 +00:00
return res.status(200).json({
2022-05-19 13:18:28 +00:00
pr: invoice.request,
routes: []
2021-10-07 18:37:59 +00:00
})
} catch (error) {
console.log(error)
res.status(400).json({ status: 'ERROR', reason: 'failed to create invoice' })
}
}