miden-testing 0.14.3

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
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
use assert_matches::assert_matches;
use miden_protocol::account::AccountId;
use miden_protocol::asset::{
    Asset,
    AssetVaultKey,
    FungibleAsset,
    NonFungibleAsset,
    NonFungibleAssetDetails,
};
use miden_protocol::errors::protocol::ERR_VAULT_GET_BALANCE_CAN_ONLY_BE_CALLED_ON_FUNGIBLE_ASSET;
use miden_protocol::errors::tx_kernel::{
    ERR_VAULT_FUNGIBLE_ASSET_AMOUNT_LESS_THAN_AMOUNT_TO_WITHDRAW,
    ERR_VAULT_FUNGIBLE_MAX_AMOUNT_EXCEEDED,
    ERR_VAULT_NON_FUNGIBLE_ASSET_ALREADY_EXISTS,
    ERR_VAULT_NON_FUNGIBLE_ASSET_TO_REMOVE_NOT_FOUND,
};
use miden_protocol::errors::{AssetError, AssetVaultError};
use miden_protocol::testing::account_id::{
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1,
    ACCOUNT_ID_PUBLIC_NON_FUNGIBLE_FAUCET,
    ACCOUNT_ID_PUBLIC_NON_FUNGIBLE_FAUCET_1,
};
use miden_protocol::testing::constants::{FUNGIBLE_ASSET_AMOUNT, NON_FUNGIBLE_ASSET_DATA};
use miden_protocol::transaction::memory;
use miden_protocol::{ONE, Word};

use crate::executor::CodeExecutor;
use crate::kernel_tests::tx::ExecutionOutputExt;
use crate::{TransactionContextBuilder, assert_execution_error};

/// Tests that account::get_balance returns the correct amount.
#[tokio::test]
async fn get_balance_returns_correct_amount() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;

    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap();
    let code = format!(
        r#"
        use $kernel::prologue
        use miden::protocol::active_account

        begin
            exec.prologue::prepare_transaction

            push.{prefix}
            push.{suffix}
            exec.active_account::get_balance
            # => [balance]

            # truncate the stack
            swap drop
        end
            "#,
        prefix = faucet_id.prefix().as_felt(),
        suffix = faucet_id.suffix(),
    );

    let exec_output = tx_context.execute_code(&code).await?;

    assert_eq!(
        exec_output.get_stack_element(0).as_canonical_u64(),
        tx_context.account().vault().get_balance(faucet_id).unwrap()
    );

    Ok(())
}

/// Tests that asset_vault::peek_asset returns the correct asset.
#[tokio::test]
async fn peek_asset_returns_correct_asset() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap();
    let asset_key = AssetVaultKey::new_fungible(faucet_id).unwrap();

    let code = format!(
        r#"
        use $kernel::prologue
        use $kernel::memory
        use $kernel::asset_vault

        begin
            exec.prologue::prepare_transaction

            exec.memory::get_account_vault_root_ptr
            push.{ASSET_KEY}
            # => [ASSET_KEY, account_vault_root_ptr]

            # emit an event to fetch the merkle path for the asset since peek_asset does not do
            # that
            emit.event("miden::protocol::account::vault_before_get_asset")
            # => [ASSET_KEY, account_vault_root_ptr]

            exec.asset_vault::peek_asset
            # => [PEEKED_ASSET_VALUE]

            # truncate the stack
            swapw dropw
        end
            "#,
        ASSET_KEY = asset_key.to_word()
    );

    let exec_output = tx_context.execute_code(&code).await?;

    assert_eq!(
        exec_output.get_stack_word(0),
        tx_context.account().vault().get(asset_key).unwrap().to_value_word()
    );

    Ok(())
}

