aboutsummaryrefslogtreecommitdiffstats
path: root/routes/bitcoin/fee.js
blob: 74c26a92cd21ccceba2d12fdc59b392d1ef6f87e (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
import config from "$config";
import db from "$db";
import bc from "$lib/bitcoin";
import { err } from "$lib/logging";
import { emit } from "$lib/sockets";
import buildTx from "$lib/buildtx";
import { SATS } from "$lib/utils";

export default async (req, res) => {
  let { user } = req;
  let { address, amount, feeRate, replaceable = true } = req.body;
  let tx, fee;

  if (user.account.pubkey) {
    try {
      let psbt = await buildTx({ address, amount, feeRate, replaceable, user });
      return res.send(psbt);
    } catch (e) {
      return res.code(500).send(e.message);
    }
  }

  let invoice = await db.Invoice.findOne({
    where: { address },
    include: {
      attributes: ["username"],
      model: db.User,
      as: "user"
    }
  });

  if (invoice) {
    let { ismine } = await bc.getAddressInfo(address);
    if (ismine) {
      emit(user.username, "to", invoice.user);
      return res.send({});
    }
  }

  try {
    amount = parseInt(amount);

    let partial = await bc.createRawTransaction(
      [],
      {
        [address]: (amount / SATS).toFixed(8)
      },
      0,
      replaceable
    );

    let params = {
      subtractFeeFromOutputs: amount === user.balance ? [0] : [],
      replaceable
    };

    if (feeRate) params.feeRate = (feeRate / SATS).toFixed(8);

    tx = await bc.fundRawTransaction(partial, params);

    if (config.bitcoin.walletpass)
      await bc.walletPassphrase(config.bitcoin.walletpass, 300);

    let signed = await bc.signRawTransactionWithWallet(tx.hex);
    let decoded = await bc.decodeRawTransaction(signed.hex);
    feeRate = Math.round((tx.fee * SATS * 1000) / decoded.vsize);

    res.send({ feeRate, tx });
  } catch (e) {
    err("bitcoin fee estimation error", e);
    return res.code(500).send(e.message);
  }
};