aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/SetMemo.svelte
diff options
context:
space:
mode:
Diffstat (limited to 'src/components/SetMemo.svelte')
0 files changed, 0 insertions, 0 deletions
b/payments.js?h=prod&id=d18b06483a4b62b2d871d8c3cbbc5be4dec042fc'>d18b0648 ^
f2b4dfaa ^
191ce135 ^
60a79d20 ^
191ce135 ^

3d38a365 ^
bad17599 ^
8c5835fc ^
5264f702 ^




f0c9dd97 ^
63fe7c28 ^
5264f702 ^


5dd47b9b ^
5264f702 ^
2edcafb3 ^
5264f702 ^
5dd47b9b ^
5264f702 ^


5955ff69 ^
7fec7cc3 ^



db38e8f3 ^
72280846 ^


797d10c9 ^

50d35a64 ^



ab49b84a ^
50d35a64 ^
ab49b84a ^


797d10c9 ^
5dd47b9b ^
5955ff69 ^
5264f702 ^


1ae65a5a ^
17a2a698 ^

1ae65a5a ^
545820ba ^








545820ba ^
5264f702 ^
5264f702 ^


2edcafb3 ^
e9a82567 ^
f0543b6d ^
5264f702 ^
db38e8f3 ^
5264f702 ^
2edcafb3 ^
7fec7cc3 ^
5264f702 ^

5dd47b9b ^
797d10c9 ^
63fe7c28 ^
5264f702 ^

5dd47b9b ^

5264f702 ^
5dd47b9b ^
5264f702 ^




5dd47b9b ^
a650cf9a ^
5d42bd23 ^
db38e8f3 ^
72280846 ^


a7322928 ^



5d42bd23 ^
7709c1ef ^
a650cf9a ^

17a2a698 ^
60a79d20 ^
a650cf9a ^
5264f702 ^




7fec7cc3 ^
0aea6033 ^








7fec7cc3 ^
13f3c21b ^
5264f702 ^
13f3c21b ^
5264f702 ^
a650cf9a ^
5264f702 ^
7fec7cc3 ^
5264f702 ^

5dd47b9b ^
5d42bd23 ^
5264f702 ^

63fe7c28 ^
5264f702 ^

a650cf9a ^

5264f702 ^


5dd47b9b ^
5264f702 ^

13f3c21b ^
5264f702 ^
13f3c21b ^
bad17599 ^
5264f702 ^
f0543b6d ^




db38e8f3 ^
5264f702 ^




a650cf9a ^
5264f702 ^


b72619d3 ^
17cf1c5d ^
f2878d2e ^






63fe7c28 ^
17cf1c5d ^
19b906ec ^

3d38a365 ^





3537906a ^


92394751 ^
5264f702 ^





13f3c21b ^
75ae7195 ^
07cf00a0 ^
75ae7195 ^
5264f702 ^
7fec7cc3 ^
bdd9a349 ^
13f3c21b ^
5264f702 ^
13f3c21b ^
5264f702 ^
13f3c21b ^
5264f702 ^



bad17599 ^




63fe7c28 ^



bad17599 ^
bad17599 ^




74d0ea35 ^


bad17599 ^










7709c1ef ^
bad17599 ^

7709c1ef ^
bad17599 ^









7709c1ef ^
bad17599 ^
bad17599 ^























63fe7c28 ^
bad17599 ^




63fe7c28 ^
bad17599 ^






