flotilla/src/app/lightning.ts

107 lines
2.5 KiB
TypeScript
Raw Normal View History

2026-07-28 16:16:26 +00:00
import {writable} from "svelte/store"
import {nwc} from "@getalby/sdk"
2026-07-28 16:16:26 +00:00
import type {Maybe} from "@welshman/lib"
import {isNWCWallet, isWebLNWallet} from "@welshman/util"
import type {Wallet} from "@welshman/util"
import {withGetter} from "@welshman/store"
export const wallet = withGetter(writable<Maybe<Wallet>>(undefined))
export const getWebLn = () => (window as any).webln
export const getNwcClient = () => {
2026-07-28 16:16:26 +00:00
const $wallet = wallet.get()
2026-07-28 16:16:26 +00:00
if (!$wallet || !isNWCWallet($wallet)) {
throw new Error("No NWC wallet is connected")
}
2026-07-28 16:16:26 +00:00
const {info} = $wallet
if (info.nostrWalletConnectUrl) {
return new nwc.NWCClient({nostrWalletConnectUrl: info.nostrWalletConnectUrl})
}
return new nwc.NWCClient(info)
}
export const payInvoice = async (invoice: string, msats?: number) => {
2026-07-28 16:16:26 +00:00
const $wallet = wallet.get()
2026-07-28 16:16:26 +00:00
if (!$wallet) {
throw new Error("No wallet is connected")
}
2026-07-28 16:16:26 +00:00
if (isNWCWallet($wallet)) {
const params: {invoice: string; amount?: number} = {invoice}
if (msats) params.amount = msats
return getNwcClient().payInvoice(params)
2026-07-28 16:16:26 +00:00
} else if (isWebLNWallet($wallet)) {
if (msats) throw new Error("Unable to pay zero invoices with webln")
return getWebLn()
.enable()
.then(() => getWebLn().sendPayment(invoice))
}
}
export type CreateInvoiceParams = {
sats: number
description?: string
}
export const createInvoice = async ({
sats,
description = "Receive via lightning",
}: CreateInvoiceParams) => {
2026-07-28 16:16:26 +00:00
const $wallet = wallet.get()
2026-07-28 16:16:26 +00:00
if (!$wallet) {
throw new Error("No wallet is connected")
}
const satAmount = Math.floor(sats)
if (!Number.isFinite(satAmount) || satAmount <= 0) {
throw new Error("Invalid satoshi amount")
}
2026-07-28 16:16:26 +00:00
if (isNWCWallet($wallet)) {
const createdInvoice = await getNwcClient().makeInvoice({
amount: satAmount * 1000,
description,
})
if (!createdInvoice.invoice) {
throw new Error("NWC wallet failed to return an invoice")
}
return createdInvoice.invoice
}
2026-07-28 16:16:26 +00:00
if (isWebLNWallet($wallet)) {
const webLn = getWebLn()
if (!webLn) {
throw new Error("WebLN not available")
}
await webLn.enable()
const response = await webLn.makeInvoice({
amount: satAmount,
defaultMemo: description,
})
const paymentRequest =
typeof response === "string" ? response : response?.paymentRequest || response?.pr || ""
if (!paymentRequest) {
throw new Error("Invalid payment request returned from WebLN")
}
return paymentRequest
}
throw new Error("Unsupported wallet type")
}