stacker.news/api/resolvers/wallet.js

84 lines
2.6 KiB
JavaScript
Raw Normal View History

2021-05-13 01:51:37 +00:00
import { createInvoice, decodePaymentRequest, subscribeToPayViaRequest } from 'ln-service'
2021-05-11 15:52:50 +00:00
import { UserInputError, AuthenticationError } from 'apollo-server-micro'
2021-04-30 21:42:51 +00:00
export default {
Query: {
2021-05-06 21:15:22 +00:00
invoice: async (parent, { id }, { me, models, lnd }) => {
2021-05-11 15:52:50 +00:00
return await models.invoice.findUnique({ where: { id: Number(id) } })
2021-05-13 01:51:37 +00:00
},
withdrawl: async (parent, { id }, { me, models, lnd }) => {
console.log(models)
return await models.withdrawl.findUnique({ where: { id: Number(id) } })
2021-04-30 21:42:51 +00:00
}
},
Mutation: {
2021-05-06 21:15:22 +00:00
createInvoice: async (parent, { amount }, { me, models, lnd }) => {
2021-05-11 15:52:50 +00:00
if (!me) {
throw new AuthenticationError('You must be logged in')
}
if (!amount || amount <= 0) {
throw new UserInputError('Amount must be positive', { argumentName: 'amount' })
}
// set expires at to 3 hours into future
const expiresAt = new Date(new Date().setHours(new Date().getHours() + 3))
const description = `${amount} sats for @${me.name} on stacker.news`
2021-05-13 01:51:37 +00:00
const invoice = await createInvoice({
description,
lnd,
tokens: amount,
expires_at: expiresAt
})
2021-05-11 15:52:50 +00:00
const data = {
hash: invoice.id,
bolt11: invoice.request,
expiresAt: expiresAt,
msatsRequested: amount * 1000,
user: {
connect: {
name: me.name
}
}
}
return await models.invoice.create({ data })
2021-05-12 23:04:19 +00:00
},
createWithdrawl: async (parent, { invoice, maxFee }, { me, models, lnd }) => {
if (!me) {
throw new AuthenticationError('You must be logged in')
}
// decode invoice to get amount
const decoded = await decodePaymentRequest({ lnd, request: invoice })
// create withdrawl transactionally (id, bolt11, amount, fee)
2021-05-13 01:51:37 +00:00
const [withdrawl] =
await models.$queryRaw`SELECT * FROM create_withdrawl(${decoded.id}, ${invoice},
${Number(decoded.mtokens)}, ${Number(maxFee)}, ${me.name})`
2021-05-12 23:04:19 +00:00
// create the payment, subscribing to its status
2021-05-13 01:51:37 +00:00
const sub = subscribeToPayViaRequest({
lnd,
request: invoice,
max_fee_mtokens: maxFee,
pathfinding_timeout: 30000
})
2021-05-12 23:04:19 +00:00
// if it's confirmed, update confirmed
2021-05-13 01:51:37 +00:00
sub.on('confirmed', console.log)
2021-05-12 23:04:19 +00:00
// if the payment fails, we need to
// 1. transactionally return the funds to the user
// 2. transactionally update the widthdrawl as failed
2021-05-13 01:51:37 +00:00
sub.on('failed', console.log)
2021-05-12 23:04:19 +00:00
// in walletd
// for each payment that hasn't failed or succeede
2021-05-13 01:51:37 +00:00
return withdrawl
2021-04-30 21:42:51 +00:00
}
}
}