lightning.ts raw
1 import { TProfile } from '@/types'
2 import { Invoice } from '@getalby/lightning-tools'
3 import { isEmail } from './utils'
4
5 export function getAmountFromInvoice(invoice: string): number {
6 try {
7 const _invoice = new Invoice({ pr: invoice })
8 return _invoice.satoshi
9 } catch (error) {
10 console.error('Invalid Lightning invoice:', error)
11 return 0
12 }
13 }
14
15 export function getInvoiceDetails(invoice: string): { amount: number; description: string | null } {
16 try {
17 const _invoice = new Invoice({ pr: invoice })
18 return {
19 amount: _invoice.satoshi,
20 description: _invoice.description
21 }
22 } catch (error) {
23 console.error('Invalid Lightning invoice:', error)
24 return {
25 amount: 0,
26 description: null
27 }
28 }
29 }
30
31 export function formatAmount(amount: number) {
32 if (amount < 1000) return amount
33 if (amount < 1000000) return `${Math.round(amount / 100) / 10}k`
34 return `${Math.round(amount / 100000) / 10}M`
35 }
36
37 export function getLightningAddressFromProfile(profile: TProfile) {
38 // Some clients have incorrectly filled in the positions for lud06 and lud16
39 const { lud16: a, lud06: b } = profile
40 let lud16: string | undefined
41 let lud06: string | undefined
42
43 if (a && isEmail(a)) {
44 lud16 = a
45 } else if (b && isEmail(b)) {
46 lud16 = b
47 } else if (b && b.startsWith('lnurl')) {
48 lud06 = b
49 } else if (a && a.startsWith('lnurl')) {
50 lud06 = a
51 }
52
53 return lud16 || lud06 || undefined
54 }