// Merge prepared events without inserting between visible posts or evicting // the reading position. Row geometry comes from the currently rendered feed. export function mergeFeedWindow(notes, shown, additions, { rows = [], height = 0, keep = 200, page = 20, holdHead = false } = {}) { const byId = new Map(rows.map((r) => [r.id, r])); const first = rows.find((r) => r.bottom > 0 && r.top < height); const seen = new Set(notes.map((e) => e.id)); const added = [], deferred = []; for (const e of additions) { if (seen.has(e.id)) continue; seen.add(e.id); // Equal timestamps sort after existing events. Ignore hidden rows when // locating the next rendered post: they cannot serve as an anchor. const next = notes.find((n) => n.created_at < e.created_at && byId.has(n.id)); const row = next && byId.get(next.id); // Above the first post on screen is fine even with the header showing: // that post is held where it is and the header goes up with the rest, // so the scrollbar shows there's more above without anything you're // reading moving. holdHead (someone is writing up there) keeps the old // rule, so the composer isn't scrolled out from under a typing thumb. const inView = row && row.top < height && (row === first ? holdHead && row.top > 0 : row.top >= 0); (inView ? deferred : added).push(e); } if (!added.length) return { notes, shown, added, deferred }; const held = new Set([...notes.slice(0, shown).map((e) => e.id), ...byId.keys()]); const merged = [...notes, ...added].sort((a, b) => b.created_at - a.created_at); for (let i = 0; i < merged.length; i++) if (held.has(merged[i].id)) shown = Math.max(shown, i + 1); // Keep another page beyond the displayed window so paging still advances // after the reader has reached the normal in-memory cache limit. return { notes: merged.slice(0, Math.max(keep, shown + page)), shown, added, deferred }; } value='setup-updates'>setup-updates coinos server — legacy coinos.io backend (Lightning, on-chain, Liquid)coinos
aboutsummaryrefslogtreecommitdiffstats
path: root/lib/buildtx.js
blob: 5e0fe29f7787c0a31985c80bfa3ea0603b3b5803 (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
const axios = require("axios");
const bitcoin = require("bitcoinjs-lib");
const coinselect = require("coinselect");
const split = require("coinselect/split");
const api = prod ? "https://blockstream.info/api" : "http://localhost:3095";
const SATS = 100000000;
const network = prod
  ? bitcoin.networks["bitcoin"]
  : bitcoin.networks["regtest"];

module.exports = async ({ address, amount, feeRate, replaceable, user }) => {
  if (!feeRate) feeRate = (await bc.estimateSmartFee(6)).feerate * SATS;
  feeRate = Math.round(feeRate / 1000);

  const payments = await db.Payment.findAll({
    where: {
      received: true,
      account_id: user.account_id,
      network: 'bitcoin',
    } 
  });


  const addresses = [...new Set(payments.map(p => p.address))];
  const utxos = [];
  for (let i = 0; i < addresses.length; i++) {
    try {
      utxos.push(...(await axios.get(`${api}/address/${addresses[i]}/utxo`)).data);
    } catch (e) {
      l.error("problem fetching utxos", e.message);
    }
  } 

  let targets = [
    {
      address,
      value: amount
    }
  ];

  let { inputs, outputs, fee } = coinselect(utxos, targets, feeRate);

  if (!inputs || !outputs) {
    l.info("utxos", amount, feeRate, utxos.map(u => u.value));
    throw new Error("Couldn't find inputs for transaction, check your balance/fee");
  } 

  let psbt = new bitcoin.Psbt({ network });
  let total = 0;

  outputs.map(({ address, value }) => {
    total += value;
    if (!address) {
      address =  payments[payments.length - 1].address;
      change.push(address);
    } 

    psbt = psbt.addOutput({
      address,
      value
    });
  });

  for (let i = 0; i < inputs.length; i++) {
    let { txid, vout } = inputs[i];
    let nonWitnessUtxo = Buffer.from(await bc.getRawTransaction(txid), "hex");
    psbt = psbt.addInput({
      hash: txid,
      index: vout,
      nonWitnessUtxo
    });
  }

  if (replaceable) psbt.setInputSequence(0, 0xffffffff - 2);

  feeRate = Math.round(feeRate * 1000);
  psbt = psbt.toBase64();

  return { tx: psbt, feeRate };
};