miden-testing 0.16.0-beta.1

Miden protocol testing tools
Documentation
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
use anyhow::Context;
use miden_protocol::Felt;
use miden_protocol::account::auth::AuthScheme;
use miden_protocol::account::{Account, AccountId, AccountType};
use miden_protocol::asset::{Asset, FungibleAsset, NonFungibleAsset};
use miden_protocol::note::{Note, NoteDetails, NoteId, NoteType};
use miden_protocol::testing::account_id::{
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1,
    AccountIdBuilder,
};
use miden_protocol::transaction::RawOutputNote;
use miden_standards::code_builder::CodeBuilder;
use miden_standards::note::P2idNote;
use miden_testing::{Auth, MockChain};

use crate::prove_and_verify_transaction;

/// Creates a SWAP note from the transaction script and proves and verifies the transaction.
#[tokio::test]
pub async fn prove_send_swap_note() -> anyhow::Result<()> {
    let payback_note_type = NoteType::Private;
    let SwapTestSetup {
        mock_chain,
        mut sender_account,
        offered_asset,
        swap_note,
        ..
    } = setup_swap_test(payback_note_type)?;

    // CREATE SWAP NOTE TX
    // --------------------------------------------------------------------------------------------

    let tx_script_src = &format!(
        "
        use miden::protocol::output_note
        @transaction_script
        pub proc main
            push.{recipient}
            push.{note_type}
            push.{tag}
            call.::miden::standards::note::note_creator::create_note
            movdn.15 dropw dropw dropw drop drop drop

            push.{ASSET_VALUE}
            push.{ASSET_ID}
            call.::miden::standards::wallets::basic::move_asset_to_note
            dropw dropw dropw dropw
        end
        ",
        recipient = swap_note.recipient().digest(),
        note_type = NoteType::Public as u8,
        tag = Felt::from(swap_note.metadata().tag()),
        ASSET_ID = offered_asset.to_id_word(),
        ASSET_VALUE = offered_asset.to_value_word(),
    );

    let tx_script = CodeBuilder::default().compile_tx_script(tx_script_src)?;

    let create_swap_note_tx = mock_chain
        .build_tx_context(sender_account.id(), &[], &[])
        .context("failed to build tx context")?
        .tx_script(tx_script)
        .extend_expected_output_notes(vec![RawOutputNote::Full(swap_note.clone())])
        .build()?
        .execute()
        .await?;

    sender_account
        .apply_patch(create_swap_note_tx.account_patch())
        .context("failed to apply patch")?;

    assert!(
        create_swap_note_tx
            .output_notes()
            .iter()
            .any(|n| n.details_commitment() == swap_note.details_commitment())
    );
    assert_eq!(
        sender_account.vault().assets().count(),
        0,
        "offered asset should no longer be present in vault"
    );

    let swap_output_note = create_swap_note_tx.output_notes().iter().next().unwrap();
    assert_eq!(swap_output_note.assets().iter().next().unwrap(), &offered_asset);
    assert!(prove_and_verify_transaction(create_swap_note_tx).await.is_ok());

    Ok(())
}

/// Creates a SWAP note in the mock chain with a private payback note and consumes it, creating the
/// payback note. The payback note is consumed by the original sender of the SWAP note.
///
/// Both transactions are proven and verified.
#[tokio::test]
async fn consume_swap_note_private_payback_note() -> anyhow::Result<()> {
    let payback_note_type = NoteType::Private;
    let SwapTestSetup {
        mock_chain,
        mut sender_account,
        mut target_account,
        offered_asset,
        requested_asset,
        swap_note,
        payback_note,
    } = setup_swap_test(payback_note_type)?;

    // CONSUME CREATED NOTE
    // --------------------------------------------------------------------------------------------

    let consume_swap_note_tx = mock_chain
        .build_tx_context(target_account.id(), &[swap_note.id()], &[])
        .context("failed to build tx context")?
        .build()?
        .execute()
        .await?;

    target_account
        .apply_patch(consume_swap_note_tx.account_patch())
        .context("failed to apply patch to target account")?;

    let output_payback_note = consume_swap_note_tx.output_notes().iter().next().unwrap().clone();
    assert_eq!(
        output_payback_note.id(),
        NoteId::new(payback_note.commitment(), output_payback_note.metadata())
    );
    assert_eq!(output_payback_note.assets().iter().next().unwrap(), &requested_asset);

    assert!(target_account.vault().assets().count() == 1);
    assert!(target_account.vault().assets().any(|asset| asset == offered_asset));

    // CONSUME PAYBACK P2ID NOTE
    // --------------------------------------------------------------------------------------------

    let full_payback_note = Note::new(
        payback_note.assets().clone(),
        *output_payback_note.metadata().partial_metadata(),
        payback_note.recipient().clone(),
    );

    let consume_payback_tx = mock_chain
        .build_tx_context(sender_account.id(), &[], &[full_payback_note])
        .context("failed to build tx context")?
        .build()?
        .execute()
        .await?;

    sender_account
        .apply_patch(consume_payback_tx.account_patch())
        .context("failed to apply patch to sender account")?;

    assert!(sender_account.vault().assets().any(|asset| asset == requested_asset));

    prove_and_verify_transaction(consume_swap_note_tx)
        .await
        .context("failed to prove/verify consume_swap_note_tx")?;

    prove_and_verify_transaction(consume_payback_tx)
        .await
        .context("failed to prove/verify consume_payback_tx")?;

    Ok(())
}