63fe7c28 ^
bad17599 ^

















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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330





                                            
                                            
                                              
                                            

                                              
                                      
                                   
                    

                                  
                                         
                         
                                            




                         
               
                     


                          
       
         
          
       
       


                        
          



                                             
                                       


                                          

                      



                                                                             
                                                                            
                            


                                                               
   
 
                                           


                                                                      
                                                              

                                     
 








                            
                                             
 


                    
        
         
           
         
        
        
                    
         

             
        
        
                        

    

                                        
 
                                         




                              
                                                                               
                                 
 
                                       


                                          



                                   
 
                        

                           
                                  
                                                    
                                             




                                             
                                   








                                                                           
 
                
           
       
         
                                   
        
         

             
        
        

                    
                        

    

                                                        


                               
                                                

                        
                                           
          
                                   
   
 




                                                                       
                                                  




                                              
                                             


                                          
 
                                     






                                                                            
                                                 
       

   





                                                             


                                                             
 





                                                     
                                                         
                                       
                          
 
                     
                            
 
                        
 
                  
            
                                              



                                         




                                                                         



                                                                             
 




                                                              


                                                                










                                                             
                                                  

                                            
                                                 









                                                                        
                                                                   
 























                                                                         
                                                                              




                                                             
                     






                                                           
                        

















                                                                      
import config from "$config";
import store from "$lib/store";
import { emit } from "$lib/sockets";
import { v4 } from "uuid";
import { notify } from "$lib/notifications";
import { db, g, s, t } from "$lib/db";
import { l, err, warn } from "$lib/logging";
import { fail, wait, SATS } from "$lib/utils";
import { callWebhook } from "$lib/webhooks";
import dollarsToWords from "dollars-to-words";
import got from "got";
import { spawn } from "child_process";
import ffmpeg from "fluent-ffmpeg";
import fs from "fs";
import EventEmitter from "events";
import crc32 from "buffer-crc32";
import { mqtt1, mqtt2 } from "$lib/mqtt";
import ln from "$lib/ln";
import { mail, templates } from "$lib/mail";

export const types = {
  internal: "internal",
  bitcoin: "bitcoin",
  lightning: "lightning",
  fund: "fund",
  classic: "classic",
};

export let debit = async (
  hash,
  amount,
  fee = 0,
  memo,
  user,
  type = types.internal,
  id = v4()
) => {
  let ref;
  let { id: uid, currency, username } = user;

  let rate = store.rates[currency];

  let iid = await g(`invoice:${hash}`);
  if (iid && iid.hash) iid = iid.hash;
  let invoice = await g(`invoice:${iid}`);

  if (invoice) {
    ref = invoice.uid;

    let equivalentRate =
      invoice.rate * (store.rates[currency] / store.rates[invoice.currency]);

    if (Math.abs(invoice.rate / store.rates[invoice.currency] - 1) < 0.01) {
      rate = equivalentRate;
    } else {
      warn("rate slipped", hash, invoice.rate, equivalentRate);
    }
  }

  let tip = parseInt(invoice?.tip) || null;

  if (!amount || amount < 0) fail("Amount must be greater than zero");

  let ourfee = [types.bitcoin, types.lightning].includes(type)
    ? Math.round(amount * config.fee)
    : 0;

  let r = await db.debit(
    `balance:${uid}`,
    `credit:${type}:${uid}`,
    amount || 0,
    tip || 0,
    fee || 0,
    ourfee || 0
  );

  if (r !== "ok") fail("Insufficient funds");

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

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

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

  return p;
};

export let credit = async (hash, amount, memo, ref, type = types.internal) => {
  amount = parseInt(amount) || 0;

  let iid = await g(`invoice:${hash}`);
  if (iid && iid.hash) iid = iid.hash;
  let invoice = await g(`invoice:${iid}`);

  if (!invoice) {
    await db.sAdd("missing", hash);
    return;
  }

  let { tip } = invoice;
  tip = parseInt(tip) || 0;

  if (!memo) ({ memo } = invoice);
  if (amount < 0 || tip < 0) fail("Invalid amount");
  if (type === types.internal) amount += tip;

  let user = await g(`user:${invoice.uid}`);

  let { id: uid, currency, username } = user;

  let rate = store.rates[currency];

  let equivalentRate =
    invoice.rate * (store.rates[currency] / store.rates[invoice.currency]);

  if (Math.abs(invoice.rate / store.rates[invoice.currency] - 1) < 0.01) {
    rate = equivalentRate;
  } else {
    warn("rate slipped", hash, invoice.rate, equivalentRate);
  }

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

  if (type === types.bitcoin) invoice.pending += amount;
  else invoice.received += amount;

  let balance = "balance";
  if (type === types.bitcoin) {
    let [txid, vout] = ref.split(":").slice(-2);
    p.confirmed = false;
    balance = "pending";
    await s(`payment:${txid}:${vout}`, id);
  } else {
    await s(`payment:${hash}`, id);
  }

  let m = await db.multi();

  if ([types.bitcoin, types.lightning].includes(type))
    m.incrBy(`credit:${type}:${uid}`, Math.round(amount * config.fee));

  m.set(`invoice:${iid}`, JSON.stringify(invoice))
    .set(`payment:${p.id}`, JSON.stringify(p))
    .lPush(`${uid}:payments`, p.id)
    .incrBy(`${balance}:${uid}`, amount)
    .exec();

  l("received", type, username, amount, tip);
  emit(uid, "payment", p);
  notify(user, `Received ${amount} sats`);
  callWebhook(invoice, p);

  if (user.verified && user.notify) {
    mail(user, "Payment received", templates.paymentReceived, {
      username,
      sats:
        "⚡️" +
        new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }).format(
          p.amount
        ),
      link: `${process.env.URL}/payment/${p.id}`,
    });
  }

  mqtt1.publish(
    username,
    `pay:${p.amount}:${p.tip}:${p.rate}:${p.created}:${p.id}`
  );

  mqtt2.publish(
    username,
    `pay:${p.amount}:${p.tip}:${p.rate}:${p.created}:${p.id}`
  );

  return p;
};