#[tokio::test]
async fn test_get_balance_non_fungible_fails() -> anyhow::Result<()> {
    // Disable lazy loading otherwise the handler will return an error before the transaction kernel
    // can abort, which is what we want to test.
    let tx_context = TransactionContextBuilder::with_existing_mock_account()
        .disable_lazy_loading()
        .build()?;

    let faucet_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_NON_FUNGIBLE_FAUCET).unwrap();
    let code = format!(
        "
        use $kernel::prologue
        use miden::protocol::active_account

        begin
            exec.prologue::prepare_transaction
            push.{prefix} push.{suffix}
            exec.active_account::get_balance
        end
        ",
        prefix = faucet_id.prefix().as_felt(),
        suffix = faucet_id.suffix(),
    );

    let exec_result = tx_context.execute_code(&code).await;

    assert_execution_error!(
        exec_result,
        ERR_VAULT_GET_BALANCE_CAN_ONLY_BE_CALLED_ON_FUNGIBLE_ASSET
    );

    Ok(())
}

#[tokio::test]
async fn test_has_non_fungible_asset() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let non_fungible_asset =
        tx_context.account().vault().assets().find(Asset::is_non_fungible).unwrap();

    let code = format!(
        "
        use $kernel::prologue
        use miden::protocol::active_account

        begin
            exec.prologue::prepare_transaction
            push.{NON_FUNGIBLE_ASSET_KEY}
            exec.active_account::has_non_fungible_asset

            # truncate the stack
            swap drop
        end
        ",
        NON_FUNGIBLE_ASSET_KEY = non_fungible_asset.to_key_word(),
    );

    let exec_output = tx_context.execute_code(&code).await?;

    assert_eq!(exec_output.get_stack_element(0), ONE);

    Ok(())
}

#[tokio::test]
async fn test_add_fungible_asset_success() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let mut account_vault = tx_context.account().vault().clone();
    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap();
    let amount = FungibleAsset::MAX_AMOUNT - FUNGIBLE_ASSET_AMOUNT;
    let add_fungible_asset = FungibleAsset::new(faucet_id, amount)?;

    let code = format!(
        "
        use $kernel::prologue
        use mock::account

        begin
            exec.prologue::prepare_transaction
            push.{FUNGIBLE_ASSET_VALUE}
            push.{FUNGIBLE_ASSET_KEY}
            call.account::add_asset

            # truncate the stack
            swapdw dropw dropw
        end
        ",
        FUNGIBLE_ASSET_KEY = add_fungible_asset.to_key_word(),
        FUNGIBLE_ASSET_VALUE = add_fungible_asset.to_value_word(),
    );

    let exec_output = &tx_context.execute_code(&code).await?;

    assert_eq!(
        exec_output.get_stack_word(0),
        account_vault
            .add_asset(Asset::Fungible(add_fungible_asset))
            .unwrap()
            .to_value_word()
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(memory::NATIVE_ACCT_VAULT_ROOT_PTR),
        account_vault.root()
    );

    Ok(())
}

#[tokio::test]
async fn test_add_non_fungible_asset_fail_overflow() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let mut account_vault = tx_context.account().vault().clone();

    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap();
    let amount = FungibleAsset::MAX_AMOUNT - FUNGIBLE_ASSET_AMOUNT + 1;
    let add_fungible_asset = FungibleAsset::new(faucet_id, amount)?;

    let code = format!(
        "
        use $kernel::prologue
        use mock::account

        begin
            exec.prologue::prepare_transaction
            push.{FUNGIBLE_ASSET_VALUE}
            push.{FUNGIBLE_ASSET_KEY}
            call.account::add_asset
            dropw dropw
        end
        ",
        FUNGIBLE_ASSET_KEY = add_fungible_asset.to_key_word(),
        FUNGIBLE_ASSET_VALUE = add_fungible_asset.to_value_word(),
    );

    let exec_result = tx_context.execute_code(&code).await;

    assert_execution_error!(exec_result, ERR_VAULT_FUNGIBLE_MAX_AMOUNT_EXCEEDED);
    assert!(account_vault.add_asset(Asset::Fungible(add_fungible_asset)).is_err());

    Ok(())
}

