aboutsummaryrefslogtreecommitdiffstats
path: root/views/layout.html
diff options
context:
space:
mode:
Diffstat (limited to 'views/layout.html')
0 files changed, 0 insertions, 0 deletions
href='/coinos-server.git/blame/routes/payments.ts?h=regtest-fulcrum&id=4f2e4ffdd5de8819abf2fe505fca4af12d3d7f6f'>^
4b59d73b ^
8c7fa95d ^
b07b5ed5 ^
11a7c49e ^










11a7c49e ^

b07b5ed5 ^
80470a2c ^
11a7c49e ^
80470a2c ^

a55eb812 ^
80470a2c ^



80470a2c ^
9473aad7 ^
11a7c49e ^
8c7fa95d ^
963aa2d1 ^
91e84712 ^
4efa82b3 ^
ad6bbbd5 ^


4efa82b3 ^
11a7c49e ^
9662c275 ^
501e2ba1 ^
11a7c49e ^
40f3fb49 ^
36539ce5 ^
63fe7c28 ^
d2db386e ^
11a7c49e ^
b67ca07b ^

30910e1a ^
40f3fb49 ^



06308bb1 ^

df386245 ^
06308bb1 ^
2ff6a289 ^



501e2ba1 ^
2ff6a289 ^
7de7a87d ^
7de7a87d ^
40f3fb49 ^

06308bb1 ^






d15c03fe ^
3fb8e0bd ^






f0c9dd97 ^


40f3fb49 ^
7de7a87d ^
d62cc3b3 ^
40f3fb49 ^

96f865cd ^
77b9560d ^
40f3fb49 ^

91e84712 ^
a440edf4 ^
4efa82b3 ^


d2db386e ^
4efa82b3 ^
4c287cfd ^
4efa82b3 ^
53a4d40f ^


d2db386e ^

fc226864 ^
d2db386e ^
79c048cc ^

2eb199b8 ^

70d75264 ^
11a7c49e ^
6f36b0a9 ^
70d75264 ^
dd52d07a ^
6f36b0a9 ^

d2db386e ^
2eb199b8 ^
3fb8e0bd ^

2eb199b8 ^
b67ca07b ^
2eb199b8 ^

63f50dcb ^
2eb199b8 ^

11a7c49e ^
7be5db4d ^



d2db386e ^
7be5db4d ^








d2db386e ^
7be5db4d ^

4c9cc0ec ^
7be5db4d ^






11a7c49e ^

2eb199b8 ^
79c048cc ^
2eb199b8 ^

7be5db4d ^
91e84712 ^

4efa82b3 ^
a41ba43f ^
11a7c49e ^
a41ba43f ^

11a7c49e ^
3fb8e0bd ^

e663cb2f ^
a41ba43f ^

5642b90b ^
a41ba43f ^


91e84712 ^

4efa82b3 ^
11a7c49e ^
4efa82b3 ^


91f8f3bd ^
11a7c49e ^
193457c5 ^
11a7c49e ^
91e84712 ^
9f02f34a ^




91e84712 ^
4f5617ca ^









11a7c49e ^

91e84712 ^
11a7c49e ^
d18ad032 ^
11a7c49e ^

fbf27aae ^


8b67a32b ^
0acff570 ^
4f5617ca ^
91f8f3bd ^
8b67a32b ^
963aa2d1 ^

4efa82b3 ^
11a7c49e ^
05b18b10 ^
4efa82b3 ^
05b18b10 ^
f7357de3 ^
f0c9dd97 ^
05b18b10 ^
63f50dcb ^
963aa2d1 ^

567512dd ^
963aa2d1 ^

63f50dcb ^
05b18b10 ^
6b077077 ^

963aa2d1 ^

1629a9ea ^
















841e5434 ^
05b18b10 ^

















4efa82b3 ^




cb9d3293 ^
d2db386e ^
6bdedce7 ^

4a9d5e1f ^
6b21771f ^
4b59d73b ^







6b21771f ^
5ffc5ee9 ^
6b21771f ^
05b18b10 ^
6b21771f ^

5ffc5ee9 ^

6b21771f ^
4b59d73b ^






6b21771f ^

4b59d73b ^
6b21771f ^
6bdedce7 ^
6bdedce7 ^
4b59d73b ^


6b21771f ^
4b59d73b ^



