export let confirm = async (address, txid, vout) => {
  let id = `payment:${txid}:${vout}`;
  let p = await g(id);
  if (typeof p === "string") p = await g(`payment:${p}`);
  if (!p) return db.sAdd("missed", id);
  if (p.confirmed) return;

  p.confirmed = true;
  emit(p.uid, "payment", p);

  l("confirming", txid);

  let r = await db
    .multi()
    .set(`payment:${p.id}`, JSON.stringify(p))
    .decrBy(`pending:${p.uid}`, p.amount)
    .incrBy(`balance:${p.uid}`, p.amount)
    .exec();
};

export let payLightning = async (user, payreq, amount, maxfee, memo) => {
  let p;
  let hash = payreq;

  if (typeof amount !== "undefined") {
    amount = parseInt(amount);
    if (amount < 0 || amount > SATS || isNaN(amount)) fail("Invalid amount");
  }


  let total = amount;
  let { amount_msat, payment_hash } = await ln.decode(payreq);
  if (amount_msat) total = Math.round(amount_msat / 1000);

  maxfee = maxfee ? parseInt(maxfee) : Math.round(total * 0.05);
  if (maxfee < 0) fail("Max fee cannot be negative");

  let iid = await g(`invoice:${hash}`);
  if (iid && iid.hash) iid = iid.hash;
  let invoice = await g(`invoice:${iid}`);

  if (invoice) {
    if (invoice.uid === user.id) fail("Cannot send to self");
    hash = payreq;
  } else {
    let r;

    let { pays } = await ln.listpays(payreq);
    if (pays.find((p) => p.status === "complete"))
      fail("Invoice has already been paid");

    if (pays.find((p) => p.status === "pending"))
      fail("Payment is already underway");

    p = await debit(payreq, total, maxfee, memo, user, types.lightning);

    let check = async () => {
      try {
        let { pays } = await ln.listpays(payreq);

        let recordExists = !!(await g(`payment:${p.id}`));
        let paymentFailed =
          !pays.length || pays.every((p) => p.status === "failed");

        if (recordExists && paymentFailed) {
          await db.del(`payment:${p.id}`);

          let credit = Math.round(total * config.fee) - p.ourfee;
          warn("crediting balance", total + maxfee + p.ourfee);
          await db.incrBy(`balance:${p.uid}`, total + maxfee + p.ourfee);

          warn("crediting credits", credit);
          await db.incrBy(`credit:${types.lightning}:${p.uid}`, credit);

          warn("reversing payment", p.id);
          await db.lRem(`${p.uid}:payments`, 1, p.id);

          clearInterval(interval);
        }
      } catch (e) {
        console.log(e);
        err("Failed to reverse payment", r);
      }
    };

    let interval = setInterval(check, 5000);

    try {
      l("paying lightning invoice", payreq.substr(-8), total, amount, maxfee);

      r = await ln.pay({
        bolt11: payreq.replace(/\s/g, "").toLowerCase(),
        amount_msat: amount_msat ? undefined : amount * 1000,
        maxfee: maxfee * 1000,
        retry_for: 5,
      });

      if (!(r.status === "complete" && r.payment_preimage))
        fail("Payment did not complete");

      l("payment completed", p.id, r.payment_preimage);

      p.amount = -total;
      p.fee = Math.round((r.amount_sent_msat - r.amount_msat) / 1000);
      p.ref = r.payment_preimage;

      await s(`payment:${p.id}`, p);

      l("refunding fee", maxfee, p.fee, maxfee - p.fee, p.ref);
      await db.incrBy(`balance:${p.uid}`, maxfee - p.fee);
    } catch (e) {
      warn("something went wrong", e.message);
      await check();
      throw e;
    }

    clearInterval(interval);
  }

  return p;
};