#[tokio::test]
async fn test_add_non_fungible_asset_success() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_NON_FUNGIBLE_FAUCET.try_into()?;
    let mut account_vault = tx_context.account().vault().clone();
    let add_non_fungible_asset = Asset::NonFungible(NonFungibleAsset::new(
        &NonFungibleAssetDetails::new(faucet_id, vec![1, 2, 3, 4, 5, 6, 7, 8]).unwrap(),
    )?);

    let code = format!(
        "
        use $kernel::prologue
        use mock::account

        begin
            exec.prologue::prepare_transaction
            push.{NON_FUNGIBLE_ASSET_VALUE}
            push.{NON_FUNGIBLE_ASSET_KEY}
            call.account::add_asset

            # truncate the stack
            swapdw dropw dropw
        end
        ",
        NON_FUNGIBLE_ASSET_KEY = add_non_fungible_asset.to_key_word(),
        NON_FUNGIBLE_ASSET_VALUE = add_non_fungible_asset.to_value_word(),
    );

    let exec_output = &tx_context.execute_code(&code).await?;

    assert_eq!(
        exec_output.get_stack_word(0),
        account_vault.add_asset(add_non_fungible_asset)?.to_value_word()
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(memory::NATIVE_ACCT_VAULT_ROOT_PTR),
        account_vault.root()
    );

    Ok(())
}

#[tokio::test]
async fn test_add_non_fungible_asset_fail_duplicate() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_NON_FUNGIBLE_FAUCET.try_into().unwrap();
    let mut account_vault = tx_context.account().vault().clone();
    let non_fungible_asset_details =
        NonFungibleAssetDetails::new(faucet_id, NON_FUNGIBLE_ASSET_DATA.to_vec()).unwrap();
    let non_fungible_asset =
        Asset::NonFungible(NonFungibleAsset::new(&non_fungible_asset_details).unwrap());

    let code = format!(
        "
        use $kernel::prologue
        use mock::account

        begin
            exec.prologue::prepare_transaction
            push.{NON_FUNGIBLE_ASSET_VALUE}
            push.{NON_FUNGIBLE_ASSET_KEY}
            call.account::add_asset
            dropw dropw
        end
        ",
        NON_FUNGIBLE_ASSET_KEY = non_fungible_asset.to_key_word(),
        NON_FUNGIBLE_ASSET_VALUE = non_fungible_asset.to_value_word(),
    );

    let exec_result = tx_context.execute_code(&code).await;

    assert_execution_error!(exec_result, ERR_VAULT_NON_FUNGIBLE_ASSET_ALREADY_EXISTS);
    assert!(account_vault.add_asset(non_fungible_asset).is_err());

    Ok(())
}

#[tokio::test]
async fn test_remove_fungible_asset_success_no_balance_remaining() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let mut account_vault = tx_context.account().vault().clone();

    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap();
    let amount = FUNGIBLE_ASSET_AMOUNT;
    let remove_fungible_asset = FungibleAsset::new(faucet_id, amount)?;

    let code = format!(
        "
        use $kernel::prologue
        use mock::account

        begin
            exec.prologue::prepare_transaction
            push.{FUNGIBLE_ASSET_VALUE}
            push.{FUNGIBLE_ASSET_KEY}
            call.account::remove_asset

            # truncate the stack
            exec.::miden::core::sys::truncate_stack
        end
        ",
        FUNGIBLE_ASSET_KEY = remove_fungible_asset.to_key_word(),
        FUNGIBLE_ASSET_VALUE = remove_fungible_asset.to_value_word(),
    );

    let exec_output = &tx_context.execute_code(&code).await?;

    let remaining = account_vault
        .remove_asset(Asset::Fungible(remove_fungible_asset))?
        .expect("fungible removal should return remaining asset");
    assert_eq!(exec_output.get_stack_word(0), remaining.to_value_word());

    assert_eq!(
        exec_output.get_kernel_mem_word(memory::NATIVE_ACCT_VAULT_ROOT_PTR),
        account_vault.root()
    );

    Ok(())
}

