Repository: lnbits/lnbits

Issue:
[BUG] Deleted wallet balance is included in Wallet Management "LNBits Balance"
**Describe the bug**
Problem: If / When deleted wallets have balance it is calculated to balance on Manage Server page on Wallets Management also after deletion. Issue ruins usability of LNBits Balance and Reserve calculation %.

**To Reproduce**
Steps to reproduce the behavior:

1. Go to super admin page and note LNBits Balance and Reserve% 
2. Go to any wallet with balance
3. Delete the wallet
4. Go to super admin page and notice the LNBits Balance is not change and Reserve  % has not increased

**Expected behavior**
LNBits balance should decrease of amount of deleted wallet had.

- LNbits version: 0.11.1
- Database sqlite

**Additional context**
Even if user would empty before delete, issue remains cause wallet may have millisats, which are impossible for user to drain.

Seems also "Node Balance" does not included balance from disconnected channels (FundingSource LNDRest).

Yvette confirmed at https://t.me/lnbits/80187 issue deleted wallet balance.

**Suggestions to fix** 

1.  Tell how one can set one wallet balance on database to zero, cause updating is not trivial as this:
How you set balance of wallet to zero, cause database.balances rows are views?

on database.sqlite3
sqlite> UPDATE balances SET balance = 0 WHERE wallet = '37cf3944dc8649e.....';
Error: cannot modify balances because it is a view

2. Implemnt "Un-topup" functionality, where Server Super Admin can discard extra balance for eg "Burner Wallet" (wallet that has exessive balance for some reason).

3. Implement change where wallet deletion also zeroes deleted wallet balance, from balances table, including millisats.

Why this is needed?

Cause currently LNBits admin has no idea how much of total balance of users wallets is. Calculation now days counts deleted wallets balance too. ie it counts balances of wallets that no one can access ie it counts wrong.


Discussion:
This is a "feature not a bug" but I agree it should change. When a wallet is deleted, the "lnbits balance" should be deducted by however much that wallet contained. I looked into the code and it involves adding a deduction transaction as part of the deletion process. It would also be nice to "clean up" any previously deleted wallets from the balance. A use-case is when the LN node operator wants to swap-out sats with an onchain payment but deduct the sata from an lnbits wallet, the only way to keep the lnbits wallet balanced is to transfer it to a special "swap-out" wallet. It would be nice to also have the opposite of the "top off" button and allow the admin to subtract sats from a wallet for such an admin case.
> This is a "feature not a bug" but I agree it should change. When a wallet is deleted, the "lnbits balance" should be deducted by however much that wallet contained.

You should explain why you think it should change. Otherwise your comment does not say anything new. 


> > This is a "feature not a bug" but I agree it should change. When a wallet is deleted, the "lnbits balance" should be deducted by however much that wallet contained.
> 
> You should explain why you think it should change. Otherwise your comment does not say anything new. 
> 
> 

Ok. I think it should change.
yes, i also think that should change, eventually the `watchdog` feature aalso should utilize this and turn off payments if lnbits balance exceeds the node balance
Change cause superuser of LNbits cannot know actual balance needed to cover user funds if non-accessible wallets are calculated to balance now.

Should you consider also solution option that wallet with any (Even millisats) can not be deleted? During delecion process move funds to another wallet would be mandatory. This way there would be no deleted wallet with balance. But anyhow solution to fix currently broken balances should be offered to superusers

________________________________
From: Pavol Rusnak ***@***.***>
Sent: Sunday, March 24, 2024 11:22:12 PM
To: lnbits/lnbits ***@***.***>
Cc: Tomi Lind ***@***.***>; Author ***@***.***>
Subject: Re: [lnbits/lnbits] [BUG] Deleted wallet balance is included in Wallet Management "LNBits Balance" (Issue #2224)


This is a "feature not a bug" but I agree it should change. When a wallet is deleted, the "lnbits balance" should be deducted by however much that wallet contained.

You should explain why you think it should change. Otherwise your comment does not say anything new.

—
Reply to this email directly, view it on GitHub<https://github.com/lnbits/lnbits/issues/2224#issuecomment-2016947066>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/ABXJ6Z7M7I2VQPBIOUCTUZLYZ47YJAVCNFSM6AAAAABCQFFY3OVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDAMJWHE2DOMBWGY>.
You are receiving this because you authored the thread.Message ID: ***@***.***>


Resolving patch:
diff --git a/lnbits/core/crud.py b/lnbits/core/crud.py
--- a/lnbits/core/crud.py
+++ b/lnbits/core/crud.py
@@ -587,11 +587,6 @@ async def get_total_balance(conn: Optional[Connection] = None):
     return 0 if row[0] is None else row[0]
 
 
-async def get_active_wallet_total_balance(conn: Optional[Connection] = None):
-    row = await (conn or db).fetchone("SELECT SUM(balance) FROM balances")
-    return 0 if row[0] is None else row[0]
-
-
 # wallet payments
 # ---------------
 
diff --git a/lnbits/core/migrations.py b/lnbits/core/migrations.py
--- a/lnbits/core/migrations.py
+++ b/lnbits/core/migrations.py
@@ -471,3 +471,23 @@ async def m017_add_timestamp_columns_to_accounts_and_wallets(db):
     except OperationalError as exc:
         logger.error(f"Migration 17 failed: {exc}")
         pass
+
+
+async def m018_balances_view_exclude_deleted(db):
+    """
+    Make deleted wallets not show up in the balances view.
+    """
+    await db.execute("DROP VIEW balances")
+    await db.execute(
+        """
+        CREATE VIEW balances AS
+        SELECT apipayments.wallet,
+               SUM(apipayments.amount - ABS(apipayments.fee)) AS balance
+        FROM apipayments
+        LEFT JOIN wallets ON apipayments.wallet = wallets.id
+        WHERE (wallets.deleted = false OR wallets.deleted is NULL)
+              AND ((apipayments.pending = false AND apipayments.amount > 0)
+              OR apipayments.amount < 0)
+        GROUP BY wallet
+    """
+    )


Test patch: