Skip to content

Commit 8b8675b

Browse files
wallet: add transactions
1 parent ef1c483 commit 8b8675b

1 file changed

Lines changed: 48 additions & 23 deletions

File tree

  • internal_filesystem/apps/com.lightningpiggy.displaywallet/assets

internal_filesystem/apps/com.lightningpiggy.displaywallet/assets/wallet.py

Lines changed: 48 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,13 @@ def __str__(self):
7676

7777
def handle_new_balance(self, new_balance):
7878
if new_balance != self.last_known_balance:
79+
print("Balance changed!")
7980
self.last_known_balance = new_balance
81+
print("Calling balance_updated_cb")
8082
self.balance_updated_cb()
81-
new_payments = self.fetch_payments() # if the balance changed, then re-list transactions
82-
self.handle_new_payments(new_payments)
83+
# Refreshing isn't strictly necessary if it was changed by a payment notification
84+
print("Refreshing payments...")
85+
self.fetch_payments() # if the balance changed, then re-list transactions
8386

8487
def handle_new_payments(self, new_payments):
8588
print("handle_new_payments")
@@ -119,7 +122,6 @@ def wallet_manager_thread(self):
119122
while self.keep_running:
120123
try:
121124
new_balance = self.fetch_balance()
122-
self.handle_new_balance(new_balance)
123125
except Exception as e:
124126
print(f"WARNING: wallet_manager_thread got exception {e}, ignorning.")
125127
print("Sleeping a while before re-fetching balance...")
@@ -143,7 +145,8 @@ def fetch_balance(self):
143145
balance_reply = json.loads(response_text)
144146
print(f"Got balance: {balance_reply['balance']}")
145147
balance_msat = balance_reply['balance']
146-
return round(balance_msat / 1000)
148+
new_balance = round(int(balance_msat) / 1000)
149+
self.handle_new_balance(new_balance)
147150
except Exception as e:
148151
print(f"Could not parse reponse text '{response_text}' as JSON: {e}")
149152
raise e
@@ -165,20 +168,20 @@ def fetch_payments(self):
165168
payments_reply = json.loads(response_text)
166169
#print(f"Got payments: {payments_reply}")
167170
new_payments = UniqueSortedList()
168-
for payment in payments_reply:
169-
#print(f"Got payment: {payment}")
170-
amount = payment["amount"]
171+
for transaction in payments_reply:
172+
#print(f"Got transaction: {transaction}")
173+
amount = transaction["amount"]
171174
amount = round(amount / 1000)
172-
comment = payment["memo"]
173-
epoch_time = payment["time"]
174-
extra = payment["extra"]
175+
comment = transaction["memo"]
176+
epoch_time = transaction["time"]
177+
extra = transaction["extra"]
175178
if extra:
176179
extracomment = extra["comment"]
177180
if extracomment:
178181
comment = extracomment
179-
payment = Payment(epoch_time, amount, comment)
180-
new_payments.add(payment)
181-
return new_payments
182+
transaction = Payment(epoch_time, amount, comment)
183+
new_payments.add(transaction)
184+
self.handle_new_payments(new_payments)
182185
except Exception as e:
183186
print(f"Could not parse reponse text '{response_text}' as JSON: {e}")
184187
raise e
@@ -211,7 +214,7 @@ def wallet_manager_thread(self):
211214
return
212215

213216
# Set up subscription to receive response
214-
self.subscription_id = "nwc_balance_" + str(round(time.time()))
217+
self.subscription_id = "micropython_nwc_" + str(round(time.time()))
215218
print(f"DEBUG: Setting up subscription with ID: {self.subscription_id}")
216219
self.filters = Filters([Filter(
217220
kinds=[23195], # NWC replies
@@ -224,7 +227,7 @@ def wallet_manager_thread(self):
224227
request_message = [ClientMessageType.REQUEST, self.subscription_id]
225228
request_message.extend(self.filters.to_json_array())
226229
self.relay_manager.publish_message(json.dumps(request_message))
227-
time.sleep(1)
230+
time.sleep(5)
228231

229232
self.fetch_balance()
230233

@@ -243,14 +246,34 @@ def wallet_manager_thread(self):
243246
print(f"DEBUG: Decrypted content: {decrypted_content}")
244247
response = json.loads(decrypted_content)
245248
print(f"DEBUG: Parsed response: {response}")
246-
if response["result"]:
247-
if response["result"]["balance"]:
248-
self.last_known_balance = round(int(response["result"]["balance"]) / 1000)
249-
print(f"Got balance: {self.last_known_balance}")
250-
# TODO: if balance changed, then update list of transactions
251-
self.balance_updated_cb()
252-
elif response["result"]["transactions"]:
253-
print("TODO: Response contains transactions!")
249+
result = response.get("result")
250+
if result:
251+
if result.get("balance"):
252+
new_balance = round(int(response["result"]["balance"]) / 1000)
253+
print(f"Got balance: {new_balance}")
254+
self.handle_new_balance(new_balance)
255+
elif result.get("transactions"):
256+
print("Response contains transactions!")
257+
new_payments = UniqueSortedList()
258+
for transaction in result["transactions"]:
259+
amount = transaction["amount"]
260+
amount = round(amount / 1000)
261+
comment = transaction["description"]
262+
try:
263+
json_comment = json.loads(comment)
264+
for field in json_comment:
265+
if field[0] == "text/plain":
266+
comment = field[1]
267+
break
268+
else:
269+
print("text/plain field is missing from JSON description")
270+
except Exception as e:
271+
print(f"Could not parse comment as JSON: {e}")
272+
pass # NWC description can also be just a regular sting, not json
273+
epoch_time = transaction["created_at"]
274+
payment = Payment(epoch_time, amount, comment)
275+
new_payments.add(payment)
276+
self.handle_new_payments(new_payments)
254277
else:
255278
print("Unsupported response, ignoring.")
256279
else:
@@ -290,8 +313,10 @@ def fetch_payments(self):
290313
dm = EncryptedDirectMessage(
291314
recipient_pubkey=self.wallet_pubkey,
292315
cleartext_content=json.dumps(list_transactions)
316+
#cleartext_content='{"params":{"limit": 4 },"method":"list_transactions"}'
293317
)
294318
self.private_key.sign_event(dm) # sign also does encryption if it's a encrypted dm
319+
print("\n\nPublishing DM to fetch payments...\n\n")
295320
self.relay_manager.publish_event(dm)
296321

297322
def parse_nwc_url(self, nwc_url):

0 commit comments

Comments
 (0)