add refund functionality

This commit is contained in:
Danny Morabito 2025-07-09 13:27:37 +02:00
parent 15202e5339
commit 43217f327e
Signed by: dannym
GPG key ID: 7CC8056A5A04557E

View file

@ -435,4 +435,64 @@ export default class PortalBtcWallet {
listener();
}
}
/**
* Refunds a payment
*
* @param payment - The payment to refund
*/
async refundPayment(payment: Payment) {
if (!this.breezSDK) throw new Error("Breez SDK not initialized");
const prepareAddr = await this.breezSDK.prepareReceivePayment({
paymentMethod: "bitcoinAddress",
});
const receiveRes = await this.breezSDK.receivePayment({
prepareResponse: prepareAddr,
});
const refundAddress = receiveRes.destination as string;
try {
const refundables = await this.breezSDK.listRefundables();
let swapAddress: string | undefined;
if (refundables.length === 1) {
swapAddress = refundables[0]?.swapAddress;
} else {
swapAddress = refundables.find(
(r) =>
r.amountSat === payment.amountSat &&
Math.abs(r.timestamp - payment.timestamp) < 300,
)?.swapAddress;
}
if (!swapAddress) {
throw new Error("Could not identify refundable swap for this payment.");
}
const fees = await this.breezSDK.recommendedFees();
const feeRateSatPerVbyte = fees.economyFee;
const refundRequest = {
swapAddress,
refundAddress,
feeRateSatPerVbyte,
} as const;
try {
await this.breezSDK.prepareRefund(refundRequest);
} catch (err) {
console.warn(
"prepareRefund failed (may be expected for some swaps)",
err,
);
return;
}
await this.breezSDK.refund(refundRequest);
} catch (err) {
console.error("Refund failed", err);
throw new Error(
`Refund failed: ${err instanceof Error ? err.message : err}`,
);
}
}
}