Skip to main content

cosmic_applet_avestruz/handlers/
zap.rs

1// SPDX-License-Identifier: MIT
2
3//! Zap message handlers for Avestruz.
4//!
5//! Zapping a note opens a view of its own: how much, and a word to go with
6//! it. The author's Lightning address is then asked for an invoice, which
7//! shows as a QR code for a wallet to scan; this client holds no money and
8//! pays nothing itself.
9//!
10//! While the invoice is on show the relays are listened to for the receipt
11//! the author's wallet service publishes once it is paid. When it comes the
12//! view says so, and the note's count has it. The listening stops when the
13//! view is left.
14//!
15//! Anyone can zap. With a secret key the zap is the account's; without one
16//! the request is signed with a key made for it, and the zap is anonymous.
17
18use 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
29/// What the amount field starts at, in sats.
30const DEFAULT_ZAP_SATS: u64 = 21;
31
32/// How long an amount may be typed, in digits, and a comment, in
33/// characters.
34const MAX_AMOUNT_DIGITS: usize = 9;
35const MAX_COMMENT_CHARS: usize = 140;
36
37/// Why there is no invoice, in the user's language.
38fn 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
49/// What a wallet scans to pay `bolt11`: the invoice as a `lightning:`
50/// address, in capitals, which a QR code holds in fewer modules.
51fn wallet_address(bolt11: &str) -> String {
52    format!("LIGHTNING:{}", bolt11.to_ascii_uppercase())
53}
54
55impl AppModel {
56    /// Who a zap sent now would be from.
57    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    /// Open the zap view for the note `id`, which is one on show and whose
65    /// author has a Lightning address. A zap of the same note that was left
66    /// open comes back as it was.
67    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(&note.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    /// The amount was typed, or a preset chosen. Only digits are kept.
90    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    /// The comment was typed.
98    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    /// Ask the author's Lightning address for an invoice of the amount
105    /// chosen.
106    pub fn handle_request_zap_invoice(&mut self) -> Task<cosmic::Action<Message>> {
107        let zapper = self.zapper();
108        // Where the receipt is looked for afterwards: the relays read from.
109        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    /// The invoice for the zap of `note` came, or didn't. One that comes
134    /// after the view was left, or for another zap, is let go.
135    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                // Only a zap is announced; a plain payment has no receipt
153                // to wait for.
154                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    /// Copy the invoice on show, for a wallet on this machine.
179    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    /// The wait for the receipt of `note`'s zap ended: with the invoice
190    /// that was paid, or with nothing when the time ran out.
191    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                // The receipt is in the store now: count the note again.
203                self.engagement_asked.remove(&note);
204                self.look_up_engagement([note])
205            }
206            Some(_) => Task::none(),
207            None => {
208                *waiting = None;
209                Task::none()
210            }
211        }
212    }
213
214    /// Leave the zap view for what it was opened from. Whatever was being
215    /// waited for is let go.
216    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}