Skip to content

Commit a145ca6

Browse files
Work on Nostr Client
1 parent 36cc20b commit a145ca6

File tree

2 files changed

+95
-11
lines changed

2 files changed

+95
-11
lines changed

internal_filesystem/apps/com.micropythonos.nostr/assets/nostr.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -103,15 +103,17 @@ def went_online(self):
103103
print("wallet is already running, nothing to do") # might have come from the QR activity
104104
return
105105
try:
106-
from nwc_wallet import NWCWallet
107-
self.wallet = NWCWallet(self.prefs.get_string("nwc_url"))
106+
from nostr_client import NostrClient
107+
self.wallet = NostrClient(self.prefs.get_string("nwc_url"))
108108
self.wallet.static_receive_code = self.prefs.get_string("nwc_static_receive_code")
109109
self.redraw_static_receive_code_cb()
110110
except Exception as e:
111111
self.error_cb(f"Couldn't initialize NWC Wallet because: {e}")
112+
import sys
113+
sys.print_exception(e)
112114
return
113115
self.balance_label.set_text(lv.SYMBOL.REFRESH)
114-
self.payments_label.set_text(f"\nConnecting to {wallet_type} backend.\n\nIf this takes too long, it might be down or something's wrong with the settings.")
116+
self.payments_label.set_text(f"\nConnecting to backend.\n\nIf this takes too long, it might be down or something's wrong with the settings.")
115117
# by now, self.wallet can be assumed
116118
self.wallet.start(self.balance_updated_cb, self.redraw_payments_cb, self.redraw_static_receive_code_cb, self.error_cb)
117119

@@ -182,18 +184,12 @@ def error_cb(self, error):
182184
self.payments_label.set_text(str(error))
183185

184186
def should_show_setting(self, setting):
185-
wallet_type = self.prefs.get_string("wallet_type")
186-
if wallet_type != "lnbits" and setting["key"].startswith("lnbits_"):
187-
return False
188-
if wallet_type != "nwc" and setting["key"].startswith("nwc_"):
189-
return False
190187
return True
191188

