diff --git a/src/lib/cashu.svelte.ts b/src/lib/cashu.svelte.ts index dd4408e..cdd8363 100644 --- a/src/lib/cashu.svelte.ts +++ b/src/lib/cashu.svelte.ts @@ -188,28 +188,46 @@ async function tryRedeemUnredeemedCashuQuotes() { return quotes; } -let wallet: CashuWallet | undefined; +let wallet: CashuWallet | null = null; +let walletPromise: Promise | null = null; -const walletReady = (async () => { +export async function getWallet(): Promise { 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 | 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 { 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;