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 logger = require('winston')
const isFinite = require('lodash/isFinite')
const isNumber = require('lodash/isNumber')
const isNaN = require('lodash/isNaN')
const LightningServices = require('../../../utils/lightningServices')
@ -882,33 +885,52 @@ const sendHRWithInitialMsg = async (
* lightning cannot find a route for the payment.
* @returns {Promise<void>}
*/
const sendPayment = async (to, amount, memo, gun, user, SEA) => {
if (!user.is) {
throw new Error(ErrorCode.NOT_AUTH)
}
const sendPayment = async (to, amount, memo) => {
try {
const SEA = require('../Mediator').mySEA
const getUser = () => require('../Mediator').getUser()
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) {
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} */
const order = {
amount: await SEA.encrypt(amount.toString(), ourSecret),
from: user._.sea.pub,
memo: await SEA.encrypt(memo || 'no memo', ourSecret),
amount: amount.toString(),
from: getUser()._.sea.pub,
memo: memo || 'no memo',
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} */
const orderID = await new Promise((res, rej) => {
const ord = gun
const ord = require('../Mediator')
.getGun()
.get(Key.ORDER_NODES)
.get(currOrderAddress)
.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} */
const invoice = await Promise.race([
new Promise((res, rej) => {
bob
Utils.tryAndWait(
gun =>
gun
.user(to)
.get(Key.ORDER_TO_RESPONSE)
.get(orderID)
.on(data => {
if (typeof data !== 'string') {
rej(
`Expected order response from pub ${to} to be an string, instead got: ${typeof data}`
)
} else {
res(data)
}
})
.then()
.then(v => {
clearTimeout(timeoutID)
return v
}),
v => typeof v !== 'string'
),
new Promise((_, rej) => {
setTimeout(() => {
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)
logger.info('decoded invoice: ' + decInvoice)
const {
services: { lightning }
} = LightningServices
@ -968,6 +1000,8 @@ const sendPayment = async (to, amount, memo, gun, user, SEA) => {
* @prop {any[]|null} payment_route
*/
logger.info('Will now send payment through lightning')
await new Promise((resolve, rej) => {
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
}
}
/**