|
| 1 | +import { nwc } from '@getalby/sdk' |
| 2 | + |
| 3 | +import { CreateInvoiceRequest, CreateInvoiceResponse, GetInvoiceResponse, IPaymentsProcessor } from '../@types/clients' |
| 4 | +import { Factory } from '../@types/base' |
| 5 | +import { Invoice, InvoiceStatus, InvoiceUnit } from '../@types/invoice' |
| 6 | +import { Settings } from '../@types/settings' |
| 7 | +import { createLogger } from '../factories/logger-factory' |
| 8 | + |
| 9 | +const debug = createLogger('alby-nwc-payments-processor') |
| 10 | + |
| 11 | +type NwcTransaction = { |
| 12 | + state?: 'settled' | 'pending' | 'expired' | 'failed' | 'accepted' |
| 13 | + invoice?: string |
| 14 | + payment_hash?: string |
| 15 | + amount?: number |
| 16 | + description?: string |
| 17 | + created_at?: number |
| 18 | + settled_at?: number |
| 19 | + expires_at?: number |
| 20 | +} |
| 21 | + |
| 22 | +const mapNwcStateToInvoiceStatus = (state?: NwcTransaction['state']): InvoiceStatus => { |
| 23 | + switch (state) { |
| 24 | + case 'settled': |
| 25 | + return InvoiceStatus.COMPLETED |
| 26 | + case 'expired': |
| 27 | + case 'failed': |
| 28 | + return InvoiceStatus.EXPIRED |
| 29 | + case 'accepted': |
| 30 | + case 'pending': |
| 31 | + default: |
| 32 | + return InvoiceStatus.PENDING |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +const timestampToDate = (unixSeconds?: number): Date | null => { |
| 37 | + if (typeof unixSeconds === 'number' && Number.isFinite(unixSeconds) && unixSeconds > 0) { |
| 38 | + return new Date(unixSeconds * 1000) |
| 39 | + } |
| 40 | + |
| 41 | + return null |
| 42 | +} |
| 43 | + |
| 44 | +export class AlbyNwcInvoice implements Invoice { |
| 45 | + id: string |
| 46 | + pubkey: string |
| 47 | + bolt11: string |
| 48 | + amountRequested: bigint |
| 49 | + amountPaid?: bigint |
| 50 | + unit: InvoiceUnit |
| 51 | + status: InvoiceStatus |
| 52 | + description: string |
| 53 | + confirmedAt?: Date | null |
| 54 | + expiresAt: Date | null |
| 55 | + updatedAt: Date |
| 56 | + createdAt: Date |
| 57 | +} |
| 58 | + |
| 59 | +export class AlbyNwcCreateInvoiceResponse implements CreateInvoiceResponse { |
| 60 | + id: string |
| 61 | + pubkey: string |
| 62 | + bolt11: string |
| 63 | + amountRequested: bigint |
| 64 | + description: string |
| 65 | + unit: InvoiceUnit |
| 66 | + status: InvoiceStatus |
| 67 | + expiresAt: Date | null |
| 68 | + confirmedAt?: Date | null |
| 69 | + createdAt: Date |
| 70 | + rawResponse?: string |
| 71 | +} |
| 72 | + |
| 73 | +export class AlbyNwcPaymentsProcessor implements IPaymentsProcessor { |
| 74 | + public constructor( |
| 75 | + private nwcUrl: string, |
| 76 | + private replyTimeoutMs: number, |
| 77 | + private settings: Factory<Settings>, |
| 78 | + ) {} |
| 79 | + |
| 80 | + private withReplyTimeout = async <T>(operation: Promise<T>): Promise<T> => { |
| 81 | + let timeoutId: ReturnType<typeof setTimeout> | undefined |
| 82 | + |
| 83 | + try { |
| 84 | + return await Promise.race([ |
| 85 | + operation, |
| 86 | + new Promise<never>((_, reject) => { |
| 87 | + timeoutId = setTimeout(() => { |
| 88 | + reject(new nwc.Nip47ReplyTimeoutError(`reply timeout after ${this.replyTimeoutMs}ms`, 'INTERNAL')) |
| 89 | + }, this.replyTimeoutMs) |
| 90 | + }), |
| 91 | + ]) |
| 92 | + } finally { |
| 93 | + if (timeoutId) { |
| 94 | + clearTimeout(timeoutId) |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + private withClient = async <T>(fn: (client: nwc.NWCClient) => Promise<T>): Promise<T> => { |
| 100 | + const client = new nwc.NWCClient({ nostrWalletConnectUrl: this.nwcUrl }) |
| 101 | + |
| 102 | + try { |
| 103 | + return await fn(client) |
| 104 | + } finally { |
| 105 | + client.close() |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + public async getInvoice(invoiceOrId: string | Invoice): Promise<GetInvoiceResponse> { |
| 110 | + const invoiceId = typeof invoiceOrId === 'string' ? invoiceOrId : invoiceOrId.id |
| 111 | + debug('get invoice: %s', invoiceId) |
| 112 | + |
| 113 | + try { |
| 114 | + return await this.withClient(async (client) => { |
| 115 | + const transaction = (await this.withReplyTimeout( |
| 116 | + client.lookupInvoice({ payment_hash: invoiceId }), |
| 117 | + )) as NwcTransaction |
| 118 | + const status = mapNwcStateToInvoiceStatus(transaction.state) |
| 119 | + |
| 120 | + const invoice = new AlbyNwcInvoice() |
| 121 | + invoice.id = transaction.payment_hash || invoiceId |
| 122 | + invoice.pubkey = typeof invoiceOrId === 'string' ? '' : invoiceOrId.pubkey |
| 123 | + invoice.bolt11 = transaction.invoice || (typeof invoiceOrId === 'string' ? '' : invoiceOrId.bolt11) |
| 124 | + invoice.amountRequested = |
| 125 | + typeof transaction.amount === 'number' && Number.isFinite(transaction.amount) |
| 126 | + ? BigInt(Math.trunc(transaction.amount)) |
| 127 | + : typeof invoiceOrId === 'string' |
| 128 | + ? 0n |
| 129 | + : invoiceOrId.amountRequested |
| 130 | + invoice.amountPaid = status === InvoiceStatus.COMPLETED ? invoice.amountRequested : undefined |
| 131 | + invoice.unit = InvoiceUnit.MSATS |
| 132 | + invoice.status = status |
| 133 | + invoice.description = transaction.description || (typeof invoiceOrId === 'string' ? '' : invoiceOrId.description) |
| 134 | + invoice.confirmedAt = status === InvoiceStatus.COMPLETED ? (timestampToDate(transaction.settled_at) ?? new Date()) : null |
| 135 | + invoice.expiresAt = timestampToDate(transaction.expires_at) |
| 136 | + invoice.createdAt = timestampToDate(transaction.created_at) ?? new Date() |
| 137 | + invoice.updatedAt = new Date() |
| 138 | + |
| 139 | + return invoice |
| 140 | + }) |
| 141 | + } catch (error) { |
| 142 | + if (error instanceof nwc.Nip47WalletError || error instanceof nwc.Nip47ReplyTimeoutError) { |
| 143 | + console.error(`Unable to get Alby NWC invoice ${invoiceId}. Reason:`, error.message) |
| 144 | + } else { |
| 145 | + console.error(`Unable to get Alby NWC invoice ${invoiceId}. Reason:`, error) |
| 146 | + } |
| 147 | + throw error |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + public async createInvoice(request: CreateInvoiceRequest): Promise<CreateInvoiceResponse> { |
| 152 | + debug('create invoice: %o', request) |
| 153 | + const { amount: amountMsats, description, requestId: pubkey } = request |
| 154 | + |
| 155 | + try { |
| 156 | + return await this.withClient(async (client) => { |
| 157 | + const expirySeconds = this.settings().paymentsProcessors?.alby?.invoiceExpirySeconds |
| 158 | + const transaction = (await this.withReplyTimeout( |
| 159 | + client.makeInvoice({ |
| 160 | + amount: Number(amountMsats), |
| 161 | + description, |
| 162 | + expiry: expirySeconds, |
| 163 | + }), |
| 164 | + )) as NwcTransaction |
| 165 | + |
| 166 | + const invoice = new AlbyNwcCreateInvoiceResponse() |
| 167 | + invoice.id = transaction.payment_hash || '' |
| 168 | + invoice.pubkey = pubkey |
| 169 | + invoice.bolt11 = transaction.invoice || '' |
| 170 | + invoice.amountRequested = |
| 171 | + typeof transaction.amount === 'number' && Number.isFinite(transaction.amount) |
| 172 | + ? BigInt(Math.trunc(transaction.amount)) |
| 173 | + : amountMsats |
| 174 | + invoice.description = transaction.description || description || '' |
| 175 | + invoice.unit = InvoiceUnit.MSATS |
| 176 | + invoice.status = mapNwcStateToInvoiceStatus(transaction.state) |
| 177 | + invoice.confirmedAt = invoice.status === InvoiceStatus.COMPLETED ? (timestampToDate(transaction.settled_at) ?? new Date()) : null |
| 178 | + invoice.expiresAt = timestampToDate(transaction.expires_at) |
| 179 | + invoice.createdAt = timestampToDate(transaction.created_at) ?? new Date() |
| 180 | + invoice.rawResponse = JSON.stringify(transaction) |
| 181 | + |
| 182 | + return invoice |
| 183 | + }) |
| 184 | + } catch (error) { |
| 185 | + if (error instanceof nwc.Nip47WalletError || error instanceof nwc.Nip47ReplyTimeoutError) { |
| 186 | + console.error('Unable to request Alby NWC invoice. Reason:', error.message) |
| 187 | + } else { |
| 188 | + console.error('Unable to request Alby NWC invoice. Reason:', error) |
| 189 | + } |
| 190 | + throw error |
| 191 | + } |
| 192 | + } |
| 193 | +} |
0 commit comments