6bdedce7 ^
7e8a2158 ^
cb9d3293 ^
6bdedce7 ^
ef367905 ^

1629a9ea ^





b3b12c6c ^
1629a9ea ^

















b3b12c6c ^
1629a9ea ^






b3b12c6c ^


1629a9ea ^



b3b12c6c ^























4efa82b3 ^
11a7c49e ^
4efa82b3 ^


39b669f5 ^
11a7c49e ^


80365c22 ^

144ffdb0 ^
11a7c49e ^
5c105c8f ^
3fb8e0bd ^

5c105c8f ^

11a7c49e ^
5c105c8f ^
13f3c21b ^
80365c22 ^




3ac47dfb ^
80365c22 ^

5c105c8f ^



11a7c49e ^
5c105c8f ^

11a7c49e ^
99e2c2b1 ^
65523113 ^
5c105c8f ^




01e16862 ^
5c105c8f ^

11a7c49e ^

5c105c8f ^


11a7c49e ^

5c105c8f ^

d2db386e ^
5c105c8f ^







01e16862 ^

5c105c8f ^

11a7c49e ^
1d5053fe ^
5264f702 ^

39b669f5 ^

13f3c21b ^
39b669f5 ^

5264f702 ^
2edcafb3 ^

4efa82b3 ^
11a7c49e ^
39b669f5 ^
96f865cd ^
39b669f5 ^
80f67a64 ^






8bcf2787 ^

aa4cd39c ^
39b669f5 ^
2edcafb3 ^

4efa82b3 ^
11a7c49e ^
94f8e7a2 ^
9a7cbaf3 ^
11a7c49e ^


2edcafb3 ^
92bd9085 ^
94f8e7a2 ^
e295b8d3 ^
94f8e7a2 ^

19480e0c ^
12bf0c93 ^
4efa82b3 ^
11a7c49e ^
4efa82b3 ^

30910e1a ^

417f6697 ^
30910e1a ^






4efa82b3 ^
11a7c49e ^
4efa82b3 ^


cfca71ff ^
11a7c49e ^
cfca71ff ^

63f50dcb ^
11a7c49e ^
63f50dcb ^
1d5053fe ^
63f50dcb ^
b67ca07b ^
63f50dcb ^

cfca71ff ^



2f1372b5 ^

4efa82b3 ^

a1a95f4f ^
4efa82b3 ^


2f1372b5 ^
63f50dcb ^
bad17599 ^

11a7c49e ^

b67ca07b ^
92bd9085 ^
2f1372b5 ^
11a7c49e ^
bad17599 ^
2f1372b5 ^

11a7c49e ^
92bd9085 ^
11a7c49e ^
63f50dcb ^
11a7c49e ^

c8adb563 ^

b6f56cec ^
44b5d463 ^
5c105c8f ^
501e2ba1 ^
bad17599 ^

2f1372b5 ^
63f50dcb ^
2f1372b5 ^

63fe7c28 ^
517065e5 ^
4efa82b3 ^
11a7c49e ^
4efa82b3 ^


517065e5 ^


144ffdb0 ^
4efa82b3 ^
11a7c49e ^
4efa82b3 ^


144ffdb0 ^
11a7c49e ^
144ffdb0 ^


11a7c49e ^

144ffdb0 ^
11a7c49e ^
144ffdb0 ^


11a7c49e ^

144ffdb0 ^






11a7c49e ^
144ffdb0 ^
11a7c49e ^
3498d1b6 ^
144ffdb0 ^



11a7c49e ^
144ffdb0 ^

c9a70b8e ^

144ffdb0 ^
11a7c49e ^
c9a70b8e ^
3498d1b6 ^
144ffdb0 ^


996d76af ^
144ffdb0 ^


2a60293d ^
4efa82b3 ^
11a7c49e ^
4efa82b3 ^


2a60293d ^
11a7c49e ^
f1cd8904 ^
2a60293d ^
9c3b89f9 ^




4f5617ca ^
0acff570 ^


4f5617ca ^
53a4d40f ^









8c7fa95d ^




a1a95f4f ^
8c7fa95d ^




















