65 lines
2.1 KiB
TypeScript
65 lines
2.1 KiB
TypeScript
import { t } from './i18n'
|
|
import { getAlbyService, isWebLNAvailable } from './alby'
|
|
|
|
export async function copyInvoiceToClipboard(params: {
|
|
invoice: string
|
|
setCopied: (value: boolean) => void
|
|
setErrorMessage: (value: string | null) => void
|
|
showToast: ((message: string, variant?: 'success' | 'info' | 'warning' | 'error', duration?: number) => void) | undefined
|
|
}): Promise<void> {
|
|
try {
|
|
await navigator.clipboard.writeText(params.invoice)
|
|
params.setCopied(true)
|
|
if (params.showToast !== undefined) {
|
|
params.showToast(t('payment.modal.copySuccess'), 'success', 2000)
|
|
}
|
|
scheduleCopiedReset(params.setCopied)
|
|
} catch (e) {
|
|
console.error('Failed to copy:', e)
|
|
params.setErrorMessage(t('payment.modal.copyFailed'))
|
|
}
|
|
}
|
|
|
|
export async function openWalletForInvoice(params: {
|
|
invoice: string
|
|
onPaymentComplete: () => void
|
|
setErrorMessage: (value: string | null) => void
|
|
showToast: ((message: string, variant?: 'success' | 'info' | 'warning' | 'error', duration?: number) => void) | undefined
|
|
}): Promise<void> {
|
|
try {
|
|
await payWithWebLN(params.invoice)
|
|
if (params.showToast !== undefined) {
|
|
params.showToast(t('payment.modal.paymentInitiated'), 'success')
|
|
}
|
|
params.onPaymentComplete()
|
|
} catch (e) {
|
|
const error = normalizePaymentError(e)
|
|
if (isUserCancellationError(error)) {
|
|
return
|
|
}
|
|
console.error('Payment failed:', error)
|
|
params.setErrorMessage(error.message)
|
|
}
|
|
}
|
|
|
|
function normalizePaymentError(error: unknown): Error {
|
|
return error instanceof Error ? error : new Error(String(error))
|
|
}
|
|
|
|
function scheduleCopiedReset(setCopied: (value: boolean) => void): void {
|
|
setTimeout(() => setCopied(false), 2000)
|
|
}
|
|
|
|
function isUserCancellationError(error: Error): boolean {
|
|
return error.message.includes('user rejected') || error.message.includes('cancelled')
|
|
}
|
|
|
|
async function payWithWebLN(invoice: string): Promise<void> {
|
|
const alby = getAlbyService()
|
|
if (!isWebLNAvailable()) {
|
|
throw new Error(t('payment.modal.weblnNotAvailable'))
|
|
}
|
|
await alby.enable()
|
|
await alby.sendPayment(invoice)
|
|
}
|