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;
if (walletPromise) return walletPromise;
walletPromise = (async () => {
try {
await loadProofs(); await loadProofs();
try { try {
await getMnemonic(); await getMnemonic();
} catch (_) {} } catch (_) {}
const mint = new CashuMint(MINT_URL); const mint = new CashuMint(MINT_URL);
wallet = new CashuWallet(mint); const w = new CashuWallet(mint);
await wallet.loadMint(); await w.loadMint();
await tryRedeemUnredeemedCashuQuotes();
try { tryRedeemUnredeemedCashuQuotes()
console.log(`cashu addr: ${await getCashuAddress()}`); .then(() => persistProofs())
} catch (_) { .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);
} }
})();
await persistProofs(); return walletPromise;
return wallet; }
})();
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;