aboutsummaryrefslogtreecommitdiffstats
path: root/routes/lightning/receive.js
blob: 980d9e01a9c0ebda0e5fbb3a8875a068ee8b9aac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const asset = "LNBTC";

const handlePayment = async msg => {
  if (!msg.settled) return;

  const invoice = await db.Invoice.findOne({
    where: {
      text: msg.payment_request
    }
  });

  if (!invoice) return;

  const { text: hash, currency, rate, tip, user_id } = invoice;
  const amount = parseInt(msg.value) - tip;

  const account = await db.Account.findOne({
    where: {
      user_id,
      asset: config.liquid.btcasset
    }
  });

  let payment = await db.Payment.create({
    account_id: account.id,
    user_id,
    hash,
    amount,
    currency,
    preimage: msg.r_preimage.toString('hex'),
    rate,
    received: true,
    confirmed: true,
    network: "LNBTC",
    tip
  });

  invoice.received += amount + tip;
  account.balance += amount + tip;

  await account.save();
  await invoice.save();
  await payment.save();
  payments.push(msg.payment_request);

  let user = await getUserById(user_id);

  payment = payment.get({ plain: true });
  payment.account = account.get({ plain: true });
  emit(user.username, "payment", payment);
  emit(user.username, "user", user);

  l.info(
    "lightning payment received",
    user.username,
    payment.amount,
    payment.tip,
  );
};

const invoices = lna.subscribeInvoices({});
invoices.on("data", handlePayment);

const invoicesb = lnb.subscribeInvoices({});
invoicesb.on("data", handlePayment);