miden_client/note/
mod.rs

1//! Contains the Client APIs related to notes. Notes can contain assets and scripts that are
2//! executed as part of transactions.
3//!
4//! This module enables the tracking, retrieval, and processing of notes.
5//! It offers methods to query input and output notes from the store, check their consumability,
6//! compile note scripts, and retrieve notes based on partial ID matching.
7//!
8//! ## Overview
9//!
10//! The module exposes APIs to:
11//!
12//! - Retrieve input notes and output notes.
13//! - Determine the consumability of notes using the [`NoteScreener`].
14//! - Compile note scripts from source code with `compile_note_script`.
15//! - Retrieve an input note by a prefix of its ID using the helper function
16//!   [`get_input_note_with_id_prefix`].
17//!
18//! ## Example
19//!
20//! ```rust
21//! use miden_client::{
22//!     auth::TransactionAuthenticator,
23//!     Client,
24//!     crypto::FeltRng,
25//!     note::{NoteScreener, get_input_note_with_id_prefix},
26//!     store::NoteFilter,
27//! };
28//! use miden_objects::account::AccountId;
29//!
30//! # async fn example<AUTH: TransactionAuthenticator + Sync>(client: &Client<AUTH>) -> Result<(), Box<dyn std::error::Error>> {
31//! // Retrieve all committed input notes
32//! let input_notes = client.get_input_notes(NoteFilter::Committed).await?;
33//! println!("Found {} committed input notes.", input_notes.len());
34//!
35//! // Check consumability for a specific note
36//! if let Some(note) = input_notes.first() {
37//!     let consumability = client.get_note_consumability(note.clone()).await?;
38//!     println!("Note consumability: {:?}", consumability);
39//! }
40//!
41//! // Retrieve an input note by a partial ID match
42//! let note_prefix = "0x70b7ec";
43//! match get_input_note_with_id_prefix(client, note_prefix).await {
44//!     Ok(note) => println!("Found note with matching prefix: {}", note.id().to_hex()),
45//!     Err(err) => println!("Error retrieving note: {err:?}"),
46//! }
47//!
48//! // Compile the note script
49//! let script_src = "begin push.9 push.12 add end";
50//! let note_script = client.script_builder().compile_note_script(script_src)?;
51//! println!("Compiled note script successfully.");
52//!
53//! # Ok(())
54//! # }
55//! ```
56//!
57//! For more details on the API and error handling, see the documentation for the specific functions
58//! and types in this module.
59
60use alloc::string::ToString;
61use alloc::vec::Vec;
62
63use miden_objects::account::AccountId;
64use miden_tx::auth::TransactionAuthenticator;
65
66use crate::store::{InputNoteRecord, NoteFilter, OutputNoteRecord};
67use crate::{Client, ClientError, IdPrefixFetchError};
68
69mod import;
70mod note_screener;
71mod note_update_tracker;
72
73// RE-EXPORTS
74// ================================================================================================
75
76pub use miden_lib::note::utils::{build_p2id_recipient, build_swap_tag};
77pub use miden_lib::note::well_known_note::WellKnownNote;
78pub use miden_lib::note::{create_p2id_note, create_swap_note};
79pub use miden_objects::NoteError;
80pub use miden_objects::block::BlockNumber;
81pub use miden_objects::note::{
82    Note,
83    NoteAssets,
84    NoteDetails,
85    NoteExecutionHint,
86    NoteExecutionMode,
87    NoteFile,
88    NoteId,
89    NoteInclusionProof,
90    NoteInputs,
91    NoteMetadata,
92    NoteRecipient,
93    NoteScript,
94    NoteTag,
95    NoteType,
96    Nullifier,
97};
98pub use note_screener::{NoteConsumability, NoteRelevance, NoteScreener, NoteScreenerError};
99pub use note_update_tracker::{
100    InputNoteUpdate,
101    NoteUpdateTracker,
102    NoteUpdateType,
103    OutputNoteUpdate,
104};
105
106/// Note retrieval methods.
107impl<AUTH> Client<AUTH>
108where
109    AUTH: TransactionAuthenticator + Sync,
110{
111    // INPUT NOTE DATA RETRIEVAL
112    // --------------------------------------------------------------------------------------------
113
114    /// Retrieves the input notes managed by the client from the store.
115    ///
116    /// # Errors
117    ///
118    /// Returns a [`ClientError::StoreError`] if the filter is [`NoteFilter::Unique`] and there is
119    /// no Note with the provided ID.
120    pub async fn get_input_notes(
121        &self,
122        filter: NoteFilter,
123    ) -> Result<Vec<InputNoteRecord>, ClientError> {
124        self.store.get_input_notes(filter).await.map_err(Into::into)
125    }
126
127    /// Returns the input notes and their consumability. Assuming the notes will be consumed by a
128    /// normal consume transaction. If `account_id` is None then all consumable input notes are
129    /// returned.
130    ///
131    /// The note screener runs a series of checks to determine whether the note can be executed as
132    /// part of a transaction for a specific account. If the specific account ID can consume it (ie,
133    /// if it's compatible with the account), it will be returned as part of the result list.
134    pub async fn get_consumable_notes(
135        &self,
136        account_id: Option<AccountId>,
137    ) -> Result<Vec<(InputNoteRecord, Vec<NoteConsumability>)>, ClientError> {
138        let committed_notes = self.store.get_input_notes(NoteFilter::Committed).await?;
139
140        let note_screener = NoteScreener::new(self.store.clone(), self.authenticator.clone());
141
142        let mut relevant_notes = Vec::new();
143        for input_note in committed_notes {
144            let mut account_relevance =
145                note_screener.check_relevance(&input_note.clone().try_into()?).await?;
146
147            if let Some(account_id) = account_id {
148                account_relevance.retain(|(id, _)| *id == account_id);
149            }
150
151            if account_relevance.is_empty() {
152                continue;
153            }
154
155            relevant_notes.push((input_note, account_relevance));
156        }
157
158        Ok(relevant_notes)
159    }
160
161    /// Returns the consumability conditions for the provided note.
162    ///
163    /// The note screener runs a series of checks to determine whether the note can be executed as
164    /// part of a transaction for a specific account. If the specific account ID can consume it (ie,
165    /// if it's compatible with the account), it will be returned as part of the result list.
166    pub async fn get_note_consumability(
167        &self,
168        note: InputNoteRecord,
169    ) -> Result<Vec<NoteConsumability>, ClientError> {
170        let note_screener = NoteScreener::new(self.store.clone(), self.authenticator.clone());
171        note_screener
172            .check_relevance(&note.clone().try_into()?)
173            .await
174            .map_err(Into::into)
175    }
176
177    /// Retrieves the input note given a [`NoteId`]. Returns `None` if the note is not found.
178    pub async fn get_input_note(
179        &self,
180        note_id: NoteId,
181    ) -> Result<Option<InputNoteRecord>, ClientError> {
182        Ok(self.store.get_input_notes(NoteFilter::Unique(note_id)).await?.pop())
183    }
184
185    // OUTPUT NOTE DATA RETRIEVAL
186    // --------------------------------------------------------------------------------------------
187
188    /// Returns output notes managed by this client.
189    pub async fn get_output_notes(
190        &self,
191        filter: NoteFilter,
192    ) -> Result<Vec<OutputNoteRecord>, ClientError> {
193        self.store.get_output_notes(filter).await.map_err(Into::into)
194    }
195
196    /// Retrieves the output note given a [`NoteId`]. Returns `None` if the note is not found.
197    pub async fn get_output_note(
198        &self,
199        note_id: NoteId,
200    ) -> Result<Option<OutputNoteRecord>, ClientError> {
201        Ok(self.store.get_output_notes(NoteFilter::Unique(note_id)).await?.pop())
202    }
203}
204
205/// Returns the client input note whose ID starts with `note_id_prefix`.
206///
207/// # Errors
208///
209/// - Returns [`IdPrefixFetchError::NoMatch`] if we were unable to find any note where
210///   `note_id_prefix` is a prefix of its ID.
211/// - Returns [`IdPrefixFetchError::MultipleMatches`] if there were more than one note found where
212///   `note_id_prefix` is a prefix of its ID.
213pub async fn get_input_note_with_id_prefix<AUTH>(
214    client: &Client<AUTH>,
215    note_id_prefix: &str,
216) -> Result<InputNoteRecord, IdPrefixFetchError>
217where
218    AUTH: TransactionAuthenticator + Sync,
219{
220    let mut input_note_records = client
221        .get_input_notes(NoteFilter::All)
222        .await
223        .map_err(|err| {
224            tracing::error!("Error when fetching all notes from the store: {err}");
225            IdPrefixFetchError::NoMatch(format!("note ID prefix {note_id_prefix}").to_string())
226        })?
227        .into_iter()
228        .filter(|note_record| note_record.id().to_hex().starts_with(note_id_prefix))
229        .collect::<Vec<_>>();
230
231    if input_note_records.is_empty() {
232        return Err(IdPrefixFetchError::NoMatch(
233            format!("note ID prefix {note_id_prefix}").to_string(),
234        ));
235    }
236    if input_note_records.len() > 1 {
237        let input_note_record_ids =
238            input_note_records.iter().map(InputNoteRecord::id).collect::<Vec<_>>();
239        tracing::error!(
240            "Multiple notes found for the prefix {}: {:?}",
241            note_id_prefix,
242            input_note_record_ids
243        );
244        return Err(IdPrefixFetchError::MultipleMatches(
245            format!("note ID prefix {note_id_prefix}").to_string(),
246        ));
247    }
248
249    Ok(input_note_records
250        .pop()
251        .expect("input_note_records should always have one element"))
252}