aboutsummaryrefslogtreecommitdiffstats
path: root/routes/liquid/fee.js
blob: 253810a9ff89df4c52c72edc3619d155219ab101 (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
const buildTx = require("../../lib/buildliquidtx");

liquidTx = async ({ address, asset, amount, feeRate, replaceable, user }) => {
  let tx, fee;
  let node = lq;

  if (user.account.pubkey) {
    let psbt = await buildTx({
      address,
      asset,
      amount,
      feeRate,
      replaceable,
      user
    });
    return psbt;
  }

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

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

  if (config.liquid.walletpass)
    await node.walletPassphrase(config.liquid.walletpass, 300);

  amount = parseInt(amount);

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

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

  let info = await node.getAddressInfo(address);

  tx = await node.createRawTransaction(
    [],
    [{
      [address]: (amount / SATS).toFixed(8),
      asset
    }],
    0,
    replaceable,
  );

  l.info("funding tx for fee estimate", tx);

  tx = await node.fundRawTransaction(tx, params);

  let blinded = await node.blindRawTransaction(tx.hex);
  let signed = await node.signRawTransactionWithWallet(blinded);

  decoded = await node.decodeRawTransaction(signed.hex);
  feeRate = Math.round((tx.fee * SATS * 1000) / decoded.vsize);
  l.info("estimated", asset, feeRate);

  return { feeRate, tx };
};

module.exports = ah(async (req, res) => {
  try {
    let tx = await liquidTx({ ...req.body, user: req.user })
    res.send(tx);
  } catch (e) {
    l.error("error estimating liquid fee", e.message, e.stack);
    return res.status(500).send(e.message);
  }
});