#[tokio::test]
async fn test_remove_fungible_asset_fail_remove_too_much() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap();
    let amount = FUNGIBLE_ASSET_AMOUNT + 1;
    let remove_fungible_asset = FungibleAsset::new(faucet_id, amount)?;

    let code = format!(
        "
        use $kernel::prologue
        use mock::account

        begin
            exec.prologue::prepare_transaction
            push.{FUNGIBLE_ASSET_VALUE}
            push.{FUNGIBLE_ASSET_KEY}
            call.account::remove_asset
        end
        ",
        FUNGIBLE_ASSET_KEY = remove_fungible_asset.to_key_word(),
        FUNGIBLE_ASSET_VALUE = remove_fungible_asset.to_value_word(),
    );

    let exec_result = tx_context.execute_code(&code).await;

    assert_execution_error!(
        exec_result,
        ERR_VAULT_FUNGIBLE_ASSET_AMOUNT_LESS_THAN_AMOUNT_TO_WITHDRAW
    );

    Ok(())
}

#[tokio::test]
async fn test_remove_fungible_asset_success_balance_remaining() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let mut account_vault = tx_context.account().vault().clone();

    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap();
    let amount = FUNGIBLE_ASSET_AMOUNT - 1;
    let remove_fungible_asset = FungibleAsset::new(faucet_id, amount)?;

    let code = format!(
        "
        use $kernel::prologue
        use mock::account

        begin
            exec.prologue::prepare_transaction
            push.{FUNGIBLE_ASSET_VALUE}
            push.{FUNGIBLE_ASSET_KEY}
            call.account::remove_asset

            # truncate the stack
            exec.::miden::core::sys::truncate_stack
        end
        ",
        FUNGIBLE_ASSET_KEY = remove_fungible_asset.to_key_word(),
        FUNGIBLE_ASSET_VALUE = remove_fungible_asset.to_value_word(),
    );

    let exec_output = &tx_context.execute_code(&code).await?;

    let remaining = account_vault
        .remove_asset(Asset::Fungible(remove_fungible_asset))?
        .expect("fungible removal should return remaining asset");
    assert_eq!(exec_output.get_stack_word(0), remaining.to_value_word());

    assert_eq!(
        exec_output.get_kernel_mem_word(memory::NATIVE_ACCT_VAULT_ROOT_PTR),
        account_vault.root()
    );

    Ok(())
}

#[tokio::test]
async fn test_remove_inexisting_non_fungible_asset_fails() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_NON_FUNGIBLE_FAUCET_1.try_into().unwrap();
    let mut account_vault = tx_context.account().vault().clone();

    let non_fungible_asset_details =
        NonFungibleAssetDetails::new(faucet_id, NON_FUNGIBLE_ASSET_DATA.to_vec()).unwrap();
    let nonfungible = NonFungibleAsset::new(&non_fungible_asset_details).unwrap();
    let non_existent_non_fungible_asset = Asset::NonFungible(nonfungible);

    assert_matches!(
        account_vault.remove_asset(non_existent_non_fungible_asset).unwrap_err(),
        AssetVaultError::NonFungibleAssetNotFound(err_asset) if err_asset == nonfungible,
        "asset must not be in the vault before the test",
    );

    let code = format!(
        "
        use $kernel::prologue
        use mock::account

        begin
            exec.prologue::prepare_transaction
            push.{FUNGIBLE_ASSET_VALUE}
            push.{FUNGIBLE_ASSET_KEY}
            call.account::remove_asset
        end
        ",
        FUNGIBLE_ASSET_KEY = non_existent_non_fungible_asset.to_key_word(),
        FUNGIBLE_ASSET_VALUE = non_existent_non_fungible_asset.to_value_word(),
    );

    let exec_result = tx_context.execute_code(&code).await;

    assert_execution_error!(exec_result, ERR_VAULT_NON_FUNGIBLE_ASSET_TO_REMOVE_NOT_FOUND);
    assert_matches!(
        account_vault.remove_asset(non_existent_non_fungible_asset).unwrap_err(),
        AssetVaultError::NonFungibleAssetNotFound(err_asset) if err_asset == nonfungible,
        "asset should not be in the vault after the test",
    );

    Ok(())
}

