bug: fix cashu wallet not being loaded all the time

This commit is contained in:
Danny Morabito 2025-07-07 18:26:29 +02:00
parent 1df32badfb
commit 18a5227033
Signed by: dannym
GPG key ID: 7CC8056A5A04557E

View file

@ -188,28 +188,46 @@ async function tryRedeemUnredeemedCashuQuotes() {
return quotes;
}
let wallet: CashuWallet | undefined;
let wallet: CashuWallet | null = null;
let walletPromise: Promise<CashuWallet> | null = null;
const walletReady = (async () => {
export async function getWallet(): Promise<CashuWallet> {
if (wallet) return wallet;
await loadProofs();
try {
await getMnemonic();
} catch (_) {}
if (walletPromise) return walletPromise;
const mint = new CashuMint(MINT_URL);
wallet = new CashuWallet(mint);
await wallet.loadMint();
await tryRedeemUnredeemedCashuQuotes();
walletPromise = (async () => {
try {
await loadProofs();
try {
await getMnemonic();
} catch (_) {}
try {
console.log(`cashu addr: ${await getCashuAddress()}`);
} catch (_) {
}
const mint = new CashuMint(MINT_URL);
const w = new CashuWallet(mint);
await w.loadMint();
await persistProofs();
return wallet;
})();
tryRedeemUnredeemedCashuQuotes()
.then(() => persistProofs())
.catch((err) => console.error("Failed background redemption", err));
getCashuAddress()
.then((addr) => console.log(`cashu addr: ${addr}`))
.catch(() => {});
wallet = w;
return w;
} catch (err) {
walletPromise = null;
throw err;
} finally {
setTimeout(() => {
if (wallet) walletPromise = null;
}, 0);
}
})();
return walletPromise;
}
let quoteRedeemInterval: ReturnType<typeof setInterval> | undefined;
if (quoteRedeemInterval) clearInterval(quoteRedeemInterval);
@ -275,7 +293,7 @@ async function maybeMelt() {
if (balance < meltThreshold) return;
try {
const wallet = await walletReady;
const wallet = await getWallet();
const invoice = await createMeltInvoice(balance - (balance % 2000));
const meltQuote = await wallet.createMeltQuote(invoice);
@ -337,7 +355,7 @@ loadCashuTxns();
export async function payBolt11Invoice(invoice: string): Promise<void> {
if (!invoice.trim()) throw new Error("Invoice is empty");
const wallet = await walletReady;
const wallet = await getWallet();
const meltQuote = await wallet.createMeltQuote(invoice);
const amountToMelt = meltQuote.amount + meltQuote.fee_reserve;