better sendPayment()

This commit is contained in:
Daniel Lugo 2020-02-28 16:29:47 -04:00
parent 832957171c
commit da3c4cba24

View file

@ -3,6 +3,9 @@
*/ */
const uuidv1 = require('uuid/v1') const uuidv1 = require('uuid/v1')
const logger = require('winston') const logger = require('winston')
const isFinite = require('lodash/isFinite')
const isNumber = require('lodash/isNumber')
const isNaN = require('lodash/isNaN')
const LightningServices = require('../../../utils/lightningServices') const LightningServices = require('../../../utils/lightningServices')
@ -882,33 +885,52 @@ const sendHRWithInitialMsg = async (
* lightning cannot find a route for the payment. * lightning cannot find a route for the payment.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
const sendPayment = async (to, amount, memo, gun, user, SEA) => { const sendPayment = async (to, amount, memo) => {
if (!user.is) { try {
throw new Error(ErrorCode.NOT_AUTH) const SEA = require('../Mediator').mySEA
} const getUser = () => require('../Mediator').getUser()
const recipientEpub = await Utils.pubToEpub(to) const recipientEpub = await Utils.pubToEpub(to)
const ourSecret = await SEA.secret(recipientEpub, user._.sea) const ourSecret = await SEA.secret(recipientEpub, getUser()._.sea)
if (amount < 1) { if (amount < 1) {
throw new RangeError('Amount must be at least 1 sat.') throw new RangeError('Amount must be at least 1 sat.')
} }
const currOrderAddress = await Getters.currentOrderAddress(to)
logger.info('sendPayment() -> will now create order:')
/** @type {Order} */ /** @type {Order} */
const order = { const order = {
amount: await SEA.encrypt(amount.toString(), ourSecret), amount: amount.toString(),
from: user._.sea.pub, from: getUser()._.sea.pub,
memo: await SEA.encrypt(memo || 'no memo', ourSecret), memo: memo || 'no memo',
timestamp: Date.now() timestamp: Date.now()
} }
const currOrderAddress = await Getters.currentOrderAddress(to) logger.info(JSON.stringify(order))
order.timestamp = Date.now() /* eslint-disable require-atomic-updates */
const [encMemo, encAmount] = await Promise.all([
SEA.encrypt(order.memo, ourSecret),
SEA.encrypt(order.amount, ourSecret)
])
order.memo = encMemo
order.amount = encAmount
order.timestamp = Date.now() // most up to date timestamp
logger.info(`sendPayment() -> encrypted order: ${JSON.stringify(order)}`)
/* eslint-enable require-atomic-updates */
logger.info(
`sendPayment() -> will now place order into address: ${currOrderAddress} for PK: ${to}`
)
/** @type {string} */ /** @type {string} */
const orderID = await new Promise((res, rej) => { const orderID = await new Promise((res, rej) => {
const ord = gun const ord = require('../Mediator')
.getGun()
.get(Key.ORDER_NODES) .get(Key.ORDER_NODES)
.get(currOrderAddress) .get(currOrderAddress)
.set(order, ack => { .set(order, ack => {
@ -924,24 +946,32 @@ const sendPayment = async (to, amount, memo, gun, user, SEA) => {
}) })
}) })
const bob = gun.user(to) if (typeof orderID !== 'string') {
const msg = `orderID returned by gun not an string, got: ${JSON.stringify(
orderID
)}`
throw new Error(msg)
}
/** @type {ReturnType<typeof setTimeout>} */
// eslint-disable-next-line init-declarations
let timeoutID
/** @type {string} */ /** @type {string} */
const invoice = await Promise.race([ const invoice = await Promise.race([
new Promise((res, rej) => { Utils.tryAndWait(
bob gun =>
gun
.user(to)
.get(Key.ORDER_TO_RESPONSE) .get(Key.ORDER_TO_RESPONSE)
.get(orderID) .get(orderID)
.on(data => { .then()
if (typeof data !== 'string') { .then(v => {
rej( clearTimeout(timeoutID)
`Expected order response from pub ${to} to be an string, instead got: ${typeof data}` return v
)
} else {
res(data)
}
})
}), }),
v => typeof v !== 'string'
),
new Promise((_, rej) => { new Promise((_, rej) => {
setTimeout(() => { setTimeout(() => {
rej(new Error(ErrorCode.ORDER_NOT_ANSWERED_IN_TIME)) rej(new Error(ErrorCode.ORDER_NOT_ANSWERED_IN_TIME))
@ -951,6 +981,8 @@ const sendPayment = async (to, amount, memo, gun, user, SEA) => {
const decInvoice = await SEA.decrypt(invoice, ourSecret) const decInvoice = await SEA.decrypt(invoice, ourSecret)
logger.info('decoded invoice: ' + decInvoice)
const { const {
services: { lightning } services: { lightning }
} = LightningServices } = LightningServices
@ -968,6 +1000,8 @@ const sendPayment = async (to, amount, memo, gun, user, SEA) => {
* @prop {any[]|null} payment_route * @prop {any[]|null} payment_route
*/ */
logger.info('Will now send payment through lightning')
await new Promise((resolve, rej) => { await new Promise((resolve, rej) => {
lightning.sendPaymentSync( lightning.sendPaymentSync(
{ {
@ -1000,6 +1034,11 @@ const sendPayment = async (to, amount, memo, gun, user, SEA) => {
} }
) )
}) })
} catch (e) {
logger.error('Error inside sendPayment()')
logger.error(e)
throw e
}
} }
/** /**