#[tokio::test]
async fn test_remove_non_fungible_asset_success() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let faucet_id: AccountId = ACCOUNT_ID_PUBLIC_NON_FUNGIBLE_FAUCET.try_into().unwrap();
    let mut account_vault = tx_context.account().vault().clone();
    let non_fungible_asset_details =
        NonFungibleAssetDetails::new(faucet_id, NON_FUNGIBLE_ASSET_DATA.to_vec()).unwrap();
    let non_fungible_asset =
        Asset::NonFungible(NonFungibleAsset::new(&non_fungible_asset_details).unwrap());

    let code = format!(
        "
        use $kernel::prologue
        use mock::account

        begin
            exec.prologue::prepare_transaction
            push.{FUNGIBLE_ASSET_VALUE}
            push.{FUNGIBLE_ASSET_KEY}
            call.account::remove_asset

            # truncate the stack
            exec.::miden::core::sys::truncate_stack
        end
        ",
        FUNGIBLE_ASSET_KEY = non_fungible_asset.to_key_word(),
        FUNGIBLE_ASSET_VALUE = non_fungible_asset.to_value_word(),
    );

    let exec_output = &tx_context.execute_code(&code).await?;

    assert!(
        account_vault.remove_asset(non_fungible_asset)?.is_none(),
        "non-fungible removal should return None"
    );
    assert_eq!(exec_output.get_stack_word(0), Word::default());

    assert_eq!(
        exec_output.get_kernel_mem_word(memory::NATIVE_ACCT_VAULT_ROOT_PTR),
        account_vault.root()
    );

    Ok(())
}

/// Tests that adding two fungible assets results in the expected value.
#[tokio::test]
async fn test_merge_fungible_asset_success() -> anyhow::Result<()> {
    let asset0 = FungibleAsset::mock(FUNGIBLE_ASSET_AMOUNT);
    let asset1 = FungibleAsset::mock(FungibleAsset::MAX_AMOUNT - FUNGIBLE_ASSET_AMOUNT);
    let merged_asset = asset0.unwrap_fungible().add(asset1.unwrap_fungible())?;

    // Check merging is commutative by checking asset0 + asset1 = asset1 + asset0.
    for (asset_a, asset_b) in [(asset0, asset1), (asset1, asset0)] {
        let code = format!(
            "
        use $kernel::fungible_asset

        begin
            push.{ASSETA}
            push.{ASSETB}
            exec.fungible_asset::merge
            # => [MERGED_ASSET]

            # truncate the stack
            swapw dropw
        end
        ",
            ASSETA = asset_a.to_value_word(),
            ASSETB = asset_b.to_value_word(),
        );

        let exec_output = CodeExecutor::with_default_host().run(&code).await?;

        assert_eq!(exec_output.get_stack_word(0), merged_asset.to_value_word());
    }

    Ok(())
}

/// Tests that adding two fungible assets fails when the added amounts exceed
/// [`FungibleAsset::MAX_AMOUNT`].
#[tokio::test]
async fn test_merge_fungible_asset_fails_when_max_amount_exceeded() -> anyhow::Result<()> {
    let asset0 = FungibleAsset::mock(FUNGIBLE_ASSET_AMOUNT);
    let asset1 = FungibleAsset::mock(FungibleAsset::MAX_AMOUNT + 1 - FUNGIBLE_ASSET_AMOUNT);

    // Check merging fails for both asset0 + asset1 and asset1 + asset0.
    for (asset_a, asset_b) in [(asset0, asset1), (asset1, asset0)] {
        // Sanity check that the Rust implementation errors.
        assert_matches!(
            asset_a.unwrap_fungible().add(asset_b.unwrap_fungible()).unwrap_err(),
            AssetError::FungibleAssetAmountTooBig(_)
        );

        let code = format!(
            "
        use $kernel::fungible_asset

        begin
            push.{ASSETA}
            push.{ASSETB}
            exec.fungible_asset::merge
            # => [MERGED_ASSET]

            # truncate the stack
            swapw dropw
        end
        ",
            ASSETA = asset_a.to_value_word(),
            ASSETB = asset_b.to_value_word(),
        );

        let exec_output = CodeExecutor::with_default_host().run(&code).await;

        assert_execution_error!(exec_output, ERR_VAULT_FUNGIBLE_MAX_AMOUNT_EXCEEDED);
    }

    Ok(())
}