// Consumes a SWAP note with a public payback without any off-band advice. The executor materializes
// the payback recipient from the creator account ID embedded in SWAP storage and the SWAP's own
// serial number, then registers it with the advice provider via `p2id::prepare_note ->
// note::build_recipient`.
#[tokio::test]
async fn consume_swap_note_public_payback_note_no_advice() -> anyhow::Result<()> {
    let payback_note_type = NoteType::Public;
    let SwapTestSetup {
        mock_chain,
        mut sender_account,
        mut target_account,
        offered_asset,
        requested_asset,
        swap_note,
        payback_note,
    } = setup_swap_test(payback_note_type)?;

    let consume_swap_note_tx = mock_chain
        .build_tx_context(target_account.id(), &[swap_note.id()], &[])
        .context("failed to build tx context")?
        .build()?
        .execute()
        .await?;

    target_account.apply_patch(consume_swap_note_tx.account_patch())?;

    let output_payback_note = consume_swap_note_tx.output_notes().iter().next().unwrap().clone();
    assert_eq!(
        output_payback_note.id(),
        NoteId::new(payback_note.commitment(), output_payback_note.metadata())
    );
    assert_eq!(output_payback_note.assets().iter().next().unwrap(), &requested_asset);

    assert_eq!(target_account.vault().assets().count(), 1);
    assert!(target_account.vault().assets().any(|asset| asset == offered_asset));

    let full_payback_note = Note::new(
        payback_note.assets().clone(),
        *output_payback_note.metadata().partial_metadata(),
        payback_note.recipient().clone(),
    );

    let consume_payback_tx = mock_chain
        .build_tx_context(sender_account.id(), &[], &[full_payback_note])
        .context("failed to build tx context")?
        .build()?
        .execute()
        .await?;

    sender_account.apply_patch(consume_payback_tx.account_patch())?;
    assert!(sender_account.vault().assets().any(|asset| asset == requested_asset));

    Ok(())
}

// Creates a swap note with a public payback note, then consumes it to complete the swap
// The target account receives the offered asset and creates a public payback note for the sender
#[tokio::test]
async fn consume_swap_note_public_payback_note() -> anyhow::Result<()> {
    let payback_note_type = NoteType::Public;
    let SwapTestSetup {
        mock_chain,
        mut sender_account,
        mut target_account,
        offered_asset,
        requested_asset,
        swap_note,
        payback_note,
    } = setup_swap_test(payback_note_type)?;

    // CONSUME CREATED NOTE
    // --------------------------------------------------------------------------------------------

    // When consuming a SWAP note with a public payback note output
    // it is necessary to add the details of the public note to the advice provider
    // via `.extend_expected_output_notes()`
    let payback_p2id_note = Note::from(
        P2idNote::builder()
            .sender(target_account.id())
            .target(sender_account.id())
            .assets(vec![requested_asset])
            .note_type(payback_note_type)
            .serial_number(payback_note.serial_num())
            .build()
            .unwrap(),
    );

    let consume_swap_note_tx = mock_chain
        .build_tx_context(target_account.id(), &[swap_note.id()], &[])
        .context("failed to build tx context")?
        .extend_expected_output_notes(vec![RawOutputNote::Full(payback_p2id_note)])
        .build()?
        .execute()
        .await?;

    target_account.apply_patch(consume_swap_note_tx.account_patch())?;

    let output_payback_note = consume_swap_note_tx.output_notes().iter().next().unwrap().clone();
    assert_eq!(
        output_payback_note.id(),
        NoteId::new(payback_note.commitment(), output_payback_note.metadata())
    );
    assert_eq!(output_payback_note.assets().iter().next().unwrap(), &requested_asset);

    assert!(target_account.vault().assets().count() == 1);
    assert!(target_account.vault().assets().any(|asset| asset == offered_asset));

    // CONSUME PAYBACK P2ID NOTE
    // --------------------------------------------------------------------------------------------

    let full_payback_note = Note::new(
        payback_note.assets().clone(),
        *output_payback_note.metadata().partial_metadata(),
        payback_note.recipient().clone(),
    );

    let consume_payback_tx = mock_chain
        .build_tx_context(sender_account.id(), &[], &[full_payback_note])
        .context("failed to build tx context")?
        .build()?
        .execute()
        .await?;

    sender_account.apply_patch(consume_payback_tx.account_patch())?;

    assert!(sender_account.vault().assets().any(|asset| asset == requested_asset));
    Ok(())
}

