1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//! Note filtering and listing operations for MultisigClient.
//!
//! This module handles listing consumable notes and filtering them
//! by various criteria (faucet, amount, etc.).
use miden_client::note::NoteConsumptionStatus;
use miden_protocol::account::AccountId;
use miden_protocol::asset::Asset;
use miden_protocol::block::BlockNumber;
use miden_protocol::crypto::rand::RandomCoin;
use miden_protocol::note::NoteId;
use miden_standards::note::{P2idNote, P2ideNote};
use super::MultisigClient;
use crate::error::{MultisigError, Result};
use crate::proposal::{Proposal, TransactionType};
/// A wrapper type for a consumable note with simplified information.
#[derive(Debug, Clone)]
pub struct ConsumableNote {
/// The note ID.
pub id: NoteId,
/// Assets contained in the note.
pub assets: Vec<Asset>,
}
impl ConsumableNote {
/// Returns the total amount of a specific fungible asset in this note.
pub fn amount_for_faucet(&self, faucet_id: AccountId) -> u64 {
self.assets
.iter()
.filter_map(|asset| asset.as_fungible())
.filter(|fungible| fungible.faucet_id() == faucet_id)
.map(|fungible| fungible.amount().as_u64())
.sum()
}
/// Returns true if this note contains fungible assets from the specified faucet.
pub fn has_faucet(&self, faucet_id: AccountId) -> bool {
self.assets.iter().any(|asset| {
asset
.as_fungible()
.is_some_and(|fungible| fungible.faucet_id() == faucet_id)
})
}
}
/// Filter criteria for listing consumable notes.
///
/// # Validation
///
/// - `min_amount` requires `faucet_id` to be set (amount is per-faucet)
/// - Use `validate()` to check filter validity before use
#[derive(Debug, Clone, Default)]
pub struct NoteFilter {
/// Only include notes containing assets from this faucet.
pub faucet_id: Option<AccountId>,
/// Only include notes with at least this amount (for the specified faucet).
/// Requires `faucet_id` to be set.
pub min_amount: Option<u64>,
}
impl NoteFilter {
/// Creates a new filter for notes from a specific faucet.
pub fn by_faucet(faucet_id: AccountId) -> Self {
Self {
faucet_id: Some(faucet_id),
min_amount: None,
}
}
/// Creates a new filter for notes from a specific faucet with minimum amount.
pub fn by_faucet_min_amount(faucet_id: AccountId, min_amount: u64) -> Self {
Self {
faucet_id: Some(faucet_id),
min_amount: Some(min_amount),
}
}
/// Validates the filter configuration.
///
/// Returns an error if `min_amount` is set without `faucet_id`,
/// since amount filtering requires a specific faucet to check against.
pub fn validate(&self) -> Result<()> {
if self.min_amount.is_some() && self.faucet_id.is_none() {
return Err(MultisigError::InvalidFilter(
"min_amount requires faucet_id to be set".to_string(),
));
}
Ok(())
}
}
impl MultisigClient {
/// Lists notes that can be consumed by the current account.
///
/// Returns a list of notes that are committed on-chain and can be consumed
/// immediately by the multisig account.
pub async fn list_consumable_notes(&mut self) -> Result<Vec<ConsumableNote>> {
let account_id = self.require_account()?.id();
let consumable = self
.miden_client
.get_consumable_notes(Some(account_id))
.await
.map_err(|e| {
MultisigError::miden_client_with_context("failed to get consumable notes", e)
})?;
// Convert to our wrapper type, filtering for notes consumable
let notes = consumable
.into_iter()
.filter_map(|(record, relevances)| {
// Only include notes consumable now by our account
let can_consume_now = relevances.iter().any(|(id, status)| {
*id == account_id
&& matches!(
status,
NoteConsumptionStatus::Consumable
| NoteConsumptionStatus::ConsumableWithAuthorization
)
});
if can_consume_now {
record.id().map(|id| ConsumableNote {
id,
assets: record.assets().iter().cloned().collect(),
})
} else {
None
}
})
.collect();
Ok(notes)
}
/// Returns a list of all notes with their consumption status
pub async fn list_notes_with_status(
&mut self,
) -> Result<Vec<(ConsumableNote, Vec<(AccountId, String)>)>> {
let account_id = self.require_account()?.id();
let notes = self
.miden_client
.get_consumable_notes(Some(account_id))
.await
.map_err(|e| MultisigError::miden_client_with_context("failed to get notes", e))?;
let result = notes
.into_iter()
.filter(|(_, relevances)| relevances.iter().any(|(id, _)| *id == account_id))
.filter_map(|(record, relevances)| {
let note = ConsumableNote {
id: record.id()?,
assets: record.assets().iter().cloned().collect(),
};
let statuses: Vec<(AccountId, String)> = relevances
.into_iter()
.map(|(id, status)| (id, format!("{:?}", status)))
.collect();
Some((note, statuses))
})
.collect();
Ok(result)
}
/// Returns a list of all committed notes (not just consumable).
pub async fn list_committed_notes(&mut self) -> Result<Vec<ConsumableNote>> {
let account_id = self.require_account()?.id();
let notes = self
.miden_client
.get_consumable_notes(Some(account_id))
.await
.map_err(|e| MultisigError::miden_client_with_context("failed to get notes", e))?;
let result = notes
.into_iter()
.filter(|(_, relevances)| relevances.iter().any(|(id, _)| *id == account_id))
.filter_map(|(record, _)| {
Some(ConsumableNote {
id: record.id()?,
assets: record.assets().iter().cloned().collect(),
})
})
.collect();
Ok(result)
}
/// Lists consumable notes filtered by the given criteria.
///
/// This is a convenience method that combines `list_consumable_notes` with
/// filtering. Use this to find notes from a specific faucet or above a
/// minimum amount.
///
/// # Example
///
/// ```ignore
/// use miden_multisig_client::NoteFilter;
///
/// // Find notes from a specific faucet with at least 1000 tokens
/// let filter = NoteFilter {
/// faucet_id: Some(my_faucet_id),
/// min_amount: Some(1000),
/// };
/// let notes = client.list_consumable_notes_filtered(filter).await?;
/// ```
pub async fn list_consumable_notes_filtered(
&mut self,
filter: NoteFilter,
) -> Result<Vec<ConsumableNote>> {
// Validate filter configuration
filter.validate()?;
let notes = self.list_consumable_notes().await?;
let filtered = notes
.into_iter()
.filter(|note| {
// Filter by faucet
if let Some(faucet_id) = filter.faucet_id {
if !note.has_faucet(faucet_id) {
return false;
}
// Filter by minimum amount (faucet_id is guaranteed to be set if min_amount is)
if let Some(min) = filter.min_amount
&& note.amount_for_faucet(faucet_id) < min
{
return false;
}
}
true
})
.collect();
Ok(filtered)
}
/// Computes the ID of the note a P2ID proposal will create when executed.
///
/// The P2ID note is rebuilt deterministically from the proposal salt, so
/// the ID is known ahead of execution. For a private P2ID this is the ID
/// to pass to `export_note_to_file` after executing, so the note file can be
/// delivered to the recipient out-of-band (issue #356).
///
/// Call this before executing the proposal: the asset is derived from the
/// current vault state, which execution itself changes.
pub fn p2id_note_id(&self, proposal: &Proposal) -> Result<NoteId> {
let account = self.require_account()?;
let TransactionType::P2ID {
recipient,
faucet_id,
amount,
note_type,
heights,
} = &proposal.transaction_type
else {
return Err(MultisigError::UnsupportedTransactionType(
"p2id_note_id requires a P2ID proposal".to_string(),
));
};
if proposal.metadata.salt_hex.is_none() {
return Err(MultisigError::InvalidConfig(
"p2id_note_id requires proposal metadata with a salt".to_string(),
));
}
let salt = proposal.metadata.salt()?;
let asset = crate::execution::build_transfer_asset(*faucet_id, *amount)?;
let mut rng = RandomCoin::new(salt);
let note: miden_protocol::note::Note = if heights.is_p2ide() {
P2ideNote::builder()
.sender(account.id())
.target(*recipient)
.maybe_reclaim_height(heights.reclaim.map(|h| BlockNumber::from(h.get())))
.maybe_timelock_height(heights.timelock.map(|h| BlockNumber::from(h.get())))
.asset(asset)
.note_type(*note_type)
.generate_serial_number(&mut rng)
.build()
.map_err(|e| {
MultisigError::TransactionExecution(format!(
"failed to build P2IDE note: {}",
e
))
})?
.into()
} else {
P2idNote::builder()
.sender(account.id())
.target(*recipient)
.asset(asset)
.note_type(*note_type)
.generate_serial_number(&mut rng)
.build()
.map_err(|e| {
MultisigError::TransactionExecution(format!("failed to build P2ID note: {}", e))
})?
.into()
};
Ok(note.id())
}
}
#[cfg(test)]
mod tests {
use super::*;
// Use a regular account ID for filter validation tests (no FungibleAsset creation)
fn test_account_id() -> AccountId {
AccountId::from_hex("0x7b7b7b7a7b7b7b017b7b7b7b7b7b7b").unwrap()
}
#[test]
fn test_note_filter_validate_min_amount_without_faucet() {
let filter = NoteFilter {
faucet_id: None,
min_amount: Some(1000),
};
assert!(filter.validate().is_err());
}
#[test]
fn test_note_filter_validate_valid() {
// No filter
let filter = NoteFilter::default();
assert!(filter.validate().is_ok());
// Faucet only (any account ID works for validation)
let filter = NoteFilter::by_faucet(test_account_id());
assert!(filter.validate().is_ok());
// Faucet + min_amount
let filter = NoteFilter::by_faucet_min_amount(test_account_id(), 1000);
assert!(filter.validate().is_ok());
}
#[test]
fn test_consumable_note_empty_assets() {
// Test with empty assets - amount should be 0, has_faucet should be false
use miden_protocol::Word;
use miden_protocol::note::NoteId;
let note = ConsumableNote {
id: NoteId::from_raw(Word::default()),
assets: vec![],
};
assert_eq!(note.amount_for_faucet(test_account_id()), 0);
assert!(!note.has_faucet(test_account_id()));
}
}