/// Tests that splitting a fungible asset returns the correct remaining amount.
#[rstest::rstest]
#[case::different_amounts(FungibleAsset::mock(FUNGIBLE_ASSET_AMOUNT), FungibleAsset::mock(FUNGIBLE_ASSET_AMOUNT - 1))]
#[case::same_amounts(
    FungibleAsset::mock(FUNGIBLE_ASSET_AMOUNT),
    FungibleAsset::mock(FUNGIBLE_ASSET_AMOUNT)
)]
#[tokio::test]
async fn test_split_fungible_asset_success(
    #[case] asset0: Asset,
    #[case] asset1: Asset,
) -> anyhow::Result<()> {
    let split_asset = asset0.unwrap_fungible().sub(asset1.unwrap_fungible())?;

    let code = format!(
        "
        use $kernel::fungible_asset

        begin
            push.{ASSET0}
            push.{ASSET1}
            exec.fungible_asset::split
            # => [NEW_ASSET_VALUE_0]

            # truncate the stack
            swapw dropw
        end
        ",
        ASSET0 = asset0.to_value_word(),
        ASSET1 = asset1.to_value_word(),
    );

    let exec_output = CodeExecutor::with_default_host().run(&code).await?;

    assert_eq!(exec_output.get_stack_word(0), split_asset.to_value_word());

    Ok(())
}

/// Tests that splitting a fungible asset fails when the amount to withdraw exceeds the balance.
#[tokio::test]
async fn test_split_fungible_asset_fails_when_amount_exceeds_balance() -> anyhow::Result<()> {
    let asset0 = FungibleAsset::mock(FUNGIBLE_ASSET_AMOUNT);
    let asset1 = FungibleAsset::mock(FUNGIBLE_ASSET_AMOUNT + 1);

    // Sanity check that the Rust implementation errors.
    assert_matches!(
        asset0.unwrap_fungible().sub(asset1.unwrap_fungible()).unwrap_err(),
        AssetError::FungibleAssetAmountNotSufficient { .. }
    );

    let code = format!(
        "
        use $kernel::fungible_asset

        begin
            push.{ASSET0}
            push.{ASSET1}
            exec.fungible_asset::split
            # => [SPLIT_ASSET]

            # truncate the stack
            swapw dropw
        end
        ",
        ASSET0 = asset0.to_value_word(),
        ASSET1 = asset1.to_value_word(),
    );

    let exec_output = CodeExecutor::with_default_host().run(&code).await;

    assert_execution_error!(
        exec_output,
        ERR_VAULT_FUNGIBLE_ASSET_AMOUNT_LESS_THAN_AMOUNT_TO_WITHDRAW
    );

    Ok(())
}

/// Tests that merging two different fungible assets fails.
#[tokio::test]
async fn test_merge_different_fungible_assets_fails() -> anyhow::Result<()> {
    // Create two fungible assets from different faucets
    let faucet_id1: AccountId = ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap();
    let faucet_id2: AccountId = ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1.try_into().unwrap();

    let asset0 = FungibleAsset::new(faucet_id1, FUNGIBLE_ASSET_AMOUNT)?;
    let asset1 = FungibleAsset::new(faucet_id2, FUNGIBLE_ASSET_AMOUNT)?;

    // Sanity check that the Rust implementation errors when adding assets from different faucets.
    assert_matches!(
        asset0.add(asset1).unwrap_err(),
        AssetError::FungibleAssetInconsistentVaultKeys { .. }
    );

    Ok(())
}