91e84712 ^
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
                             

                                       
                                   
                                         
                                        
                         










                                            

                                    
                                         
        
       

       
         



             
                    
                              
                      
                          
 
                
                      


                                 
                          
                               
 
                                                         
                                                  
 
         
                                          
                                         
                                                                

                                 
 



                                       

                                                                         
                   
                                                       



                                                                   
                                                                           
         
       
 

                   






                                  
                          






                                   


                                                        
         
       
 

                  
                                                                           
                     

                           
    
 


                        
                                                          
            
                                              
 


                                                       

                                          
 
                                                                      

                                                                              

                        
                                     
                                              
                   
                                                     
                                                           

                     
                                               
                                                           

                                                  
                   
           

       
                       

                                             
                           



                                                                      
                                                                         








                                                    
                                                                     

                                                    
                          






                              

                                                                              
 
                                       

                                                                 
                                                      

    
                       
         
             

                         
                                       

                                              
                                                                              

                  
                     


                                              

    
                         
           


                       
         
                                  
                                   
                                   
 




                                              
 









                                                                       

                                                            
 
                                                    
                                                                          

                                                            


                                          
                 
                     
                                        
                           
     

    
                        
           
                     
            
                                         
                                                         
                                         
                                                                         
                                                                               

                      
                                                                              

      
                                         
 

                                                                         

    
















                                                                                
 

















                                                                         




                                         
         
                                       

                                             
                                     
 







                                                 
                                                           
                                                    
                                                 
                                                                

                                                        

                                                      
 






                                                 

                   
                       
                                 
           
 


                                                   
       



























                                                                               
                 
                                                                      
                           
     

    





                                                           
                                                       

















                                                            
                                              






                                     


                                                         



                       























                                                              
                           
           


                                   
         


                                                                         

                             
 
                                                                         
                               

                                                                       

                                  
                                           
                           
 




                                                            
                                                            

           



                                    
                                                      

                 
                                                    
                                                     
                                           




                                   
                

                                        

                                                        


                                               

                                                    

                             
                                                               







                                                           

                                                          

                    
                                                
                                                  

         

                   
                     

                                         
     

    
                       
                               
         
                                               
                 






                                 

                                        
                                                        
     

    
                        
                               
         
                                       


                                                                  
 
                  
                 
                                                       

                                    
    
 
                          
           

                       

                                                            
                              






                           
                         
           


                   
         
                                         

                                                  
 
                                
 
                   
                 
                                                                  

        



                             

    

                             
                                         


            
         
                                                

                                       

                                                                          
                                                           
                       
 
                                                
                                                                     

                                    
                                                                             
                                   
                       
 

                                            

            
                         
                                                          
                                                               
                                                                      

                  
                 
                     

                           
    
 
                           
           


                                          


                                       
 
                           
           


                   
         
                                         


                                                  

                                               
 
                                                                                


                 

                         






                                                                    
                                                                   
 
                                                        
                                       



                                   
                                           

                                              

                                                                  
                                                                       
                                                      
                                                               
                                         


                             
                                                   


                           
 
                            
           


                                 
 
                                              
                                                                
    




                                      
 


                                                                          
    









                           




                                  
 




















                                                                       
  
import config from "$config";
import api from "$lib/api";
import { requirePin } from "$lib/auth";
import { db, g, s } from "$lib/db";
import { generate } from "$lib/invoices";
import { replay } from "$lib/lightning";
import ln from "$lib/ln";
import { err, l, warn } from "$lib/logging";
import mqtt from "$lib/mqtt";
import {
  build,
  completePayment,
  credit,
  debit,
  decode,
  sendInternal,
  sendLightning,
  sendOnchain,
} from "$lib/payments";
import { emit } from "$lib/sockets";
import { PaymentType } from "$lib/types";
import {
  SATS,
  bail,
  fail,
  fields,
  getInvoice,
  getPayment,
  getUser,
  sats,
} from "$lib/utils";
import rpc from "@coinos/rpc";
import got from "got";
import { v4 } from "uuid";

