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::CommittedNote;
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>>,
39}
40
41impl PswapChainObserver {
42 pub fn new(store: Arc<dyn Store>) -> Self {
43 Self {
44 store,
45 chain_note_updates: RwLock::new(Vec::new()),
46 }
47 }
48}
49
50#[async_trait(?Send)]
51impl NoteObserver for PswapChainObserver {
52 fn name(&self) -> &'static str {
53 "PswapChainObserver"
54 }
55
56 async fn observe(
57 &self,
58 committed_note: &CommittedNote,
59 attachments: &NoteAttachments,
60 ) -> Result<bool, ClientError> {
61 let Some(attachment) = extract_pswap_attachment(attachments) else {
64 return Ok(false);
65 };
66
67 let inclusion_proof = committed_note.inclusion_proof().clone();
68 self.chain_note_updates.write().push(ObservedPswapNote {
69 note_id: *committed_note.note_id(),
70 attachment,
71 sender: committed_note.sender(),
72 tag: committed_note.metadata().tag(),
73 block_num: inclusion_proof.location().block_num(),
74 inclusion_proof,
75 });
76 Ok(true)
77 }
78
79 async fn apply(&self, sync_update: &crate::sync::StateSyncUpdate) -> Result<(), ClientError> {
82 let chain_note_updates = core::mem::take(&mut *self.chain_note_updates.write());
83
84 if chain_note_updates.is_empty()
86 && sync_update.note_updates().consumed_note_ids().next().is_none()
87 {
88 return Ok(());
89 }
90
91 let round_updates =
92 discover_pswap_rounds(self.store.clone(), sync_update, &chain_note_updates).await?;
93
94 for round_update in round_updates {
95 if let Err(err) = crate::pswap::store::apply_round(&self.store, &round_update).await {
96 warn!(
97 order_id = round_update.order_id.as_canonical_u64(),
98 round_depth = round_update.round_depth,
99 error = ?err,
100 "apply_round failed; lineage left at previous tip",
101 );
102 }
103 }
104 Ok(())
105 }
106}
107
108fn extract_pswap_attachment(attachments: &NoteAttachments) -> Option<PswapNoteAttachment> {
116 let pswap_attach = attachments.find(PswapNote::PSWAP_ATTACHMENT_SCHEME)?;
117 let word = pswap_attach.content().as_words().first()?;
118
119 let amount = AssetAmount::new(word[0].as_canonical_u64()).ok()?;
120 let order_id = word[1];
121 let depth = u32::try_from(word[2].as_canonical_u64()).ok()?;
122 Some(PswapNoteAttachment::new(amount, order_id, depth))
123}
124
125#[cfg(test)]
130mod tests {
131 use alloc::vec::Vec;
135
136 use miden_protocol::note::{NoteAttachment, NoteAttachmentScheme, NoteAttachments};
137 use miden_protocol::{Felt, Word};
138 use miden_standards::note::PswapNote;
139
140 use super::*;
141
142 fn pswap_word(amount: u64, order_id: u64, depth: u64) -> Word {
144 Word::from([
145 Felt::new(amount).unwrap(),
146 Felt::new(order_id).unwrap(),
147 Felt::new(depth).unwrap(),
148 Felt::new(0).unwrap(),
149 ])
150 }
151
152 fn pswap_attachments(word: Word) -> NoteAttachments {
154 NoteAttachments::from(NoteAttachment::with_word(PswapNote::PSWAP_ATTACHMENT_SCHEME, word))
155 }
156
157 #[test]
159 fn extract_pswap_attachment_reads_wellformed_word() {
160 let parsed = extract_pswap_attachment(&pswap_attachments(pswap_word(25, 0xabcd, 3)))
161 .expect("valid PSWAP word must parse");
162 assert_eq!(u64::from(parsed.amount()), 25);
163 assert_eq!(parsed.order_id().as_canonical_u64(), 0xabcd);
164 assert_eq!(parsed.depth(), 3);
165 }
166
167 #[test]
171 fn extract_pswap_attachment_rejects_missing_scheme() {
172 let empty = NoteAttachments::new(Vec::new()).unwrap();
173 assert!(extract_pswap_attachment(&empty).is_none());
174
175 let other = NoteAttachments::from(NoteAttachment::with_word(
177 NoteAttachmentScheme::new(1).unwrap(),
178 pswap_word(1, 2, 3),
179 ));
180 assert!(extract_pswap_attachment(&other).is_none());
181 }
182
183 #[test]
185 fn extract_pswap_attachment_rejects_oversized_amount() {
186 let word = pswap_word(AssetAmount::MAX.as_u64() + 1, 7, 1);
187 assert!(extract_pswap_attachment(&pswap_attachments(word)).is_none());
188 }
189
190 #[test]
193 fn extract_pswap_attachment_rejects_oversized_depth() {
194 let word = pswap_word(10, 7, u64::from(u32::MAX) + 1);
195 assert!(extract_pswap_attachment(&pswap_attachments(word)).is_none());
196 }
197}