aboutsummaryrefslogtreecommitdiffstats
path: root/sendPayment.js
blob: ff5b9609e59164d56b8d4fe9bac088c54428d1ff (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const bolt11 = require("bolt11");
const config = require("./config");

const l = console.log;

module.exports = (app, db, emit, seen, lna, lnb) => async (req, res) => {
  let hash = req.body.payreq;
  let payreq = bolt11.decode(hash);
  let { user } = req;

  l("sending lightning", user.username, payreq.satoshis);

  if (seen.includes(hash)) {
    return res.status(500).send("Invoice has been paid, can't pay again");
  }

  try {
    await db.transaction(async transaction => {
      let { balance } = await db.User.findOne(
        {
          where: {
            username: user.username
          }
        },
        { transaction }
      );

      if (balance < payreq.satoshis) {
        throw new Error();
      }

      user.balance -= payreq.satoshis;
      await user.save({ transaction });
    });
  } catch (e) {
    return res.status(500).send("Not enough satoshis");
  }

  const stream = lna.sendPayment(lna.meta, {});
  stream.write({ payment_request: req.body.payreq });

  stream.on("data", async m => {
    if (m.payment_error) {
      res.status(500).send(m.payment_error);
    } else {
      if (seen.includes(m.payment_preimage)) return;
      seen.push(m.payment_preimage);

      let total = parseInt(m.payment_route.total_amt);
      let fee = m.payment_route.total_fees;

      user.balance -= total - payreq.satoshis;

      await db.transaction(async transaction => {
        await user.save({ transaction });

        const payment = await db.Payment.create(
          {
            amount: -total,
            fee,
            user_id: user.id,
            hash,
            rate: app.get("rates")[user.currency],
            currency: user.currency,
            confirmed: true,
            asset: 'LNBTC',
          },
          { transaction }
        );

        emit(user.username, "payment", payment);
        emit(user.username, "user", user);

        if (payreq.payeeNodeKey === config.lnb.id) {
          let invoice = await lna.addInvoice({ value: payreq.satoshis });
          let payback = lnb.sendPayment(lnb.meta, {});

          /* eslint-disable-next-line */
          let { payment_request } = invoice;
          /* eslint-disable-next-line */
          payback.write({ payment_request });
        }

        seen.push(hash);
        res.send(payment);
      });
    }
  });

  stream.on("error", e => {
    let msg = e.message;

    res.status(500).send(msg);
  });
};
lass="si">}`, }, user: { username: "horseradish" }, }), }) .then(function (response) { return response.json(); }) .catch(console.log); main.innerHTML = `<a href="lightning:${data.hash}"> <div style="display: flex; margin-top: 50px; margin-bottom: 80px; position: relative;"> <img id="qrcode" src="${base64}" /> <div id="bg"></div> </div> </a> <div style="width: 100%; text-align: center; "> <div style="font-size: 24px; font-weight: bold; margin-bottom: 12px;">${f( (data.amount * data.rate) / 100000000, data.currency )}</div> <div style="color: #666; font-size: 18px;">${sat(data.amount)}</div> </div> <div style="text-align: center; margin: 40px auto; max-width: 460px; word-break: break-all; line-height: 1.5rem">${ data.hash }</div> <div style="margin: 20px 0; display: flex; gap: 1rem; justify-content: center; align-items: center;"> <a href="lightning:${data.hash}" style="text-decoration: none"> <div style="color: #999; font-size: 18px; border-radius: 9999px; padding: 0.5rem 1rem; border: 1px solid #ccc; background: white;">Open</div> </a> <a id="copy" href="#" style="text-decoration: none"> <div style="color: #999; font-size: 18px; border-radius: 9999px; padding: 0.5rem 1rem; border: 1px solid #ccc; background: white;">Copy</div></a> </div> `; let copyButton = document.getElementById("copy"); copyButton.addEventListener("click", (e) => { e.preventDefault(); copy(data.hash); let copied = document.createElement("div"); copied.textContent = "Copied!"; main.appendChild(copied); setTimeout(() => copied.remove(), 3000); }); let qr = document.getElementById("qrcode"); qr.style.margin = "auto"; qr.style.marginTop = "40px"; qr.style.border = "12px white solid"; qr.style.zIndex = 10; new QRCode(qr, data.hash); let bg = document.getElementById("bg"); bg.style.position = "absolute"; bg.style.margin = "auto"; bg.style.left = "0"; bg.style.right = "0"; bg.style.width = "400px"; bg.style.height = "400px"; bg.style.borderRadius = "50%"; bg.style.background = "linear-gradient(to right, #F2F6FC, #E1E3FF)"; bg.style.zIndex = "0"; let ws = new WebSocket("wss://dev.coinos.io/ws"); ws.onmessage = ({ data }) => { try { let { type, data: d } = JSON.parse(data); if (type === "payment") { main.innerHTML = '<img id="check" src="https://dev.coinos.io/icons/check.svg" alt="Check" />' + `<h1>Payment received!</h1> <h2> ${((d.amount * d.rate) / 100000000).toFixed(2)} CAD </h2> <h3> ⚡️${d.amount} </h3>`; var image = document.getElementById("check"); image.addEventListener("load", function () { image.style.transform = "scale(1)"; }); } } catch (e) { console.log(e); } }; ws.onopen = () => { ws.send(JSON.stringify({ type: "subscribe", data })); }; }); </script>