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