add refund functionality
This commit is contained in:
parent
15202e5339
commit
43217f327e
1 changed files with 60 additions and 0 deletions
60
index.ts
60
index.ts
|
|
@ -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}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue