miden_client/pswap/
observer.rs1use alloc::boxed::Box;
5use alloc::sync::Arc;
6use alloc::vec::Vec;
7
8use async_trait::async_trait;
9use miden_protocol::asset::AssetAmount;
10use miden_protocol::note::NoteAttachments;
11use miden_standards::note::{PswapNote, PswapNoteAttachment};
12use tracing::warn;
13
14use crate::ClientError;
15use crate::pswap::discovery::discover_pswap_rounds;
16use crate::pswap::lineage::ObservedPswapNote;
17use crate::rpc::domain::note::SyncedNote;
18use crate::store::Store;
19use crate::sync::NoteObserver;
20use crate::utils::RwLock;
21
22pub struct PswapChainObserver {
33 store: Arc<dyn Store>,
34 chain_note_updates: RwLock<Vec<ObservedPswapNote>>,
38}
39
40impl PswapChainObserver {
41 pub fn new(store: Arc<dyn Store>) -> Self {
42 Self {
43 store,
44 chain_note_updates: RwLock::new(Vec::new()),
45 }
46 }
47}
48
49#[async_trait(?Send)]
50impl NoteObserver for PswapChainObserver {
51 fn name(&self) -> &'static str {
52 "PswapChainObserver"
53 }
54
55 async fn observe(&self, note: &SyncedNote) -> Result<bool, ClientError> {
56 let Some(attachment) = extract_pswap_attachment(¬e.attachments) else {
59 return Ok(false);
60 };
61
62 let inclusion_proof = note.inclusion_proof.clone();
63 self.chain_note_updates.write().push(ObservedPswapNote {
64 note_id: note.note_id,
65 attachment,
66 sender: note.metadata.sender(),
67 tag: note.metadata.tag(),
68 block_num: inclusion_proof.location().block_num(),
69 inclusion_proof,
70 });
71 Ok(true)
72 }
73
74 async fn apply(&self, sync_update: &crate::sync::StateSyncUpdate) -> Result<(), ClientError> {
77 let chain_note_updates = core::mem::take(&mut *self.chain_note_updates.write());
78
79 if chain_note_updates.is_empty()
81 && sync_update.note_updates().consumed_note_ids().next().is_none()
82 {
83 return Ok(());
84 }
85
86 let round_updates =
87 discover_pswap_rounds(self.store.clone(), sync_update, &chain_note_updates).await?;
88
89 for round_update in round_updates {
90 if let Err(err) = crate::pswap::store::apply_round(&self.store, &round_update).await {
91 warn!(
92 order_id = round_update.order_id.as_canonical_u64(),
93 round_depth = round_update.round_depth,
94 error = ?err,
95 "apply_round failed; lineage left at previous tip",
96 );
97 }
98 }
99 Ok(())
100 }
101}
102
103fn extract_pswap_attachment(attachments: &NoteAttachments) -> Option<PswapNoteAttachment> {
110 let pswap_attach = attachments.find(PswapNote::PSWAP_ATTACHMENT_SCHEME)?;
111 let word = pswap_attach.content().as_words().first()?;
112
113 let amount = AssetAmount::new(word[0].as_canonical_u64()).ok()?;
114 let order_id = word[1];
115 let depth = u32::try_from(word[2].as_canonical_u64()).ok()?;
116 Some(PswapNoteAttachment::new(amount, order_id, depth))
117}
118
119#[cfg(test)]
124mod tests {
125 use alloc::vec::Vec;
128
129 use miden_protocol::note::{NoteAttachment, NoteAttachmentScheme, NoteAttachments};
130 use miden_protocol::{Felt, Word};
131 use miden_standards::note::PswapNote;
132
133 use super::*;
134
135 fn pswap_word(amount: u64, order_id: u64, depth: u64) -> Word {
137 Word::from([
138 Felt::new(amount).unwrap(),
139 Felt::new(order_id).unwrap(),
140 Felt::new(depth).unwrap(),
141 Felt::new(0).unwrap(),
142 ])
143 }
144
145 fn pswap_attachments(word: Word) -> NoteAttachments {
147 NoteAttachments::from(NoteAttachment::with_word(PswapNote::PSWAP_ATTACHMENT_SCHEME, word))
148 }
149
150 #[test]
152 fn extract_pswap_attachment_reads_wellformed_word() {
153 let parsed = extract_pswap_attachment(&pswap_attachments(pswap_word(25, 0xabcd, 3)))
154 .expect("valid PSWAP word must parse");
155 assert_eq!(u64::from(parsed.amount()), 25);
156 assert_eq!(parsed.order_id().as_canonical_u64(), 0xabcd);
157 assert_eq!(parsed.depth(), 3);
158 }
159
160 #[test]
163 fn extract_pswap_attachment_rejects_missing_scheme() {
164 let empty = NoteAttachments::new(Vec::new()).unwrap();
165 assert!(extract_pswap_attachment(&empty).is_none());
166
167 let other = NoteAttachments::from(NoteAttachment::with_word(
169 NoteAttachmentScheme::new(1).unwrap(),
170 pswap_word(1, 2, 3),
171 ));
172 assert!(extract_pswap_attachment(&other).is_none());
173 }
174
175 #[test]
177 fn extract_pswap_attachment_rejects_oversized_amount() {
178 let word = pswap_word(AssetAmount::MAX.as_u64() + 1, 7, 1);
179 assert!(extract_pswap_attachment(&pswap_attachments(word)).is_none());
180 }
181
182 #[test]
185 fn extract_pswap_attachment_rejects_oversized_depth() {
186 let word = pswap_word(10, 7, u64::from(u32::MAX) + 1);
187 assert!(extract_pswap_attachment(&pswap_attachments(word)).is_none());
188 }
189}