aboutsummaryrefslogtreecommitdiffstats
path: root/lib/utils.js
blob: c68d222b51127d5407e0e80b91ffe37e3d064238 (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
import migrate from "$lib/migrate";
import store from "$lib/store";
import { g } from "$lib/db";
import config from "$config";

export let fail = (msg) => {
  throw new Error(msg);
};

export let nada = () => {};

export let sleep = (n) => new Promise((r) => setTimeout(r, n));
export let wait = async (f, s = 300, n = 50) => {
  let i = 0;
  while (!(await f()) && i < s) (await sleep(n)) && i++;
  if (i >= s) fail("timeout");
  return f();
};

export let prod = process.env.NODE_ENV === "production";

export let bail = (res, msg) => res.code(500).send(msg);

export let SATS = 100000000;
export let sats = (n) => Math.round(n * SATS);
export let btc = (n) => parseFloat((n / SATS).toFixed(8));

export let uniq = (a, k) => [...new Map(a.map((x) => [k(x), x])).values()];
export let pick = (O, K) =>
  K.reduce((o, k) => (typeof O[k] !== "undefined" && (o[k] = O[k]), o), {});

export let bip21 = (address, { amount, memo, tip, type }) => {
  if (!(amount || memo)) return address;

  let network = { liquid: "liquidnetwork", bitcoin: "bitcoin" }[type];
  let url = new URLSearchParams();

  if (amount) {
    url.append("amount", btc(amount));
    if (type === "liquid") url.append("assetid", config.liquid.btc);
  }

  if (memo) url.append("memo", memo);

  return `${network}:${address}?${url.toString()}`;
};

export let fields = [
  "cipher",
  "pubkey",
  "password",
  "username",
  "salt",
  "currency",
  "currencies",
  "fiat",
  "otpsecret",
  "balance",
  "ip",
  "pin",
  "display",
  "haspin",
  "profile",
  "prompt",
  "banner",
];

export let getUser = async (username) => {
  if (username === "undefined") fail("invalid user");
  return migrate(username);
};

export let getInvoice = async (hash) => {
  let iid = await g(`invoice:${hash}`);
  if (iid && iid.id) iid = iid.id;
  else if (iid && iid.hash) iid = iid.hash;
  return await g(`invoice:${iid}`);
}