aboutsummaryrefslogtreecommitdiffstats
path: root/routes/ecash.js
blob: 1b8bcae1e9de2bede6ce305b3270afebd5a3e845 (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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import { g, s, db } from "$lib/db";
import { claim, mint } from "$lib/ecash";
import { bail } from "$lib/utils";
import { debit, credit, types } from "$lib/payments";
import { v4 } from "uuid";
import { l, err, warn } from "$lib/logging";
import { emit } from "$lib/sockets";
import store from "$lib/store";

let { ecash: type } = types;

export default {
  async get({ params: { id } }, res) {
    try {
      res.send(await g(`cash:${id}`));
    } catch (e) {
      bail(res, e.message);
    }
  },

  async claim({ body: { token }, user }, res) {
    try {
      let amount = await claim(token);

      let memo;
      let hash = v4();
      let { currency, id: uid } = user;
      await s(`invoice:${hash}`, {
        currency,
        id: hash,
        hash,
        rate: store.rates[currency],
        uid,
        received: 0,
      });

      await credit(hash, amount, memo, user.id, type);

      res.send({ ok: true });
    } catch (e) {
      console.log(e);
      bail(res, e.message);
    }
  },

  async mint({ body: { amount }, user }, res) {
    try {
      let id = v4();
      let hash = v4();

      let p = await debit({ hash, amount, user, type });
      let token = await mint(amount);
      p.memo = token;
      await s(`payment:${p.id}`, p);
      s(`cash:${id}`, token);

      res.send({ id });
    } catch (e) {
      bail(res, e.message);
    }
  },

  async melt({ body: { amount, bolt11: hash, preimage }, user }, res) {
    try {
      amount = Math.round(amount / 1000);
      let ref = preimage;
      let { lightning: type } = types;
      if (user.username !== "mint") fail("unauthorized");
      let { id: uid, currency, username } = user;
      let ourfee = await db.debit(
        `balance:${uid}`,
        `credit:${type}:${uid}`,
        amount || 0,
        0,
        0,
        0,
      );

      let rate = store.rates[currency];

      if (ourfee.err) fail(ourfee.err);

      let id = v4();
      let p = {
        id,
        amount: -amount,
        hash,
        ourfee,
        uid,
        confirmed: true,
        rate,
        currency,
        type,
        ref,
        created: Date.now(),
      };

      await s(`payment:${hash}`, id);
      await s(`payment:${id}`, p);
      await db.lPush(`${uid}:payments`, id);

      l(user.username, "sent", type, amount);
      emit(user.id, "payment", p);

      res.send(p);
    } catch (e) {
      bail(res, e.message);
    }
  },
};