/// Tests that a SWAP note offering asset A and requesting asset B can be matched against a SWAP
/// note offering asset B and requesting asset A.
#[tokio::test]
async fn settle_coincidence_of_wants() -> anyhow::Result<()> {
    // Create two different assets for the swap
    let faucet0 = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET)?;
    let faucet1 = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1)?;
    let asset_a = FungibleAsset::new(faucet0, 10_777)?.into();
    let asset_b = FungibleAsset::new(faucet1, 10)?.into();

    let mut builder = MockChain::builder();

    // CREATE ACCOUNT 1: Has asset A, wants asset B
    // --------------------------------------------------------------------------------------------
    let account_1 = builder.add_existing_wallet_with_assets(
        Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        },
        vec![asset_a],
    )?;

    let payback_note_type = NoteType::Private;
    let (swap_note_1, payback_note_1) =
        builder.add_swap_note(account_1.id(), asset_a, asset_b, payback_note_type)?;

    // CREATE ACCOUNT 2: Has asset B, wants asset A
    // --------------------------------------------------------------------------------------------
    let account_2 = builder.add_existing_wallet_with_assets(
        Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        },
        vec![asset_b],
    )?;
    let (swap_note_2, payback_note_2) =
        builder.add_swap_note(account_2.id(), asset_b, asset_a, payback_note_type)?;

    // MATCHER ACCOUNT: Has both assets and will fulfill both swaps
    // --------------------------------------------------------------------------------------------

    // TODO: matcher account should be able to fill both SWAP notes without holding assets A & B
    let matcher_account = builder.add_existing_wallet_with_assets(
        Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        },
        vec![asset_a, asset_b],
    )?;
    // Initial matching account balance should have two assets.
    assert_eq!(matcher_account.vault().assets().count(), 2);

    // EXECUTE SINGLE TRANSACTION TO CONSUME BOTH SWAP NOTES
    // --------------------------------------------------------------------------------------------
    let mock_chain = builder.build()?;
    let settle_tx = mock_chain
        .build_tx_context(matcher_account.id(), &[swap_note_1.id(), swap_note_2.id()], &[])
        .context("failed to build tx context")?
        .build()?
        .execute()
        .await?;

    // VERIFY PAYBACK NOTES WERE CREATED CORRECTLY
    // --------------------------------------------------------------------------------------------
    let output_notes: Vec<_> = settle_tx.output_notes().iter().collect();
    assert_eq!(output_notes.len(), 2);

    // Find payback notes by matching their IDs
    let output_payback_1 = output_notes
        .iter()
        .find(|note| note.id() == NoteId::new(payback_note_1.commitment(), note.metadata()))
        .expect("Payback note 1 not found");
    let output_payback_2 = output_notes
        .iter()
        .find(|note| note.id() == NoteId::new(payback_note_2.commitment(), note.metadata()))
        .expect("Payback note 2 not found");

    // Verify payback note 1 contains exactly the initially requested asset B for account 1
    assert_eq!(output_payback_1.assets().iter().next().unwrap(), &asset_b);

    // Verify payback note 2 contains exactly the initially requested asset A for account 2
    assert_eq!(output_payback_2.assets().iter().next().unwrap(), &asset_a);

    Ok(())
}

struct SwapTestSetup {
    mock_chain: MockChain,
    sender_account: Account,
    target_account: Account,
    offered_asset: Asset,
    requested_asset: Asset,
    swap_note: Note,
    payback_note: NoteDetails,
}

fn setup_swap_test(payback_note_type: NoteType) -> anyhow::Result<SwapTestSetup> {
    let faucet_id = AccountIdBuilder::new()
        .account_type(AccountType::Private)
        .build_with_seed([5; 32]);

    let offered_asset = FungibleAsset::new(faucet_id, 2000)?.into();
    let requested_asset = NonFungibleAsset::mock(&[1, 2, 3, 4]);

    let mut builder = MockChain::builder();
    let sender_account = builder.add_existing_wallet_with_assets(
        Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        },
        vec![offered_asset],
    )?;
    let target_account = builder.add_existing_wallet_with_assets(
        Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        },
        vec![requested_asset],
    )?;

    let (swap_note, payback_note) = builder
        .add_swap_note(sender_account.id(), offered_asset, requested_asset, payback_note_type)
        .unwrap();

    builder.add_output_note(RawOutputNote::Full(swap_note.clone()));
    let mock_chain = builder.build()?;

    Ok(SwapTestSetup {
        mock_chain,
        sender_account,
        target_account,
        offered_asset,
        requested_asset,
        swap_note,
        payback_note,
    })
}