cosmic_applet_avestruz/handlers/
zap.rs1use cosmic::iced::clipboard;
19use cosmic::prelude::*;
20use nostr_sdk::prelude::{EventId, RelayUrl};
21
22use crate::fl;
23use crate::handlers::auth::sign_error_text;
24use crate::messages::Message;
25use crate::nostr::zap::{self, Invoice, ZapError, ZapOrder, Zapper};
26use crate::state::{AppModel, ViewState, ZapStage, ZapState};
27use crate::views::components::qr_code;
28
29const DEFAULT_ZAP_SATS: u64 = 21;
31
32const MAX_AMOUNT_DIGITS: usize = 9;
35const MAX_COMMENT_CHARS: usize = 140;
36
37fn zap_error_text(error: ZapError) -> String {
39 match error {
40 ZapError::BadAddress => fl!("zap-error-address"),
41 ZapError::Unreachable(error) => fl!("zap-error-unreachable", error = error),
42 ZapError::Refused(reason) => fl!("zap-error-refused", reason = reason),
43 ZapError::OutOfRange { min, max } => fl!("zap-error-range", min = min, max = max),
44 ZapError::WrongAmount => fl!("zap-error-wrong-amount"),
45 ZapError::Sign(error) => sign_error_text(error),
46 }
47}
48
49fn wallet_address(bolt11: &str) -> String {
52 format!("LIGHTNING:{}", bolt11.to_ascii_uppercase())
53}
54
55impl AppModel {
56 pub(crate) fn zapper(&self) -> Zapper {
58 match &self.account {
59 Some(account) if account.can_sign => Zapper::Account(account.public_key),
60 _ => Zapper::Anonymous,
61 }
62 }
63
64 pub fn handle_zap_note(&mut self, id: EventId) -> Task<cosmic::Action<Message>> {
68 if self.zap.as_ref().is_none_or(|zap| zap.note != id) {
69 let Some(note) = self.note_at_hand(id) else {
70 return Task::none();
71 };
72 let Some(address) = self.profiles.get(¬e.author).and_then(|profile| profile.lightning.clone()) else {
73 return Task::none();
74 };
75 self.zap = Some(ZapState {
76 note: id,
77 recipient: note.author,
78 address,
79 amount: DEFAULT_ZAP_SATS.to_string(),
80 comment: String::new(),
81 stage: ZapStage::Choosing,
82 error: None,
83 });
84 }
85 self.view_state = ViewState::Zap;
86 Task::none()
87 }
88
89 pub fn handle_zap_amount_changed(&mut self, amount: &str) {
91 if let Some(zap) = self.zap.as_mut().filter(|zap| matches!(zap.stage, ZapStage::Choosing)) {
92 zap.amount = amount.chars().filter(char::is_ascii_digit).take(MAX_AMOUNT_DIGITS).collect();
93 zap.error = None;
94 }
95 }
96
97 pub fn handle_zap_comment_changed(&mut self, comment: &str) {
99 if let Some(zap) = self.zap.as_mut().filter(|zap| matches!(zap.stage, ZapStage::Choosing)) {
100 zap.comment = comment.chars().take(MAX_COMMENT_CHARS).collect();
101 }
102 }
103
104 pub fn handle_request_zap_invoice(&mut self) -> Task<cosmic::Action<Message>> {
107 let zapper = self.zapper();
108 let relays: Vec<RelayUrl> = self.config.relays.iter().filter_map(|url| RelayUrl::parse(url).ok()).collect();
110 let Some(zap) = self.zap.as_mut().filter(|zap| matches!(zap.stage, ZapStage::Choosing)) else {
111 return Task::none();
112 };
113 let Some(sats) = zap.sats() else {
114 return Task::none();
115 };
116 zap.stage = ZapStage::Requesting;
117 zap.error = None;
118 let note = zap.note;
119 let order = ZapOrder {
120 address: zap.address.clone(),
121 recipient: zap.recipient,
122 note,
123 sats,
124 comment: zap.comment.trim().to_string(),
125 relays,
126 zapper,
127 };
128 Task::perform(zap::request_invoice(self.http.clone(), self.signer.clone(), order), move |result| {
129 cosmic::Action::App(Message::ZapInvoiceReady { note, result })
130 })
131 }
132
133 pub fn handle_zap_invoice_ready(
136 &mut self,
137 note: EventId,
138 result: Result<Invoice, ZapError>,
139 ) -> Task<cosmic::Action<Message>> {
140 let service = self.nostr.clone();
141 let Some(zap) = self.zap.as_mut().filter(|zap| zap.note == note && matches!(zap.stage, ZapStage::Requesting)) else {
142 return Task::none();
143 };
144 match result {
145 Ok(invoice) => {
146 tracing::info!(
147 "invoice for {} sats ({})",
148 invoice.sats,
149 if invoice.is_zap { "a zap" } else { "a plain payment" }
150 );
151 let qr = qr_code(&wallet_address(&invoice.bolt11));
152 let (waiting, handle) = match service.filter(|_| invoice.is_zap) {
155 Some(service) => {
156 let bolt11 = invoice.bolt11.clone();
157 let (waiting, handle) = Task::perform(
158 async move { service.await_zap_receipt(note, bolt11.clone()).await.then_some(bolt11) },
159 move |paid| cosmic::Action::App(Message::ZapReceiptAwaited { note, paid }),
160 )
161 .abortable();
162 (waiting, Some(handle.abort_on_drop()))
163 }
164 None => (Task::none(), None),
165 };
166 zap.stage = ZapStage::Invoice { invoice, qr, copied: false, waiting: handle };
167 waiting
168 }
169 Err(e) => {
170 tracing::error!("no invoice: {e:?}");
171 zap.stage = ZapStage::Choosing;
172 zap.error = Some(zap_error_text(e));
173 Task::none()
174 }
175 }
176 }
177
178 pub fn handle_copy_zap_invoice(&mut self) -> Task<cosmic::Action<Message>> {
180 match self.zap.as_mut().map(|zap| &mut zap.stage) {
181 Some(ZapStage::Invoice { invoice, copied, .. }) => {
182 *copied = true;
183 clipboard::write(invoice.bolt11.clone())
184 }
185 _ => Task::none(),
186 }
187 }
188
189 pub fn handle_zap_receipt_awaited(&mut self, note: EventId, paid: Option<String>) -> Task<cosmic::Action<Message>> {
192 let Some(zap) = self.zap.as_mut().filter(|zap| zap.note == note) else {
193 return Task::none();
194 };
195 let ZapStage::Invoice { invoice, waiting, .. } = &mut zap.stage else {
196 return Task::none();
197 };
198 match paid {
199 Some(bolt11) if bolt11 == invoice.bolt11 => {
200 tracing::info!("zap of {} sats paid", invoice.sats);
201 zap.stage = ZapStage::Paid { sats: invoice.sats };
202 self.engagement_asked.remove(¬e);
204 self.look_up_engagement([note])
205 }
206 Some(_) => Task::none(),
207 None => {
208 *waiting = None;
209 Task::none()
210 }
211 }
212 }
213
214 pub fn handle_close_zap(&mut self) -> Task<cosmic::Action<Message>> {
217 self.zap = None;
218 self.show_list_view()
219 }
220}
221
222#[cfg(test)]
223mod tests {
224 use super::wallet_address;
225
226 #[test]
227 fn a_wallet_is_given_the_invoice_as_an_address_in_capitals() {
228 assert_eq!(wallet_address("lnbc210n1pjq9xyz"), "LIGHTNING:LNBC210N1PJQ9XYZ");
229 }
230}