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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//! Contains structures and functions related to transaction creation.
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::ToString;
use alloc::vec::Vec;
use miden_protocol::account::AccountId;
use miden_protocol::asset::{Asset, FungibleAsset};
use miden_protocol::block::BlockNumber;
use miden_protocol::crypto::merkle::InnerNodeInfo;
use miden_protocol::crypto::merkle::store::MerkleStore;
use miden_protocol::crypto::rand::FeltRng;
use miden_protocol::errors::NoteError;
use miden_protocol::note::{
Note,
NoteAssets,
NoteAttachment,
NoteDetails,
NoteId,
NoteMetadata,
NoteRecipient,
NoteScript,
NoteStorage,
NoteTag,
NoteType,
PartialNote,
};
use miden_protocol::transaction::TransactionScript;
use miden_protocol::vm::AdviceMap;
use miden_protocol::{Felt, Word};
use miden_standards::note::{P2idNote, P2ideNote, P2ideNoteStorage, SwapNote};
use super::{
ForeignAccount,
NoteArgs,
TransactionRequest,
TransactionRequestError,
TransactionScriptTemplate,
};
use crate::ClientRng;
// TRANSACTION REQUEST BUILDER
// ================================================================================================
/// A builder for a [`TransactionRequest`].
///
/// Use this builder to construct a [`TransactionRequest`] by adding input notes, specifying
/// scripts, and setting other transaction parameters.
#[derive(Clone, Debug)]
pub struct TransactionRequestBuilder {
/// Notes to be consumed by the transaction.
/// Notes whose inclusion proof is present in the store are will be consumed as authenticated;
/// the ones that do not have proofs will be consumed as unauthenticated.
input_notes: Vec<Note>,
/// Optional arguments of the Notes to be consumed by the transaction. This
/// includes both authenticated and unauthenticated notes.
input_notes_args: Vec<(NoteId, Option<NoteArgs>)>,
/// Notes to be created by the transaction. The full note data is needed internally
/// to build the transaction script template.
own_output_notes: Vec<Note>,
/// A map of recipients of the output notes expected to be generated by the transaction.
expected_output_recipients: BTreeMap<Word, NoteRecipient>,
/// A map of details and tags of notes we expect to be created as part of future transactions
/// with their respective tags.
///
/// For example, after a swap note is consumed, a payback note is expected to be created.
expected_future_notes: BTreeMap<NoteId, (NoteDetails, NoteTag)>,
/// Custom transaction script to be used.
custom_script: Option<TransactionScript>,
/// Initial state of the `AdviceMap` that provides data during runtime.
advice_map: AdviceMap,
/// Initial state of the `MerkleStore` that provides data during runtime.
merkle_store: MerkleStore,
/// Foreign account data requirements. At execution time, account data will be retrieved from
/// the network, and injected as advice inputs. Additionally, the account's code will be
/// added to the executor and prover.
foreign_accounts: BTreeMap<AccountId, ForeignAccount>,
/// The number of blocks in relation to the transaction's reference block after which the
/// transaction will expire. If `None`, the transaction will not expire.
expiration_delta: Option<u16>,
/// Indicates whether to **silently** ignore invalid input notes when executing the
/// transaction. This will allow the transaction to be executed even if some input notes
/// are invalid.
ignore_invalid_input_notes: bool,
/// Optional [`Word`] that will be pushed to the operand stack before the transaction script
/// execution. If the advice map is extended with some user defined entries, this script
/// argument could be used as a key to access the corresponding value.
script_arg: Option<Word>,
/// Optional [`Word`] that will be pushed to the stack for the authentication procedure
/// during transaction execution.
auth_arg: Option<Word>,
/// Note scripts that the node's NTX builder will need in its script registry.
///
/// See [`TransactionRequestBuilder::expected_ntx_scripts`] for details.
expected_ntx_scripts: Vec<NoteScript>,
}
impl TransactionRequestBuilder {
// CONSTRUCTORS
// --------------------------------------------------------------------------------------------
/// Creates a new, empty [`TransactionRequestBuilder`].
pub fn new() -> Self {
Self {
input_notes: vec![],
input_notes_args: vec![],
own_output_notes: Vec::new(),
expected_output_recipients: BTreeMap::new(),
expected_future_notes: BTreeMap::new(),
custom_script: None,
advice_map: AdviceMap::default(),
merkle_store: MerkleStore::default(),
expiration_delta: None,
foreign_accounts: BTreeMap::default(),
ignore_invalid_input_notes: false,
script_arg: None,
auth_arg: None,
expected_ntx_scripts: vec![],
}
}
/// Adds the specified notes as input notes to the transaction request.
#[must_use]
pub fn input_notes(
mut self,
notes: impl IntoIterator<Item = (Note, Option<NoteArgs>)>,
) -> Self {
for (note, argument) in notes {
self.input_notes_args.push((note.id(), argument));
self.input_notes.push(note);
}
self
}
/// Specifies the output notes that should be created in the transaction script and will
/// be used as a transaction script template. These notes will also be added to the expected
/// output recipients of the transaction.
///
/// If a transaction script template is already set (e.g. by calling `with_custom_script`), the
/// [`TransactionRequestBuilder::build`] method will return an error.
#[must_use]
pub fn own_output_notes(mut self, notes: impl IntoIterator<Item = Note>) -> Self {
for note in notes {
self.expected_output_recipients
.insert(note.recipient().digest(), note.recipient().clone());
self.own_output_notes.push(note);
}
self
}
/// Specifies a custom transaction script to be used.
///
/// If a script template is already set (e.g. by calling `with_own_output_notes`), the
/// [`TransactionRequestBuilder::build`] method will return an error.
#[must_use]
pub fn custom_script(mut self, script: TransactionScript) -> Self {
self.custom_script = Some(script);
self
}
/// Specifies one or more foreign accounts (public or private) that contain data
/// utilized by the transaction.
///
/// At execution, the client queries the node and retrieves the appropriate data,
/// depending on whether each foreign account is public or private:
///
/// - **Public accounts**: the node retrieves the state and code for the account and injects
/// them as advice inputs. Public accounts can be omitted here, as they will be lazily loaded
/// through RPC calls. Undeclared accounts may trigger additional RPC calls for storage map
/// accesses during execution.
/// - **Private accounts**: the node retrieves a proof of the account's existence and injects
/// that as advice inputs. Private accounts must always be declared here with their
/// [`PartialAccount`](miden_protocol::account::PartialAccount) state.
#[must_use]
pub fn foreign_accounts(
mut self,
foreign_accounts: impl IntoIterator<Item = impl Into<ForeignAccount>>,
) -> Self {
for account in foreign_accounts {
let foreign_account: ForeignAccount = account.into();
self.foreign_accounts.insert(foreign_account.account_id(), foreign_account);
}
self
}
/// Specifies a transaction's expected output note recipients.
///
/// The set of specified recipients is treated as a subset of the recipients for notes that may
/// be created by a transaction. That is, the transaction must create notes for all the
/// specified expected recipients, but it may also create notes for other recipients not
/// included in this set.
#[must_use]
pub fn expected_output_recipients(mut self, recipients: Vec<NoteRecipient>) -> Self {
self.expected_output_recipients = recipients
.into_iter()
.map(|recipient| (recipient.digest(), recipient))
.collect::<BTreeMap<_, _>>();
self
}
/// Specifies a set of notes which may be created when a transaction's output notes are
/// consumed.
///
/// For example, after a SWAP note is consumed, a payback note is expected to be created. This
/// allows the client to track this note accordingly.
#[must_use]
pub fn expected_future_notes(mut self, notes: Vec<(NoteDetails, NoteTag)>) -> Self {
self.expected_future_notes =
notes.into_iter().map(|note| (note.0.id(), note)).collect::<BTreeMap<_, _>>();
self
}
/// Extends the advice map with the specified `([Word], Vec<[Felt]>)` pairs.
#[must_use]
pub fn extend_advice_map<I, V>(mut self, iter: I) -> Self
where
I: IntoIterator<Item = (Word, V)>,
V: AsRef<[Felt]>,
{
self.advice_map.extend(iter.into_iter().map(|(w, v)| (w, v.as_ref().to_vec())));
self
}
/// Extends the merkle store with the specified [`InnerNodeInfo`] elements.
#[must_use]
pub fn extend_merkle_store<T: IntoIterator<Item = InnerNodeInfo>>(mut self, iter: T) -> Self {
self.merkle_store.extend(iter);
self
}
/// The number of blocks in relation to the transaction's reference block after which the
/// transaction will expire. By default, the transaction will not expire.
///
/// Setting transaction expiration delta defines an upper bound for transaction expiration,
/// but other code executed during the transaction may impose an even smaller transaction
/// expiration delta.
#[must_use]
pub fn expiration_delta(mut self, expiration_delta: u16) -> Self {
self.expiration_delta = Some(expiration_delta);
self
}
/// The resulting transaction will **silently** ignore invalid input notes when being executed.
/// By default, this will not happen.
#[must_use]
pub fn ignore_invalid_input_notes(mut self) -> Self {
self.ignore_invalid_input_notes = true;
self
}
/// Sets an optional [`Word`] that will be pushed to the operand stack before the transaction
/// script execution. If the advice map is extended with some user defined entries, this script
/// argument could be used as a key to access the corresponding value.
#[must_use]
pub fn script_arg(mut self, script_arg: Word) -> Self {
self.script_arg = Some(script_arg);
self
}
/// Sets an optional [`Word`] that will be pushed to the stack for the authentication
/// procedure during transaction execution.
#[must_use]
pub fn auth_arg(mut self, auth_arg: Word) -> Self {
self.auth_arg = Some(auth_arg);
self
}
/// Specifies note scripts that the node's network transaction (NTX) builder will need in
/// its script registry.
///
/// When a transaction creates notes destined for a network account, the node's NTX builder
/// must have the scripts of any public output notes in its registry. If a required script
/// is missing, the NTX will silently fail on the node side.
///
/// When this field is set, the client will check each script against the node before
/// executing the main transaction. For any script not yet registered, the client
/// automatically creates and submits a separate registration transaction (a public note
/// carrying that script) so the node's registry is populated before the NTX executes.
#[must_use]
pub fn expected_ntx_scripts(mut self, scripts: Vec<NoteScript>) -> Self {
self.expected_ntx_scripts = scripts;
self
}
// STANDARDIZED REQUESTS
// --------------------------------------------------------------------------------------------
/// Consumes the builder and returns a [`TransactionRequest`] for a transaction to consume the
/// specified notes.
///
/// - `notes` is a list of notes to be consumed.
pub fn build_consume_notes(
self,
notes: Vec<Note>,
) -> Result<TransactionRequest, TransactionRequestError> {
let input_notes = notes.into_iter().map(|id| (id, None));
self.input_notes(input_notes).build()
}
/// Consumes the builder and returns a [`TransactionRequest`] for a transaction to mint fungible
/// assets. This request must be executed against a fungible faucet account.
///
/// - `asset` is the fungible asset to be minted.
/// - `target_id` is the account ID of the account to receive the minted asset.
/// - `note_type` determines the visibility of the note to be created.
/// - `rng` is the random number generator used to generate the serial number for the created
/// note.
///
/// This function cannot be used with a previously set custom script.
pub fn build_mint_fungible_asset(
self,
asset: FungibleAsset,
target_id: AccountId,
note_type: NoteType,
rng: &mut ClientRng,
) -> Result<TransactionRequest, TransactionRequestError> {
let created_note = P2idNote::create(
asset.faucet_id(),
target_id,
vec![asset.into()],
note_type,
NoteAttachment::default(),
rng,
)?;
self.own_output_notes(vec![created_note]).build()
}
/// Consumes the builder and returns a [`TransactionRequest`] for a transaction to send a P2ID
/// or P2IDE note. This request must be executed against the wallet sender account.
///
/// - `payment_data` is the data for the payment transaction that contains the asset to be
/// transferred, the sender account ID, and the target account ID. If the recall or timelock
/// heights are set, a P2IDE note will be created; otherwise, a P2ID note will be created.
/// - `note_type` determines the visibility of the note to be created.
/// - `rng` is the random number generator used to generate the serial number for the created
/// note.
///
/// This function cannot be used with a previously set custom script.
pub fn build_pay_to_id(
self,
payment_data: PaymentNoteDescription,
note_type: NoteType,
rng: &mut ClientRng,
) -> Result<TransactionRequest, TransactionRequestError> {
if payment_data
.assets()
.iter()
.all(|asset| asset.is_fungible() && asset.unwrap_fungible().amount() == 0)
{
return Err(TransactionRequestError::P2IDNoteWithoutAsset);
}
let created_note = payment_data.into_note(note_type, rng)?;
self.own_output_notes(vec![created_note]).build()
}
/// Consumes the builder and returns a [`TransactionRequest`] for a transaction to send a SWAP
/// note. This request must be executed against the wallet sender account.
///
/// - `swap_data` is the data for the swap transaction that contains the sender account ID, the
/// offered asset, and the requested asset.
/// - `note_type` determines the visibility of the note to be created.
/// - `payback_note_type` determines the visibility of the payback note.
/// - `rng` is the random number generator used to generate the serial number for the created
/// note.
///
/// This function cannot be used with a previously set custom script.
pub fn build_swap(
self,
swap_data: &SwapTransactionData,
note_type: NoteType,
payback_note_type: NoteType,
rng: &mut ClientRng,
) -> Result<TransactionRequest, TransactionRequestError> {
// The created note is the one that we need as the output of the tx, the other one is the
// one that we expect to receive and consume eventually.
let (created_note, payback_note_details) = SwapNote::create(
swap_data.account_id(),
swap_data.offered_asset(),
swap_data.requested_asset(),
note_type,
NoteAttachment::default(),
payback_note_type,
NoteAttachment::default(),
rng,
)?;
let payback_tag = NoteTag::with_account_target(swap_data.account_id());
self.expected_future_notes(vec![(payback_note_details, payback_tag)])
.own_output_notes(vec![created_note])
.build()
}
/// Consumes the builder and returns a [`TransactionRequest`] for a transaction that registers
/// note scripts in the node's script registry.
///
/// This creates one public output note per script, each with empty assets and storage. The
/// node indexes the script of every public note it processes, so submitting this transaction
/// makes the scripts available for future network transactions (NTX).
///
/// - `sender_account_id` is the account executing the transaction.
/// - `scripts` is the list of note scripts to register.
/// - `rng` is used to generate serial numbers for the registration notes.
///
/// This function cannot be used with a previously set custom script.
pub fn build_register_note_scripts(
self,
sender_account_id: AccountId,
scripts: Vec<NoteScript>,
rng: &mut ClientRng,
) -> Result<TransactionRequest, TransactionRequestError> {
let registration_notes: Vec<Note> = scripts
.into_iter()
.map(|script| {
let serial_num = rng.draw_word();
let note_storage = NoteStorage::new(vec![])?;
let recipient = NoteRecipient::new(serial_num, script, note_storage);
let note_assets = NoteAssets::new(vec![])?;
let metadata = NoteMetadata::new(sender_account_id, NoteType::Public);
Ok(Note::new(note_assets, metadata, recipient))
})
.collect::<Result<_, NoteError>>()?;
self.own_output_notes(registration_notes).build()
}
// FINALIZE BUILDER
// --------------------------------------------------------------------------------------------
/// Consumes the builder and returns a [`TransactionRequest`].
///
/// # Errors
/// - If both a custom script and own output notes are set.
/// - If an expiration delta is set when a custom script is set.
/// - If an invalid note variant is encountered in the own output notes.
pub fn build(self) -> Result<TransactionRequest, TransactionRequestError> {
let mut seen_input_notes = BTreeSet::new();
for (note_id, _) in &self.input_notes_args {
if !seen_input_notes.insert(note_id) {
return Err(TransactionRequestError::DuplicateInputNote(*note_id));
}
}
let script_template = match (self.custom_script, self.own_output_notes.is_empty()) {
(Some(_), false) => {
return Err(TransactionRequestError::ScriptTemplateError(
"Cannot set both a custom script and own output notes".to_string(),
));
},
(Some(script), true) => {
if self.expiration_delta.is_some() {
return Err(TransactionRequestError::ScriptTemplateError(
"Cannot set expiration delta when a custom script is set".to_string(),
));
}
Some(TransactionScriptTemplate::CustomScript(script))
},
(None, false) => {
let partial_notes: Vec<PartialNote> =
self.own_output_notes.into_iter().map(Into::into).collect();
Some(TransactionScriptTemplate::SendNotes(partial_notes))
},
(None, true) => None,
};
Ok(TransactionRequest {
input_notes: self.input_notes,
input_notes_args: self.input_notes_args,
script_template,
expected_output_recipients: self.expected_output_recipients,
expected_future_notes: self.expected_future_notes,
advice_map: self.advice_map,
merkle_store: self.merkle_store,
foreign_accounts: self.foreign_accounts,
expiration_delta: self.expiration_delta,
ignore_invalid_input_notes: self.ignore_invalid_input_notes,
script_arg: self.script_arg,
auth_arg: self.auth_arg,
expected_ntx_scripts: self.expected_ntx_scripts,
})
}
}
// PAYMENT NOTE DESCRIPTION
// ================================================================================================
/// Contains information needed to create a payment note.
#[derive(Clone, Debug)]
pub struct PaymentNoteDescription {
/// Assets that are meant to be sent to the target account.
assets: Vec<Asset>,
/// Account ID of the sender account.
sender_account_id: AccountId,
/// Account ID of the receiver account.
target_account_id: AccountId,
/// Optional reclaim height for the P2IDE note. It allows the possibility for the sender to
/// reclaim the assets if the note has not been consumed by the target before this height.
reclaim_height: Option<BlockNumber>,
/// Optional timelock height for the P2IDE note. It allows the possibility to add a timelock to
/// the asset transfer, meaning that the note can only be consumed after this height.
timelock_height: Option<BlockNumber>,
}
impl PaymentNoteDescription {
// CONSTRUCTORS
// --------------------------------------------------------------------------------------------
/// Creates a new [`PaymentNoteDescription`].
pub fn new(
assets: Vec<Asset>,
sender_account_id: AccountId,
target_account_id: AccountId,
) -> PaymentNoteDescription {
PaymentNoteDescription {
assets,
sender_account_id,
target_account_id,
reclaim_height: None,
timelock_height: None,
}
}
/// Modifies the [`PaymentNoteDescription`] to set a reclaim height for payment note.
#[must_use]
pub fn with_reclaim_height(mut self, reclaim_height: BlockNumber) -> PaymentNoteDescription {
self.reclaim_height = Some(reclaim_height);
self
}
/// Modifies the [`PaymentNoteDescription`] to set a timelock height for payment note.
#[must_use]
pub fn with_timelock_height(mut self, timelock_height: BlockNumber) -> PaymentNoteDescription {
self.timelock_height = Some(timelock_height);
self
}
/// Returns the executor [`AccountId`].
pub fn account_id(&self) -> AccountId {
self.sender_account_id
}
/// Returns the target [`AccountId`].
pub fn target_account_id(&self) -> AccountId {
self.target_account_id
}
/// Returns the transaction's list of [`Asset`].
pub fn assets(&self) -> &Vec<Asset> {
&self.assets
}
/// Returns the reclaim height for the P2IDE note, if set.
pub fn reclaim_height(&self) -> Option<BlockNumber> {
self.reclaim_height
}
/// Returns the timelock height for the P2IDE note, if set.
pub fn timelock_height(&self) -> Option<BlockNumber> {
self.timelock_height
}
// CONVERSION
// --------------------------------------------------------------------------------------------
/// Converts the payment transaction data into a [`Note`] based on the specified fields. If the
/// reclaim and timelock heights are not set, a P2ID note is created; otherwise, a P2IDE note is
/// created.
pub(crate) fn into_note(
self,
note_type: NoteType,
rng: &mut ClientRng,
) -> Result<Note, NoteError> {
if self.reclaim_height.is_none() && self.timelock_height.is_none() {
// Create a P2ID note
P2idNote::create(
self.sender_account_id,
self.target_account_id,
self.assets,
note_type,
NoteAttachment::default(),
rng,
)
} else {
// Create a P2IDE note
P2ideNote::create(
self.sender_account_id,
P2ideNoteStorage::new(
self.target_account_id,
self.reclaim_height,
self.timelock_height,
),
self.assets,
note_type,
NoteAttachment::default(),
rng,
)
}
}
}
// SWAP TRANSACTION DATA
// ================================================================================================
/// Contains information related to a swap transaction.
///
/// A swap transaction involves creating a SWAP note, which will carry the offered asset and which,
/// when consumed, will create a payback note that carries the requested asset taken from the
/// consumer account's vault.
#[derive(Clone, Debug)]
pub struct SwapTransactionData {
/// Account ID of the sender account.
sender_account_id: AccountId,
/// Asset that is offered in the swap.
offered_asset: Asset,
/// Asset that is expected in the payback note generated as a result of the swap.
requested_asset: Asset,
}
impl SwapTransactionData {
// CONSTRUCTORS
// --------------------------------------------------------------------------------------------
/// Creates a new [`SwapTransactionData`].
pub fn new(
sender_account_id: AccountId,
offered_asset: Asset,
requested_asset: Asset,
) -> SwapTransactionData {
SwapTransactionData {
sender_account_id,
offered_asset,
requested_asset,
}
}
/// Returns the executor [`AccountId`].
pub fn account_id(&self) -> AccountId {
self.sender_account_id
}
/// Returns the transaction offered [`Asset`].
pub fn offered_asset(&self) -> Asset {
self.offered_asset
}
/// Returns the transaction requested [`Asset`].
pub fn requested_asset(&self) -> Asset {
self.requested_asset
}
}