192189
def settings_button_tap(self, event):
193190
intent = Intent(activity_class=SettingsActivity)
194191
intent.putExtra("prefs", self.prefs)
195192
intent.putExtra("settings", [
196-
{"title": "Wallet Type", "key": "wallet_type", "ui": "radiobuttons", "ui_options": [("LNBits", "lnbits"), ("Nostr Wallet Connect", "nwc")]},
197193
{"title": "LNBits URL", "key": "lnbits_url", "placeholder": "https://demo.lnpiggy.com", "should_show": self.should_show_setting},
198194
{"title": "LNBits Read Key", "key": "lnbits_readkey", "placeholder": "fd92e3f8168ba314dc22e54182784045", "should_show": self.should_show_setting},
199195
{"title": "Optional LN Address", "key": "lnbits_static_receive_code", "placeholder": "Will be fetched if empty.", "should_show": self.should_show_setting},

internal_filesystem/apps/com.micropythonos.nostr/assets/nostr_client.py

Lines changed: 90 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from payment import Payment
1515
from unique_sorted_list import UniqueSortedList
1616

17-
class NWCWallet():
17+
class NostrClient():
1818

1919
PAYMENTS_TO_SHOW = 6
2020
PERIODIC_FETCH_BALANCE_SECONDS = 60 # seconds
@@ -26,6 +26,7 @@ class NWCWallet():
2626
def __init__(self, nwc_url):
2727
super().__init__()
2828
self.nwc_url = nwc_url
29+
self.payment_list = UniqueSortedList()
2930
if not nwc_url:
3031
raise ValueError('NWC URL is not set.')
3132
self.connected = False
@@ -54,7 +55,6 @@ def getCommentFromTransaction(self, transaction):
5455
print("text/plain field is missing from JSON description")
5556
except Exception as e:
5657
print(f"Info: comment {comment} is not JSON, this is fine, using as-is ({e})")
57-
comment = super().try_parse_as_zap(comment)
5858
return comment
5959

6060
async def async_wallet_manager_task(self):
@@ -279,3 +279,91 @@ def parse_nwc_url(self, nwc_url):
279279
raise RuntimeError(f"Exception parsing NWC URL {nwc_url}: {e}")
280280

281281

282+
# From wallet.py:
283+
# Public variables
284+
# These values could be loading from a cache.json file at __init__
285+
last_known_balance = 0
286+
payment_list = None
287+
static_receive_code = None
288+
289+
# Variables
290+
keep_running = True
291+
292+
# Callbacks:
293+
balance_updated_cb = None
294+
payments_updated_cb = None
295+
static_receive_code_updated_cb = None
296+
error_cb = None
297+
298+
299+
def __str__(self):
300+
if isinstance(self, LNBitsWallet):
301+
return "LNBitsWallet"
302+
elif isinstance(self, NWCWallet):
303+
return "NWCWallet"
304+
305+
def handle_new_balance(self, new_balance, fetchPaymentsIfChanged=True):
306+
if not self.keep_running or new_balance is None:
307+
return
308+
sats_added = new_balance - self.last_known_balance
309+
if new_balance != self.last_known_balance:
310+
print("Balance changed!")
311+
self.last_known_balance = new_balance
312+
print("Calling balance_updated_cb")
313+
self.balance_updated_cb(sats_added)
314+
if fetchPaymentsIfChanged: # Fetching *all* payments isn't necessary if balance was changed by a payment notification
315+
print("Refreshing payments...")
316+
self.fetch_payments() # if the balance changed, then re-list transactions
317+
318+
def handle_new_payment(self, new_payment):
319+
if not self.keep_running:
320+
return
321+
print("handle_new_payment")
322+
self.payment_list.add(new_payment)
323+
self.payments_updated_cb()
324+
325+
def handle_new_payments(self, new_payments):
326+
if not self.keep_running:
327+
return
328+
print("handle_new_payments")
329+
if self.payment_list != new_payments:
330+
print("new list of payments")
331+
self.payment_list = new_payments
332+
self.payments_updated_cb()
333+
334+
def handle_new_static_receive_code(self, new_static_receive_code):
335+
print("handle_new_static_receive_code")
336+
if not self.keep_running or not new_static_receive_code:
337+
print("not self.keep_running or not new_static_receive_code")
338+
return
339+
if self.static_receive_code != new_static_receive_code:
340+
print("it's really a new static_receive_code")
341+
self.static_receive_code = new_static_receive_code
342+
if self.static_receive_code_updated_cb:
343+
self.static_receive_code_updated_cb()
344+
else:
345+
print(f"self.static_receive_code {self.static_receive_code } == new_static_receive_code {new_static_receive_code}")
346+
347+
def handle_error(self, e):
348+
if self.error_cb:
349+
self.error_cb(e)
350+
351+
# Maybe also add callbacks for:
352+
# - started (so the user can show the UI)
353+
# - stopped (so the user can delete/free it)
354+
# - error (so the user can show the error)
355+
def start(self, balance_updated_cb, payments_updated_cb, static_receive_code_updated_cb = None, error_cb = None):
356+
self.keep_running = True
357+
self.balance_updated_cb = balance_updated_cb
358+
self.payments_updated_cb = payments_updated_cb
359+
self.static_receive_code_updated_cb = static_receive_code_updated_cb
360+
self.error_cb = error_cb
361+
TaskManager.create_task(self.async_wallet_manager_task())
362+
363+
def stop(self):
364+
self.keep_running = False
365+
# idea: do a "close connections" call here instead of waiting for polling sub-tasks to notice the change
366+
367+
def is_running(self):
368+
return self.keep_running
369+

0 commit comments

Comments
 (0)