export default {
  async info(_, res) {
    res.send(await ln.getinfo());
  },

  async create(req, res) {
    const { body, user } = req;

    let { amount, hash, fee, fund, memo, payreq } = body;
    const balance = await g(`balance:${user.id}`);

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

      await requirePin({ body, user });

      let p;

      const invoice = await getInvoice(payreq || hash);
      const recipient = invoice ? await getUser(invoice.uid) : undefined;
      if (payreq) {
        if (invoice && recipient.username !== "mint") {
          if (invoice.aid === user.id) fail("Cannot send to self");
          hash = payreq;
          if (!amount) ({ amount } = invoice);
        } else {
          p = await sendLightning({ user, pr: payreq, amount, fee, memo });
        }
      }

      if (!p) {
        if (hash) {
          p = await sendInternal({
            invoice,
            amount,
            memo,
            recipient,
            sender: user,
          });
        } else if (fund) {
          p = await debit({
            hash,
            amount,
            memo: fund,
            user,
            type: PaymentType.fund,
          });
          await db.incrBy(`fund:${fund}`, amount);
          await db.lPush(`fund:${fund}:payments`, p.id);
          l("funded fund", fund);
        }
      }

      res.send(p);
    } catch (e) {
      warn(user.username, "payment failed", amount, balance, hash, payreq);
      err(e.message);
      bail(res, e.message);
    }
  },

  async list(req, res) {
    let {
      user: { id },
      query: { aid, start, end, limit, offset, received },
    } = req;
    if (!aid || aid === "undefined") aid = id;

    const index = await db.lPos(`${id}:accounts`, aid);
    if (index === null) fail("unauthorized");

    limit = Number.parseInt(limit);
    offset = Number.parseInt(offset) || 0;

    const range = !limit || received || start || end ? -1 : limit - 1;
    let payments = (await db.lRange(`${aid || id}:payments`, 0, range)) || [];

    payments = (
      await Promise.all(
        payments.map(async (pid) => {
          const p = await g(`payment:${pid}`);
          if (!p) {
            warn("user", id, "missing payment", pid);
            await db.lRem(`${aid || id}:payments`, 0, pid);
            return p;
          }
          if (received && p.amount < 0) return;
          if (p.created < start || p.created > end) return;
          if (p.type === PaymentType.internal)
            p.with = await getUser(p.ref, fields);
          return p;
        }),
      )
    )
      .filter((p) => p)
      .sort((a, b) => b.created - a.created);

    const fn = (a, b) => ({
      ...a,
      [b.currency]: {
        tips: (a[b.currency] ? a[b.currency].tips : 0) + (b.tip || 0),
        fiatTips: (
          Number.parseFloat(a[b.currency] ? a[b.currency].fiatTips : 0) +
          ((b.tip || 0) * b.rate) / SATS
        ).toFixed(2),
        sats:
          (a[b.currency] ? a[b.currency].sats : 0) +
          (b.amount || 0) +
          (b.tip || 0) -
          (b.fee || 0) -
          (b.ourfee || 0),
        fiat: (
          Number.parseFloat(a[b.currency] ? a[b.currency].fiat : 0) +
          (((b.amount || 0) +
            ((b.amount > 0 ? b.tip : -b.tip) || 0) -
            (b.fee || 0) -
            (b.ourfee || 0)) *
            b.rate) /
            SATS
        ).toFixed(2),
      },
    });

    const incoming = payments.filter((p: any) => p.amount > 0).reduce(fn, {});
    const outgoing = payments.filter((p: any) => p.amount < 0).reduce(fn, {});

    const { length: count } = payments;
    if (limit) payments = payments.slice(offset, offset + limit);

    res.send({ payments, count, incoming, outgoing });
  },

  async get(req, res) {
    try {
      const {
        params: { hash },
      } = req;
      const p = await getPayment(hash);
      if (p?.type === PaymentType.internal)
        p.with = await getUser(p.ref, fields);
      if (p?.type === PaymentType.fund) p.with = await getUser(p.uid, fields);
      res.send(p);
    } catch (e) {
      console.log(e);
      err("failed to get payment", e.message);
      bail(res, e.message);
    }
  },

  async parse(req, res) {
    const {
      body: { payreq },
      user,
    } = req;
    try {
      const hour = 1000 * 60 * 60;
      let nodes = await g("nodes");
      const { last } = nodes || {};

      if (!last || last > Date.now() - hour) {
        ({ nodes } = await ln.listnodes());
        nodes.last = Date.now();
        await s("nodes", nodes);
      }

      const decoded = await ln.decode(payreq);

      let amount_msat;
      let payee;

      if (decoded.type.includes("bolt12")) {
        ({ invoice_amount_msat: amount_msat, invoice_node_id: payee } =
          decoded);
      } else ({ amount_msat, payee } = decoded);

      const node = nodes.find((n) => n.nodeid === payee);
      const alias = node ? node.alias : payee.substr(0, 12);

      const amount = Math.round(amount_msat / 1000);
      let ourfee = Math.round(amount * config.fee[PaymentType.lightning]);
      const credit = await g(`credit:lightning:${user.id}`);
      const covered = Math.min(credit, ourfee) || 0;
      ourfee -= covered;

      res.send({ alias, amount, ourfee });
    } catch (e) {
      console.log(e);
      err("problem parsing", e.message);
      bail(res, e.message);
    }
  },

  async fund(req, res) {
    const {
      params: { id },
    } = req;
    const amount = await g(`fund:${id}`);
    if (typeof amount === "undefined" || amount === null)
      return bail(res, "fund not found");
    let payments = (await db.lRange(`fund:${id}:payments`, 0, -1)) || [];
    payments = await Promise.all(payments.map((hash) => g(`payment:${hash}`)));

    await Promise.all(
      payments.map(async (p: any) => (p.user = await getUser(p.uid, fields))),
    );

    payments = payments.filter((p) => p);

    const authorization = await g(`authorization:${id}`);
    res.send({ amount, authorization: authorization?.amount, payments });
  },

  // async withdraw(req, res) {
  //   const {
  //     params: { name },
  //   } = req;
  //   const { user } = req;
  //   const balance = await g(`fund:${name}`);
  //   const managers = await db.sMembers(`fund:${name}:managers`);
  //   if (managers.length && !managers.includes(user.id)) fail("Unauthorized");
  //   res.send({
  //     tag: "withdrawRequest",
  //     callback: `${URL}/api/lnurlw`,
  //     k1: name,
  //     defaultDescription: `Withdraw from coinos fund ${name}`,
  //     minWithdrawable: balance > 0 ? 1000 : 0,
  //     maxWithdrawable: balance * 1000,
  //   });
  // },

  async authorize(req, res) {
    const { id: uid } = req.user;
    const { id, fiat, currency, amount } = req.body;

    const managers = await db.sMembers(`fund:${id}:managers`);
    if (managers.length && !managers.includes(uid)) fail("Unauthorized");

    const authorization = {
      uid,
      currency,
      fiat,
      amount,
    };

    await s(`authorization:${id}`, authorization);
    res.send({});
  },

  async take(req, res) {
    let {
      body: { id, amount, invoice: iid },
      user,
    } = req;
    try {
      amount = Number.parseInt(amount);
      if (amount < 0) fail("Invalid amount");

      const rates = await g("rates");

      if (!iid) {
        const inv = await generate({
          invoice: { amount, type: "lightning" },
          user,
        });
        iid = inv.id;
      }

      const authorization = await g(`authorization:${id}`);
      if (authorization && !authorization.claimed) {
        const { currency, fiat } = authorization;
        amount = Math.min(amount, sats(fiat / rates[currency]));

        const sender = await getUser(authorization.uid);
        authorization.claimed = true;
        await s(`authorization:${id}`, authorization);

        const { hash } = await generate({
          invoice: { amount, type: "lightning" },
          user: sender,
        });

        const { id: pid } = await debit({
          hash,
          amount,
          memo: id,
          user: sender,
          type: PaymentType.fund,
        });

        await db.incrBy(`fund:${id}`, amount);
        await db.lPush(`fund:${id}:payments`, pid);
        l("funded fund", id);
      }

      const managers = await db.sMembers(`fund:${id}:managers`);
      if (managers.length && !managers.includes(user.id)) fail("Unauthorized");

      const result: any = await db.debit(
        `fund:${id}`,
        "",
        "Insufficient funds",
        amount,
        0,
        0,
        0,
        0,
      );
      if (result.err) fail(result.err);

      const payment = await credit({
        aid: user.id,
        hash: iid,
        amount,
        memo: id,
        ref: id,
        type: PaymentType.fund,
      });

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

      res.send(payment);
    } catch (e) {
      warn("problem withdrawing from fund", user.username, e.message);
      bail(res, e.message);
    }
  },

  async managers(req, res) {
    const { name } = req.params;

    const ids = await db.sMembers(`fund:${name}:managers`);

    const managers = await Promise.all(
      ids.map(async (id) => await getUser(id, fields)),
    );

    res.send(managers);
  },

  async addManager(req, res) {
    const { id, username } = req.body;
    const { user } = req;

    const k = `fund:${id}:managers`;

    let managers = await db.sMembers(k);
    if (managers.length) {
      if (!managers.includes(user.id)) fail("Unauthorized");
    } else {
      await db.sAdd(k, user.id);
    }

    const u = await getUser(username, fields);
    if (!u) fail("User not found");
    const { id: uid } = u;

    await db.sAdd(k, uid);

    const ids = await db.sMembers(k);
    if (!managers.length)
      managers = await Promise.all(
        ids.map(async (id) => await getUser(id, fields)),
      );

    res.send(managers);
  },

  async deleteManager(req, res) {
    try {
      const { name } = req.params;
      const { id: uid } = req.body;
      const { user } = req;

      const k = `fund:${name}:managers`;
      let managers = await db.sMembers(k);

      if (managers.length) {
        if (!managers.includes(user.id)) fail("Unauthorized");
      }

      await db.sRem(k, uid);

      const ids = await db.sMembers(k);
      managers = await Promise.all(
        ids.map(async (id) => await getUser(id, fields)),
      );

      res.send(managers);
    } catch (e) {}
  },

  async confirm(req, res) {
    const {
      body: { txid, wallet, type },
    } = req;

    try {
      const node = rpc({ ...config[type], wallet });
      const { confirmations, details } = await node.getTransaction(txid);
      const hot = wallet === config[type].wallet;
      let aid;
      if (!hot) aid = wallet;

      for (const { address, amount, asset, category, vout } of details) {
        if (!address) continue;
        if (type === PaymentType.liquid && asset !== config.liquid.btc)
          continue;

        if (category === "send") {
          const p = await getPayment(txid);
          if (!p) continue;

          if (confirmations) {
            p.confirmed = true;
            await s(`payment:${p.id}`, p);
            if (aid) await db.sRem(`inflight:${aid}`, p.id);
          } else {
            if (aid) await db.sAdd(`inflight:${aid}`, p.id);
          }

          emit(p.uid, "payment", p);
          continue;
        }

        const p = await getPayment(`${txid}:${vout}`);

        if (!p) {
          const invoice = await getInvoice(address);
          if (!hot && aid !== invoice?.aid) continue;
          if (sats(amount) < 500) continue;
          await credit({
            hash: address,
            amount: sats(amount),
            ref: `${txid}:${vout}`,
            type,
            aid,
          });
        } else if (confirmations >= 1) {
          const id = `payment:${txid}:${vout}`;
          const p = await getPayment(`${txid}:${vout}`);
          if (!p) return db.sAdd("missed", id);
          if (p.confirmed) return;

          const invoice = await getInvoice(address);
          const { id: iid } = invoice;

          p.confirmed = true;
          invoice.received += Number.parseInt(invoice.pending);
          invoice.pending = 0;

          l("confirming", id, p.id, p.amount);

          await db
            .multi()
            .set(`invoice:${iid}`, JSON.stringify(invoice))
            .set(`payment:${p.id}`, JSON.stringify(p))
            .decrBy(`pending:${p.aid || p.uid}`, p.amount)
            .incrBy(`balance:${p.aid || p.uid}`, p.amount)
            .exec();

          const user = await g(`user:${p.uid}`);
          await completePayment(invoice, p, user);
        }
      }
      res.send({});
    } catch (e) {
      console.log(e);
      warn(`problem processing ${txid}`);
      bail(res, e.message);
    }
  },

  async fee(req, res) {
    const { body, user } = req;
    try {
      res.send(await build({ ...body, user }));
    } catch (e) {
      warn(
        "problem estimating fee",
        e.message,
        user.username,
        body.amount,
        body.address,
      );
      let msg = e.message;
      if (msg.includes("500")) msg = "";
      bail(res, `Failed to prepare transaction ${msg}`);
    }
  },

  async send(req, res) {
    const { body, user } = req;
    try {
      await requirePin({ body, user });
      const { hash: txid } = await sendOnchain({ ...body, user });
      const pid = await g(`payment:${txid}`);
      const p = await g(`payment:${pid}`);

      res.send(p);
    } catch (e) {
      warn(user.username, "payment failed", e.message);
      res.code(500).send(e.message);
    }
  },

  async freeze(req, res) {
    const {
      body: { secret },
    } = req;
    try {
      if (secret !== config.adminpass) fail("unauthorized");
      await s("freeze", true);
      res.send("ok");
    } catch (e) {
      console.log(e);
      bail(res, e.message);
    }
  },

  async print(req, res) {
    const {
      body: { id },
      user,
    } = req;
    try {
      const p = await g(`payment:${id}`);
      if (p.uid !== user.id) fail("unauthorized");
      emit(user.id, "payment", p);

      const { username } = user;

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

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

  async lnaddress(req, res) {
    let {
      params: { lnaddress, amount, fee },
      body,
      user,
    } = req;
    try {
      lnaddress = decodeURIComponent(lnaddress);
      await requirePin({ body, user });

      const [username, domain] = lnaddress.split("@");
      const { minSendable, maxSendable, callback, metadata } = (await got(
        `https://${domain}/.well-known/lnurlp/${username}`,
      ).json()) as any;

      const memo = metadata["text/plain"] || "";
      if (amount * 1000 < minSendable || amount * 1000 > maxSendable)
        fail("amount out of range");

      const r: any = await got(`${callback}?amount=${amount * 1000}`).json();
      if (r.reason) fail(r.reason);
      const { pr } = r;

      const { payee } = await ln.decode(pr);
      const { id } = await ln.getinfo();

      let p;
      if (payee === id) {
        p = await debit({ hash: pr, amount, memo, user });
        await credit({ hash: pr, amount, memo, ref: user.id });
      } else p = await sendLightning({ user, pr, amount, fee, memo });

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

  async gateway(req, res) {
    const {
      body: { short_channel_id, webhook },
    } = req;

    await s(short_channel_id, webhook);
    res.send({ ok: true });
  },

  async replace(req, res) {
    const {
      body: { id },
      user,
    } = req;
    try {
      const p = await g(`payment:${id}`);
      if (!p) fail("Payment not found");
      if (p.uid !== user.id) fail("unauthorized");

      const { tx, type } = await decode(p.hex);
      const node = rpc(config[type]);

      const fees: any = await fetch(`${api[type]}/fees/recommended`).then((r) =>
        r.json(),
      );

      const outputs = [];
      for (const {
        scriptPubKey: { address },
        value,
      } of tx.vout) {
        if (address && !(await node.getAddressInfo(address)).ismine)
          outputs.push({ [address]: value });
      }

      const raw = await node.createRawTransaction(tx.vin, outputs);

      const newTx = await node.fundRawTransaction(raw, {
        fee_rate: fees.fastestFee + 50,
        replaceable: true,
        subtractFeeFromOutputs: [],
      });

      const diff = sats(newTx.fee) - p.fee;
      if (diff < 0) fail("fee must increase");

      if (config[type].walletpass)
        await node.walletPassphrase(config[type].walletpass, 300);
      p.hex = (await node.signRawTransactionWithWallet(newTx.hex)).hex;
      const r = await node.testMempoolAccept([p.hex]);
      if (!r[0].allowed) fail(`transaction rejected ${p.hex}`);
      warn("bump", user.username, p.hex);

      res.send({ ok: true });
    } catch (e) {
      err("failed to bump payment", id, e.message);
      bail(res, e.message);
    }
  },

  async internal(req, res) {
    const {
      body: { username, amount },
      user: sender,
    } = req;

    const recipient = await getUser(username);
    res.send(await sendInternal({ amount, sender, recipient }));
  },

  async decode(req, res) {
    const { bolt11 } = req.params;
    res.send(await ln.decode(bolt11));
  },

  async fetchinvoice(req, res) {
    const { amount, offer } = req.body;
    res.send(await ln.fetchinvoice(offer, amount ? amount * 1000 : null));
  },

  async auth(req, res) {
    console.log(req.query);
    res.send(req.query);
  },

  async order(req, res) {
    console.log(req.body);
    res.send(req.body);
  },

  async sendinvoice(req, res) {
    try {
      const { user } = req;
      const { invreq } = req.body;

      const { amount_msat, bolt12, pay_index } = await ln.sendinvoice({
        invreq,
        label: v4(),
      });

      await generate({
        invoice: {
          amount: Math.round(amount_msat / 1000),
          type: "bolt12",
          bolt12,
        },
        user,
      });

      const p = await replay(pay_index);

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