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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;

use miden_processor::advice::AdviceInputs;
use miden_processor::{EMPTY_WORD, ExecutionOutput, Felt};
use miden_protocol::account::component::AccountComponentMetadata;
use miden_protocol::account::{
    Account,
    AccountBuilder,
    AccountComponent,
    AccountHeader,
    AccountId,
    AccountProcedureRoot,
    AccountStorage,
    AccountStorageMode,
    StorageSlot,
};
use miden_protocol::assembly::DefaultSourceManager;
use miden_protocol::asset::{Asset, FungibleAsset, NonFungibleAsset, NonFungibleAssetDetails};
use miden_protocol::errors::tx_kernel::{
    ERR_FOREIGN_ACCOUNT_CONTEXT_AGAINST_NATIVE_ACCOUNT,
    ERR_FOREIGN_ACCOUNT_INVALID_COMMITMENT,
    ERR_FOREIGN_ACCOUNT_MAX_NUMBER_EXCEEDED,
};
use miden_protocol::testing::account_id::{
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1,
    ACCOUNT_ID_PUBLIC_NON_FUNGIBLE_FAUCET,
};
use miden_protocol::testing::storage::STORAGE_LEAVES_2;
use miden_protocol::transaction::memory::{
    ACCOUNT_DATA_LENGTH,
    ACCT_ACTIVE_STORAGE_SLOTS_SECTION_OFFSET,
    ACCT_CODE_COMMITMENT_OFFSET,
    ACCT_ID_AND_NONCE_OFFSET,
    ACCT_NUM_PROCEDURES_OFFSET,
    ACCT_NUM_STORAGE_SLOTS_OFFSET,
    ACCT_PROCEDURES_SECTION_OFFSET,
    ACCT_STORAGE_COMMITMENT_OFFSET,
    ACCT_VAULT_ROOT_OFFSET,
    NATIVE_ACCOUNT_DATA_PTR,
    UPCOMING_FOREIGN_ACCOUNT_PREFIX_PTR,
    UPCOMING_FOREIGN_ACCOUNT_SUFFIX_PTR,
    UPCOMING_FOREIGN_PROCEDURE_PTR,
};
use miden_protocol::{Word, ZERO};
use miden_standards::code_builder::CodeBuilder;
use miden_standards::testing::account_component::MockAccountComponent;
use miden_tx::LocalTransactionProver;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha20Rng;

use crate::kernel_tests::tx::ExecutionOutputExt;
use crate::{Auth, MockChainBuilder, assert_execution_error, assert_transaction_executor_error};

// SIMPLE FPI TESTS
// ================================================================================================

// FOREIGN PROCEDURE INVOCATION TESTS
// ================================================================================================

#[tokio::test]
async fn test_fpi_memory_single_account() -> anyhow::Result<()> {
    // Prepare the test data
    let mock_value_slot0 = AccountStorage::mock_value_slot0();
    let mock_map_slot = AccountStorage::mock_map_slot();
    let foreign_account_code_source = "
        use miden::protocol::active_account

        pub proc get_item_foreign
            # make this foreign procedure unique to make sure that we invoke the procedure of the
            # foreign account, not the native one
            push.1 drop
            exec.active_account::get_item

            # truncate the stack
            movup.6 movup.6 drop drop
        end

        pub proc get_map_item_foreign
            # make this foreign procedure unique to make sure that we invoke the procedure of the
            # foreign account, not the native one
            push.2 drop
            exec.active_account::get_map_item
        end
    ";

    let source_manager = Arc::new(DefaultSourceManager::default());
    let foreign_account_component = AccountComponent::new(
        CodeBuilder::with_source_manager(source_manager.clone())
            .compile_component_code("test::foreign_account", foreign_account_code_source)?,
        vec![mock_value_slot0.clone(), mock_map_slot.clone()],
        AccountComponentMetadata::mock("test::foreign_account"),
    )?;

    let foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(foreign_account_component)
        .build_existing()?;

    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_slots(vec![AccountStorage::mock_map_slot()]))
        .storage_mode(AccountStorageMode::Public)
        .build_existing()?;

    let mut mock_chain =
        MockChainBuilder::with_accounts([native_account.clone(), foreign_account.clone()])?
            .build()?;
    mock_chain.prove_next_block()?;

    let fpi_inputs = mock_chain
        .get_foreign_account_inputs(foreign_account.id())
        .expect("failed to get foreign account inputs");

    let tx_context = mock_chain
        .build_tx_context(native_account.id(), &[], &[])
        .expect("failed to build tx context")
        .foreign_accounts(vec![fpi_inputs])
        .with_source_manager(source_manager)
        .build()?;

    // GET ITEM
    // --------------------------------------------------------------------------------------------
    // Check the correctness of the memory layout after `get_item_foreign` account procedure
    // invocation

    let get_item_foreign_root = foreign_account.code().procedures()[1].mast_root();

    let code = format!(
        r#"
        use miden::core::sys

        use $kernel::prologue
        use miden::protocol::tx

        const MOCK_VALUE_SLOT0 = word("{mock_value_slot0}")

        begin
            exec.prologue::prepare_transaction

            # pad the stack for the `execute_foreign_procedure` execution
            padw padw
            # => [pad(8)]

            # push the slot name of desired storage item
            push.MOCK_VALUE_SLOT0[0..2]

            # get the hash of the `get_item_foreign` procedure of the foreign account
            push.{get_item_foreign_root}

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT,
            #     slot_id_suffix, slot_id_prefix, pad(8)]

            exec.tx::execute_foreign_procedure
            # => [STORAGE_VALUE_1]

            # truncate the stack
            exec.sys::truncate_stack
            end
            "#,
        mock_value_slot0 = mock_value_slot0.name(),
        foreign_prefix = foreign_account.id().prefix().as_felt(),
        foreign_suffix = foreign_account.id().suffix(),
    );

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

    assert_eq!(
        exec_output.get_stack_word(0),
        mock_value_slot0.content().value(),
        "Value at the top of the stack should be equal to [1, 2, 3, 4]",
    );

    foreign_account_data_memory_assertions(&foreign_account, &exec_output);

    // GET MAP ITEM
    // --------------------------------------------------------------------------------------------
    // Check the correctness of the memory layout after `get_map_item` account procedure invocation

    let get_map_item_foreign_root = foreign_account.code().procedures()[2].mast_root();

    let code = format!(
        r#"
        use miden::core::sys

        use $kernel::prologue
        use miden::protocol::tx

        const MOCK_MAP_SLOT = word("{mock_map_slot}")

        begin
            exec.prologue::prepare_transaction

            # pad the stack for the `execute_foreign_procedure` execution
            padw
            # => [pad(4)]

            # push the key of desired storage item
            push.{map_key}

            # push the slot name of the desired storage item
            push.MOCK_MAP_SLOT[0..2]

            # get the hash of the `get_map_item_foreign` account procedure
            push.{get_map_item_foreign_root}

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT,
            #     slot_id_suffix, slot_id_prefix, MAP_KEY, pad(4)]

            exec.tx::execute_foreign_procedure
            # => [MAP_VALUE]

            # truncate the stack
            exec.sys::truncate_stack
        end
        "#,
        mock_map_slot = mock_map_slot.name(),
        foreign_prefix = foreign_account.id().prefix().as_felt(),
        foreign_suffix = foreign_account.id().suffix(),
        map_key = STORAGE_LEAVES_2[0].0,
    );

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

    assert_eq!(
        exec_output.get_stack_word(0),
        STORAGE_LEAVES_2[0].1,
        "Value at the top of the stack should be equal [1, 2, 3, 4]",
    );

    foreign_account_data_memory_assertions(&foreign_account, &exec_output);

    // GET ITEM TWICE
    // --------------------------------------------------------------------------------------------
    // Check the correctness of the memory layout after two consecutive invocations of the
    // `get_item` account procedures. Invoking two foreign procedures from the same account should
    // result in reuse of the loaded account.

    let code = format!(
        r#"
        use miden::core::sys

        use $kernel::prologue
        use miden::protocol::tx

        const MOCK_VALUE_SLOT0 = word("{mock_value_slot0}")

        begin
            exec.prologue::prepare_transaction

            ### Get the storage item at index 0 #####################
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw
            # => [pad(8)]

            # push the slot name of desired storage item
            push.MOCK_VALUE_SLOT0[0..2]

            # get the hash of the `get_item_foreign` procedure of the foreign account
            push.{get_item_foreign_hash}

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT,
            #     slot_id_suffix, slot_id_prefix, pad(8)]

            exec.tx::execute_foreign_procedure dropw
            # => []

            ### Get the storage item at index 0 again ###############
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw
            # => [pad(8)]

            # push the slot name of the desired storage item
            push.MOCK_VALUE_SLOT0[0..2]

            # get the hash of the `get_item_foreign` procedure of the foreign account
            push.{get_item_foreign_hash}

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT,
            #     slot_id_suffix, slot_id_prefix, pad(8)]

            exec.tx::execute_foreign_procedure

            # truncate the stack
            exec.sys::truncate_stack
        end
        "#,
        mock_value_slot0 = mock_value_slot0.name(),
        foreign_prefix = foreign_account.id().prefix().as_felt(),
        foreign_suffix = foreign_account.id().suffix(),
        get_item_foreign_hash = foreign_account.code().procedures()[1].mast_root(),
    );

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

    // Check that the second invocation of the foreign procedure from the same account does not load
    // the account data again: already loaded data should be reused.
    //
    // Native account:    [8192; 16383]  <- initialized during prologue
    // Foreign account:   [16384; 24575] <- initialized during first FPI
    // Next account slot: [24576; 32767] <- should not be initialized
    assert_eq!(
        exec_output.get_kernel_mem_word(NATIVE_ACCOUNT_DATA_PTR + ACCOUNT_DATA_LENGTH as u32 * 2),
        Word::empty(),
        "Memory starting from 24576 should stay uninitialized"
    );
    Ok(())
}

#[tokio::test]
async fn test_fpi_memory_two_accounts() -> anyhow::Result<()> {
    // Prepare the test data
    let mock_value_slot0 = AccountStorage::mock_value_slot0();
    let mock_value_slot1 = AccountStorage::mock_value_slot1();

    let foreign_account_code_source_1 = "
        use miden::protocol::active_account

        pub proc get_item_foreign_1
            # make this foreign procedure unique to make sure that we invoke the procedure of the
            # foreign account, not the native one
            push.1 drop
            exec.active_account::get_item

            # truncate the stack
            movup.6 movup.6 drop drop
        end
    ";
    let foreign_account_code_source_2 = "
        use miden::protocol::active_account

        pub proc get_item_foreign_2
            # make this foreign procedure unique to make sure that we invoke the procedure of the
            # foreign account, not the native one
            push.2 drop
            exec.active_account::get_item

            # truncate the stack
            movup.6 movup.6 drop drop
        end
    ";

    let foreign_account_component_1 = AccountComponent::new(
        CodeBuilder::default()
            .compile_component_code("test::foreign_account_1", foreign_account_code_source_1)?,
        vec![mock_value_slot0.clone()],
        AccountComponentMetadata::mock("test::foreign_account_1"),
    )?;

    let foreign_account_component_2 = AccountComponent::new(
        CodeBuilder::default()
            .compile_component_code("test::foreign_account_2", foreign_account_code_source_2)?,
        vec![mock_value_slot1.clone()],
        AccountComponentMetadata::mock("test::foreign_account_2"),
    )?;

    let foreign_account_1 = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(foreign_account_component_1)
        .build_existing()?;

    let foreign_account_2 = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(foreign_account_component_2)
        .build_existing()?;

    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .storage_mode(AccountStorageMode::Public)
        .build_existing()?;

    let mut mock_chain = MockChainBuilder::with_accounts([
        native_account.clone(),
        foreign_account_1.clone(),
        foreign_account_2.clone(),
    ])?
    .build()?;
    mock_chain.prove_next_block()?;
    let foreign_account_inputs_1 = mock_chain
        .get_foreign_account_inputs(foreign_account_1.id())
        .expect("failed to get foreign account inputs");

    let foreign_account_inputs_2 = mock_chain
        .get_foreign_account_inputs(foreign_account_2.id())
        .expect("failed to get foreign account inputs");

    let tx_context = mock_chain
        .build_tx_context(native_account.id(), &[], &[])?
        .foreign_accounts(vec![foreign_account_inputs_1, foreign_account_inputs_2])
        .build()?;

    // GET ITEM TWICE WITH TWO ACCOUNTS
    // --------------------------------------------------------------------------------------------
    // Check the correctness of the memory layout after two invocations of the `get_item` account
    // procedures separated by the call of this procedure against another foreign account. Invoking
    // two foreign procedures from the same account should result in reuse of the loaded account.

    let code = format!(
        r#"
        use miden::core::sys

        use $kernel::prologue
        use miden::protocol::tx

        const MOCK_VALUE_SLOT0 = word("{mock_value_slot0}")
        const MOCK_VALUE_SLOT1 = word("{mock_value_slot1}")

        begin
            exec.prologue::prepare_transaction

            ### Get the storage item from the first account
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw
            # => [pad(8)]

            # push the slot name of desired storage item
            push.MOCK_VALUE_SLOT0[0..2]

            # get the hash of the `get_item_foreign` procedure of the foreign account
            push.{get_item_foreign_1_hash}

            # push the foreign account ID
            push.{foreign_1_prefix} push.{foreign_1_suffix}
            # => [foreign_account_1_id_suffix, foreign_account_1_id_prefix, FOREIGN_PROC_ROOT,
            #     slot_id_suffix, slot_id_prefix, pad(8)]

            exec.tx::execute_foreign_procedure dropw
            # => []

            ### Get the storage item from the second account
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw
            # => [pad(8)]

            # push the slot name of desired storage item
            push.MOCK_VALUE_SLOT1[0..2]

            # get the hash of the `get_item_foreign_2` procedure of the foreign account 2
            push.{get_item_foreign_2_hash}

            # push the foreign account ID
            push.{foreign_2_prefix} push.{foreign_2_suffix}
            # => [foreign_account_2_id_suffix, foreign_account_2_id_prefix, FOREIGN_PROC_ROOT,
            #     slot_id_suffix, slot_id_prefix, pad(8)]

            exec.tx::execute_foreign_procedure dropw
            # => []

            ### Get the storage item from the first account again
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw
            # => [pad(8)]

            # push the slot name of desired storage item
            push.MOCK_VALUE_SLOT0[0..2]

            # get the hash of the `get_item_foreign_1` procedure of the foreign account 1
            push.{get_item_foreign_1_hash}

            # push the foreign account ID
            push.{foreign_1_prefix} push.{foreign_1_suffix}
            # => [foreign_account_1_id_suffix, foreign_account_1_id_prefix, FOREIGN_PROC_ROOT,
            #     slot_id_suffix, slot_id_prefix, pad(8)]

            exec.tx::execute_foreign_procedure

            # truncate the stack
            exec.sys::truncate_stack
        end
        "#,
        mock_value_slot0 = mock_value_slot0.name(),
        mock_value_slot1 = mock_value_slot1.name(),
        get_item_foreign_1_hash = foreign_account_1.code().procedures()[1].mast_root(),
        get_item_foreign_2_hash = foreign_account_2.code().procedures()[1].mast_root(),
        foreign_1_prefix = foreign_account_1.id().prefix().as_felt(),
        foreign_1_suffix = foreign_account_1.id().suffix(),
        foreign_2_prefix = foreign_account_2.id().prefix().as_felt(),
        foreign_2_suffix = foreign_account_2.id().suffix(),
    );

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

    // Check the correctness of the memory layout after multiple foreign procedure invocations from
    // different foreign accounts
    //
    // Native account:    [8192; 16383]  <- initialized during prologue
    // Foreign account 1: [16384; 24575] <- initialized during first FPI
    // Foreign account 2: [24576; 32767] <- initialized during second FPI
    // Next account slot: [32768; 40959] <- should not be initialized

    // check that the first word of the first foreign account slot is correct
    let header = AccountHeader::from(&foreign_account_1);
    assert_eq!(
        exec_output
            .get_kernel_mem_word(NATIVE_ACCOUNT_DATA_PTR + ACCOUNT_DATA_LENGTH as u32)
            .as_slice(),
        &header.to_elements()[0..4]
    );

    // check that the first word of the second foreign account slot is correct
    let header = AccountHeader::from(&foreign_account_2);
    assert_eq!(
        exec_output
            .get_kernel_mem_word(NATIVE_ACCOUNT_DATA_PTR + ACCOUNT_DATA_LENGTH as u32 * 2)
            .as_slice(),
        &header.to_elements()[0..4]
    );

    // check that the first word of the third foreign account slot was not initialized
    assert_eq!(
        exec_output.get_kernel_mem_word(NATIVE_ACCOUNT_DATA_PTR + ACCOUNT_DATA_LENGTH as u32 * 3),
        Word::empty(),
        "Memory starting from 32768 should stay uninitialized"
    );

    Ok(())
}

/// Test the correctness of the foreign procedure execution.
///
/// It checks the foreign account code loading, providing the mast forest to the executor,
/// construction of the account procedure maps and execution the foreign procedure in order to
/// obtain the data from the foreign account's storage slot.
#[tokio::test]
async fn test_fpi_execute_foreign_procedure() -> anyhow::Result<()> {
    // Prepare the test data
    let mock_value_slot0 = AccountStorage::mock_value_slot0();
    let mock_map_slot = AccountStorage::mock_map_slot();

    let foreign_account_code_source = r#"
        use miden::protocol::active_account
        use miden::core::sys

        #! Gets an item from the active account storage.
        #!
        #! Inputs:  [slot_id_suffix, slot_id_prefix]
        #! Outputs: [VALUE]
        pub proc get_item_foreign
            # make this foreign procedure unique to make sure that we invoke the procedure of the
            # foreign account, not the native one
            push.1 drop
            exec.active_account::get_item

            # truncate the stack
            movup.6 movup.6 drop drop
        end

        #! Gets a map item from the active account storage.
        #!
        #! Inputs:  [slot_id_suffix, slot_id_prefix, KEY]
        #! Outputs: [VALUE]
        pub proc get_map_item_foreign
            # make this foreign procedure unique to make sure that we invoke the procedure of the
            # foreign account, not the native one
            push.2 drop
            exec.active_account::get_map_item
        end

        #! Validates the correctness of the top 16 elements on the stack and returns another 16 
        #! elements to check that outputs are correctly passed back.
        #!
        #! Inputs:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
        #! Outputs: [17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
        pub proc assert_inputs_correctness
            push.[4, 3, 2, 1]     assert_eqw.err="foreign procedure: 0th input word is incorrect"
            push.[8, 7, 6, 5]     assert_eqw.err="foreign procedure: 1st input word is incorrect"
            push.[12, 11, 10, 9]  assert_eqw.err="foreign procedure: 2nd input word is incorrect"
            push.[16, 15, 14, 13] assert_eqw.err="foreign procedure: 3rd input word is incorrect"

            push.[32, 31, 30, 29] push.[28, 27, 26, 25]
            push.[24, 23, 22, 21] push.[20, 19, 18, 17]
            # => [17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, pad(16)]

            # truncate the stack
            exec.sys::truncate_stack
            # => [17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
        end
    "#;

    let source_manager = Arc::new(DefaultSourceManager::default());
    let foreign_account_component = AccountComponent::new(
        CodeBuilder::with_kernel_library(source_manager.clone())
            .compile_component_code("foreign_account", foreign_account_code_source)?,
        vec![mock_value_slot0.clone(), mock_map_slot.clone()],
        AccountComponentMetadata::mock("foreign_account"),
    )?;

    let foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(foreign_account_component.clone())
        .build_existing()?;

    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .storage_mode(AccountStorageMode::Public)
        .build_existing()?;

    let mut mock_chain =
        MockChainBuilder::with_accounts([native_account.clone(), foreign_account.clone()])?
            .build()?;
    mock_chain.prove_next_block()?;

    let code = format!(
        r#"
        use miden::protocol::tx

        const MOCK_VALUE_SLOT0 = word("{mock_value_slot0}")
        const MOCK_MAP_SLOT = word("{mock_map_slot}")

        begin
            # => [pad(16)]

            ### get the storage item ##########################################

            # push the slot name of desired storage item
            push.MOCK_VALUE_SLOT0[0..2]
            # => [slot_id_suffix, slot_id_prefix, pad(16)]

            # get the hash of the `get_item_foreign` account procedure
            procref.::foreign_account::get_item_foreign
            # => [FOREIGN_PROC_ROOT, slot_id_suffix, slot_id_prefix, pad(16)]

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT
            #     slot_id_suffix, slot_id_prefix, pad(16)]]

            exec.tx::execute_foreign_procedure
            # => [STORAGE_VALUE, pad(14)]

            # assert the correctness of the obtained value
            push.{mock_value0} assert_eqw.err="foreign proc returned unexpected value (1)"
            # => [pad(16)]

            ### get the storage map item ######################################

            # push the key of desired storage item
            push.{map_key}

            # push the slot name of the desired storage map
            push.MOCK_MAP_SLOT[0..2]

            # get the hash of the `get_map_item_foreign` account procedure
            procref.::foreign_account::get_map_item_foreign

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT,
            #     slot_id_suffix, slot_id_prefix, MAP_ITEM_KEY, pad(16)]

            exec.tx::execute_foreign_procedure
            # => [MAP_VALUE, pad(18)]

            # assert the correctness of the obtained value
            push.{mock_value0} assert_eqw.err="foreign proc returned unexpected value (2)"
            # => [pad(18)]

            ### assert foreign procedure inputs correctness ###################

            # push the elements from 1 to 16 onto the stack as the inputs of the 
            # `assert_inputs_correctness` account procedure to check that all of them will be
            # provided to the procedure correctly
            push.[16, 15, 14, 13]
            push.[12, 11, 10, 9]
            push.[8, 7, 6, 5]
            push.[4, 3, 2, 1]
            # => [[1, 2, ..., 16], pad(18)]

            # get the hash of the `assert_inputs_correctness` account procedure
            procref.::foreign_account::assert_inputs_correctness
            # => [FOREIGN_PROC_ROOT, [1, 2, ..., 16], pad(16)]

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT,
            #     [1, 2, ..., 16], pad(18)]

            exec.tx::execute_foreign_procedure
            # => [17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, pad(18)]

            # assert the correctness of the foreign procedure outputs
            push.[20, 19, 18, 17] assert_eqw.err="transaction script: 0th output word is incorrect"
            push.[24, 23, 22, 21] assert_eqw.err="transaction script: 0th output word is incorrect"
            push.[28, 27, 26, 25] assert_eqw.err="transaction script: 0th output word is incorrect"
            push.[32, 31, 30, 29] assert_eqw.err="transaction script: 0th output word is incorrect"

            # => [pad(18)]

            # truncate the stack
            drop drop
            # => [pad(16)]
        end
        "#,
        mock_value_slot0 = mock_value_slot0.name(),
        mock_value0 = mock_value_slot0.value(),
        mock_map_slot = mock_map_slot.name(),
        foreign_prefix = foreign_account.id().prefix().as_felt(),
        foreign_suffix = foreign_account.id().suffix(),
        map_key = STORAGE_LEAVES_2[0].0,
    );

    let tx_script = CodeBuilder::with_source_manager(source_manager.clone())
        .with_dynamically_linked_library(foreign_account_component.component_code())?
        .compile_tx_script(code)?;

    let foreign_account_inputs = mock_chain
        .get_foreign_account_inputs(foreign_account.id())
        .expect("failed to get foreign account inputs");

    mock_chain
        .build_tx_context(native_account.id(), &[], &[])
        .expect("failed to build tx context")
        .foreign_accounts([foreign_account_inputs])
        .tx_script(tx_script)
        .with_source_manager(source_manager)
        .build()?
        .execute()
        .await?;

    Ok(())
}

/// Test that a foreign account can get the balance of a fungible asset and check the presence of a
/// non-fungible asset.
#[tokio::test]
async fn foreign_account_can_get_balance_and_presence_of_asset() -> anyhow::Result<()> {
    let fungible_faucet_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1)?;
    let non_fungible_faucet_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_NON_FUNGIBLE_FAUCET)?;

    // Create two different assets.
    let fungible_asset = Asset::Fungible(FungibleAsset::new(fungible_faucet_id, 1)?);
    let non_fungible_asset = Asset::NonFungible(NonFungibleAsset::new(
        &NonFungibleAssetDetails::new(non_fungible_faucet_id, vec![1, 2, 3])?,
    )?);

    let foreign_account_code_source = format!(
        "
        use miden::protocol::active_account

        pub proc get_asset_balance
            # get balance of first asset
            push.{fungible_faucet_id_prefix} push.{fungible_faucet_id_suffix}
            exec.active_account::get_balance
            # => [balance]

            # check presence of non fungible asset
            push.{NON_FUNGIBLE_ASSET_KEY}
            exec.active_account::has_non_fungible_asset
            # => [has_asset, balance]

            # add the balance and the bool
            add
            # => [has_asset_balance]

            # keep only the result on stack
            swap drop
            # => [has_asset_balance]
        end
        ",
        fungible_faucet_id_prefix = fungible_faucet_id.prefix().as_felt(),
        fungible_faucet_id_suffix = fungible_faucet_id.suffix(),
        NON_FUNGIBLE_ASSET_KEY = non_fungible_asset.to_key_word(),
    );

    let source_manager = Arc::new(DefaultSourceManager::default());
    let foreign_account_component = AccountComponent::new(
        CodeBuilder::with_source_manager(source_manager.clone())
            .compile_component_code("foreign_account_code", foreign_account_code_source)?,
        vec![],
        AccountComponentMetadata::mock("foreign_account_code"),
    )?;

    let foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(foreign_account_component.clone())
        .with_assets(vec![fungible_asset, non_fungible_asset])
        .build_existing()?;

    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .storage_mode(AccountStorageMode::Public)
        .build_existing()?;

    let mut mock_chain =
        MockChainBuilder::with_accounts([native_account.clone(), foreign_account.clone()])?
            .build()?;
    mock_chain.prove_next_block()?;

    let code = format!(
        "
        use miden::core::sys

        use miden::protocol::tx

        begin
            # Get the added balance of two assets from foreign account
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw padw push.0.0.0
            # => [pad(15)]

            # get the hash of the `get_asset_balance` procedure
            procref.::foreign_account_code::get_asset_balance

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, pad(15)]

            exec.tx::execute_foreign_procedure
            # => [has_asset_balance]

            # assert that the non fungible asset exists and the fungible asset has balance 1
            push.2 assert_eq.err=\"Total balance should be 2\"
            # => []

            # truncate the stack
            exec.sys::truncate_stack
        end
        ",
        foreign_prefix = foreign_account.id().prefix().as_felt(),
        foreign_suffix = foreign_account.id().suffix(),
    );

    let tx_script = CodeBuilder::with_source_manager(source_manager.clone())
        .with_dynamically_linked_library(foreign_account_component.component_code())?
        .compile_tx_script(code)?;

    let foreign_account_inputs = mock_chain.get_foreign_account_inputs(foreign_account.id())?;

    mock_chain
        .build_tx_context(native_account.id(), &[], &[])?
        .foreign_accounts([foreign_account_inputs])
        .tx_script(tx_script)
        .with_source_manager(source_manager)
        .build()?
        .execute()
        .await?;

    Ok(())
}

/// Test that the `miden::get_initial_balance` procedure works correctly being called from a foreign
/// account.
#[tokio::test]
async fn foreign_account_get_initial_balance() -> anyhow::Result<()> {
    let fungible_faucet_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1)?;
    let fungible_asset = Asset::Fungible(FungibleAsset::new(fungible_faucet_id, 10)?);

    let foreign_account_code_source = format!(
        "
        use miden::protocol::active_account

        pub proc get_initial_balance
            # push the faucet ID on the stack
            push.{fungible_faucet_id_prefix} push.{fungible_faucet_id_suffix}

            # get the initial balance of the asset associated with the provided faucet ID
            exec.active_account::get_balance
            # => [initial_balance]

            # truncate the stack
            swap drop
            # => [initial_balance]
        end
        ",
        fungible_faucet_id_prefix = fungible_faucet_id.prefix().as_felt(),
        fungible_faucet_id_suffix = fungible_faucet_id.suffix(),
    );

    let source_manager = Arc::new(DefaultSourceManager::default());
    let foreign_account_component = AccountComponent::new(
        CodeBuilder::with_source_manager(source_manager.clone())
            .compile_component_code("foreign_account_code", foreign_account_code_source)?,
        vec![],
        AccountComponentMetadata::mock("foreign_account_code"),
    )?;

    let foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(foreign_account_component.clone())
        .with_assets(vec![fungible_asset])
        .build_existing()?;

    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .storage_mode(AccountStorageMode::Public)
        .build_existing()?;

    let mut mock_chain =
        MockChainBuilder::with_accounts([native_account.clone(), foreign_account.clone()])?
            .build()?;
    mock_chain.prove_next_block()?;

    let code = format!(
        "
        use miden::core::sys

        use miden::protocol::tx

        begin
            # Get the initial balance of the fungible asset from the foreign account

            # pad the stack for the `execute_foreign_procedure` execution
            padw padw padw push.0.0.0
            # => [pad(15)]

            # get the hash of the `get_initial_balance` procedure
            procref.::foreign_account_code::get_initial_balance

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, pad(15)]

            exec.tx::execute_foreign_procedure
            # => [init_foreign_balance]

            # assert that the initial balance of the asset in the foreign account equals 10
            push.10 assert_eq.err=\"Initial balance should be 10\"
            # => []

            # truncate the stack
            exec.sys::truncate_stack
        end
        ",
        foreign_prefix = foreign_account.id().prefix().as_felt(),
        foreign_suffix = foreign_account.id().suffix(),
    );

    let tx_script = CodeBuilder::with_source_manager(source_manager.clone())
        .with_dynamically_linked_library(foreign_account_component.component_code())?
        .compile_tx_script(code)?;

    let foreign_account_inputs = mock_chain.get_foreign_account_inputs(foreign_account.id())?;

    mock_chain
        .build_tx_context(native_account.id(), &[], &[])?
        .foreign_accounts([foreign_account_inputs])
        .tx_script(tx_script)
        .with_source_manager(source_manager)
        .build()?
        .execute()
        .await?;

    Ok(())
}

// NESTED FPI TESTS
// ================================================================================================

/// Test the correctness of the cyclic foreign procedure calls.
///
/// It checks that the account data pointers are correctly added and removed from the account data
/// stack.
///
/// The call chain in this test looks like so:
/// `Native -> First FA -> Second FA -> First FA`
#[tokio::test]
async fn test_nested_fpi_cyclic_invocation() -> anyhow::Result<()> {
    // ------ SECOND FOREIGN ACCOUNT ---------------------------------------------------------------
    let mock_value_slot0 = AccountStorage::mock_value_slot0();
    let mock_value_slot1 = AccountStorage::mock_value_slot1();

    let second_foreign_account_code_source = format!(
        r#"
        use miden::protocol::tx
        use miden::protocol::active_account

        use miden::core::sys

        const MOCK_VALUE_SLOT0 = word("{mock_value_slot0}")
        const MOCK_VALUE_SLOT1 = word("{mock_value_slot1}")

        pub proc second_account_foreign_proc
            # get the storage item at value1
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw
            # => [pad(8)]

            # push the index of desired storage item
            push.MOCK_VALUE_SLOT1[0..2]

            # get the hash of the `get_item_foreign` account procedure from the advice stack
            padw adv_loadw

            # push the foreign account ID from the advice stack
            adv_push.2
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT,
            #     slot_id_suffix, slot_id_prefix, pad(8)]

            exec.tx::execute_foreign_procedure
            # => [storage_value]

            # make sure that the resulting value equals 5
            dup push.5 assert_eq.err="value should have been 5"

            # get the first element of the value0 storage slot (it should be 1) and add it to the
            # obtained foreign value.
            push.MOCK_VALUE_SLOT0[0..2] exec.active_account::get_item
            swap.3 drop drop drop
            add

            # assert that the resulting value equals 6
            dup push.6 assert_eq.err="value should have been 6"

            exec.sys::truncate_stack
        end
    "#,
        mock_value_slot0 = mock_value_slot0.name(),
        mock_value_slot1 = mock_value_slot1.name(),
    );

    let source_manager = Arc::new(DefaultSourceManager::default());
    let second_foreign_account_component = AccountComponent::new(
        CodeBuilder::with_kernel_library(source_manager.clone()).compile_component_code(
            "test::second_foreign_account",
            second_foreign_account_code_source,
        )?,
        vec![mock_value_slot0.clone()],
        AccountComponentMetadata::mock("test::second_foreign_account"),
    )?;

    let second_foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(second_foreign_account_component)
        .build_existing()?;

    // ------ FIRST FOREIGN ACCOUNT ---------------------------------------------------------------
    let first_foreign_account_code_source = format!(
        r#"
        use miden::protocol::tx
        use miden::protocol::active_account

        use miden::core::sys

        const MOCK_VALUE_SLOT0 = word("{mock_value_slot0}")

        pub proc first_account_foreign_proc
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw padw push.0.0.0
            # => [pad(15)]

            # get the hash of the `second_account_foreign_proc` account procedure from the advice stack
            padw adv_loadw

            # push the ID of the second foreign account from the advice stack
            adv_push.2
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, storage_item_index, pad(14)]

            exec.tx::execute_foreign_procedure
            # => [storage_value]

            # get the second element of the value0 storage slot (it should be 2) and add it to the
            # obtained foreign value.
            push.MOCK_VALUE_SLOT0[0..2] exec.active_account::get_item
            drop swap.2 drop drop
            add

            # assert that the resulting value equals 8
            dup push.8 assert_eq.err="value should have been 8"

            exec.sys::truncate_stack
        end

        pub proc get_item_foreign
            # make this foreign procedure unique to make sure that we invoke the procedure of the
            # foreign account, not the native one
            push.1 drop
            exec.active_account::get_item

            # return the first element of the resulting word
            swap.3 drop drop drop
        end
    "#,
        mock_value_slot0 = mock_value_slot0.name(),
    );

    let first_foreign_account_component = AccountComponent::new(
        CodeBuilder::with_kernel_library(source_manager.clone())
            .compile_component_code("first_foreign_account", first_foreign_account_code_source)?,
        vec![mock_value_slot0.clone(), mock_value_slot1.clone()],
        AccountComponentMetadata::mock("first_foreign_account"),
    )?;

    let first_foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(first_foreign_account_component.clone())
        .build_existing()?;

    // ------ NATIVE ACCOUNT ---------------------------------------------------------------
    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .storage_mode(AccountStorageMode::Public)
        .build_existing()?;

    let mut mock_chain = MockChainBuilder::with_accounts([
        native_account.clone(),
        first_foreign_account.clone(),
        second_foreign_account.clone(),
    ])?
    .build()?;
    mock_chain.prove_next_block()?;
    let foreign_account_inputs = vec![
        mock_chain
            .get_foreign_account_inputs(first_foreign_account.id())
            .expect("failed to get foreign account inputs"),
        mock_chain
            .get_foreign_account_inputs(second_foreign_account.id())
            .expect("failed to get foreign account inputs"),
    ];

    // push the hashes of the foreign procedures and account IDs to the advice stack to be able to
    // call them dynamically.
    let mut advice_inputs = AdviceInputs::default();
    advice_inputs
        .stack
        .extend(*second_foreign_account.code().procedures()[1].mast_root());
    advice_inputs.stack.extend([
        second_foreign_account.id().prefix().as_felt(),
        second_foreign_account.id().suffix(),
    ]);

    advice_inputs
        .stack
        .extend(*first_foreign_account.code().procedures()[2].mast_root());
    advice_inputs.stack.extend([
        first_foreign_account.id().prefix().as_felt(),
        first_foreign_account.id().suffix(),
    ]);

    let code = format!(
        r#"
        use miden::core::sys
        use miden::protocol::tx

        begin
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw padw push.0.0.0
            # => [pad(15)]

            # get the hash of the `first_account_foreign_proc` procedure
            procref.::first_foreign_account::first_account_foreign_proc

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, storage_item_index, pad(14)]

            exec.tx::execute_foreign_procedure
            # => [storage_value]

            # add 10 to the returning value
            add.10

            # assert that the resulting value equals 18
            push.18 assert_eq.err="sum should be 18"
            # => []

            exec.sys::truncate_stack
        end
        "#,
        foreign_prefix = first_foreign_account.id().prefix().as_felt(),
        foreign_suffix = first_foreign_account.id().suffix(),
    );

    let tx_script = CodeBuilder::with_source_manager(source_manager.clone())
        .with_dynamically_linked_library(first_foreign_account_component.component_code())?
        .compile_tx_script(code)?;

    mock_chain
        .build_tx_context(native_account.id(), &[], &[])
        .expect("failed to build tx context")
        .foreign_accounts(foreign_account_inputs)
        .extend_advice_inputs(advice_inputs)
        .tx_script(tx_script)
        .with_source_manager(source_manager)
        .build()?
        .execute()
        .await?;

    Ok(())
}

/// Proves a transaction that uses FPI with two foreign accounts.
///
/// Call chain:
/// `Native -> First FA -> Second FA`
///
/// Each foreign account has unique code. The first foreign account calls a procedure on the second
/// foreign account via FPI. We then prove the executed transaction to ensure code for multiple
/// foreign accounts is correctly loaded into the prover host's MAST store.
#[tokio::test]
async fn test_prove_fpi_two_foreign_accounts_chain() -> anyhow::Result<()> {
    // ------ SECOND FOREIGN ACCOUNT ---------------------------------------------------------------
    // unique procedure which just leaves a constant on the stack
    let second_foreign_account_code_source = r#"
        use miden::core::sys

        pub proc second_account_foreign_proc
            # leave a constant result on the stack
            push.3

            # truncate any padding
            exec.sys::truncate_stack
        end
    "#;

    let source_manager = Arc::new(DefaultSourceManager::default());
    let second_foreign_account_component = AccountComponent::new(
        CodeBuilder::with_kernel_library(source_manager.clone())
            .compile_component_code("foreign_account", second_foreign_account_code_source)?,
        vec![],
        AccountComponentMetadata::mock("foreign_account"),
    )?;

    let second_foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(second_foreign_account_component.clone())
        .build_existing()?;

    // ------ FIRST FOREIGN ACCOUNT ---------------------------------------------------------------
    // unique procedure which calls the second foreign account via FPI and then returns
    let first_foreign_account_code_source = format!(
        r#"
        use miden::protocol::tx
        use miden::core::sys

        pub proc first_account_foreign_proc
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw padw push.0.0.0
            # => [pad(15)]

            # get the hash of the `second_account_foreign_proc` using procref
            procref.::foreign_account::second_account_foreign_proc

            # push the ID of the second foreign account
            push.{second_foreign_prefix} push.{second_foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, pad(15)]

            # call the second foreign account
            exec.tx::execute_foreign_procedure
            # => [result_from_second]

            # keep the result and drop any padding if present
            exec.sys::truncate_stack
        end
        "#,
        second_foreign_prefix = second_foreign_account.id().prefix().as_felt(),
        second_foreign_suffix = second_foreign_account.id().suffix(),
    );

    // Link against the second foreign account.
    let first_foreign_account_code = CodeBuilder::with_kernel_library(source_manager.clone())
        .with_dynamically_linked_library(second_foreign_account_component.component_code())?
        .compile_component_code("first_foreign_account", first_foreign_account_code_source)?;
    let first_foreign_account_component = AccountComponent::new(
        first_foreign_account_code,
        vec![],
        AccountComponentMetadata::mock("first_foreign_account"),
    )?;

    let first_foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(first_foreign_account_component.clone())
        .build_existing()?;

    // ------ NATIVE ACCOUNT ---------------------------------------------------------------
    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .storage_mode(AccountStorageMode::Public)
        .build_existing()?;

    let mut mock_chain = MockChainBuilder::with_accounts([
        native_account.clone(),
        first_foreign_account.clone(),
        second_foreign_account.clone(),
    ])?
    .build()?;
    mock_chain.prove_next_block()?;

    let foreign_account_inputs = vec![
        mock_chain
            .get_foreign_account_inputs(first_foreign_account.id())
            .expect("failed to get foreign account inputs"),
        mock_chain
            .get_foreign_account_inputs(second_foreign_account.id())
            .expect("failed to get foreign account inputs"),
    ];

    // ------ TRANSACTION SCRIPT (Native) ----------------------------------------------------------
    // Call the first foreign account's procedure. It will call into the second FA via FPI.
    let code = format!(
        r#"
        use miden::core::sys
        use miden::protocol::tx

        begin
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw padw push.0.0.0
            # => [pad(15)]

            # get the hash of the `first_account_foreign_proc` procedure
            procref.::first_foreign_account::first_account_foreign_proc

            # push the first foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, pad(15)]

            exec.tx::execute_foreign_procedure
            # => [result_from_second]

            # assert the result returned from the second FA is 3
            dup push.3 assert_eq.err="result from second foreign account should be 3"

            # truncate any remaining stack items
            exec.sys::truncate_stack
        end
        "#,
        foreign_prefix = first_foreign_account.id().prefix().as_felt(),
        foreign_suffix = first_foreign_account.id().suffix(),
    );

    let tx_script = CodeBuilder::with_source_manager(source_manager.clone())
        .with_dynamically_linked_library(first_foreign_account_component.component_code())?
        .compile_tx_script(code)?;

    let executed_transaction = mock_chain
        .build_tx_context(native_account.id(), &[], &[])
        .expect("failed to build tx context")
        .foreign_accounts(foreign_account_inputs)
        .tx_script(tx_script)
        .with_source_manager(source_manager)
        .build()?
        .execute()
        .await?;

    // Prove the executed transaction which uses FPI across two foreign accounts.
    LocalTransactionProver::default().prove(executed_transaction).await?;

    Ok(())
}

/// Test that code will panic in attempt to create more than 63 foreign accounts.
///
/// Attempt to create a 64th foreign account first triggers the assert during the account data
/// loading, but we have an additional assert during the account stack push just in case.
#[tokio::test]
async fn test_nested_fpi_stack_overflow() -> anyhow::Result<()> {
    let mut foreign_accounts = Vec::new();
    let mock_value_slot0 = AccountStorage::mock_value_slot0();

    let last_foreign_account_code_source = format!(
        r#"
                use miden::protocol::active_account

                const MOCK_VALUE_SLOT0 = word("{mock_value_slot0}")

                pub proc get_item_foreign
                    # make this foreign procedure unique to make sure that we invoke the procedure
                    # of the foreign account, not the native one
                    push.1 drop

                    # push the index of desired storage item
                    push.MOCK_VALUE_SLOT0[0..2]

                    exec.active_account::get_item

                    # return the first element of the resulting word
                    drop drop drop

                    # make sure that the resulting value equals 1
                    assert.err="expected value to be 1"
                end
        "#,
        mock_value_slot0 = mock_value_slot0.name(),
    );

    let last_foreign_account_code = CodeBuilder::default()
        .compile_component_code("test::last_foreign_account", last_foreign_account_code_source)
        .unwrap();
    let last_foreign_account_component = AccountComponent::new(
        last_foreign_account_code,
        vec![mock_value_slot0.clone()],
        AccountComponentMetadata::mock("test::last_foreign_account"),
    )
    .unwrap();

    let last_foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(last_foreign_account_component)
        .build_existing()
        .unwrap();

    foreign_accounts.push(last_foreign_account);

    for foreign_account_index in 0..63 {
        let next_account = foreign_accounts.last().unwrap();

        let foreign_account_code_source = format!(
                    "
                use miden::protocol::tx
                use miden::core::sys

                pub proc read_first_foreign_storage_slot_{foreign_account_index}
                    # pad the stack for the `execute_foreign_procedure` execution
                    padw padw padw push.0.0.0
                    # => [pad(15)]

                    # get the hash of the `get_item` account procedure
                    push.{next_account_proc_hash}

                    # push the foreign account ID
                    push.{next_foreign_prefix} push.{next_foreign_suffix}
                    # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, storage_item_index, pad(14)]

                    exec.tx::execute_foreign_procedure
                    # => [storage_value]

                    exec.sys::truncate_stack
                end
            ",
                    next_account_proc_hash = next_account.code().procedures()[1].mast_root(),
                    next_foreign_suffix = next_account.id().suffix(),
                    next_foreign_prefix = next_account.id().prefix().as_felt(),
                );

        let foreign_account_code = CodeBuilder::default()
            .compile_component_code(
                format!("test::foreign_account_chain_{foreign_account_index}"),
                foreign_account_code_source,
            )
            .unwrap();
        let foreign_account_component = AccountComponent::new(
            foreign_account_code,
            vec![],
            AccountComponentMetadata::mock("test::foreign_account_chain"),
        )
        .unwrap();

        let foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
            .with_auth_component(Auth::IncrNonce)
            .with_component(foreign_account_component)
            .build_existing()
            .unwrap();

        foreign_accounts.push(foreign_account)
    }

    // ------ NATIVE ACCOUNT ---------------------------------------------------------------
    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .storage_mode(AccountStorageMode::Public)
        .build_existing()
        .unwrap();

    let mut mock_chain = MockChainBuilder::with_accounts(
        [vec![native_account.clone()], foreign_accounts.clone()].concat(),
    )
    .unwrap()
    .build()
    .unwrap();

    mock_chain.prove_next_block().unwrap();

    let foreign_accounts: Vec<_> = foreign_accounts
        .iter()
        .map(|acc| {
            mock_chain
                .get_foreign_account_inputs(acc.id())
                .expect("failed to get foreign account inputs")
        })
        .collect();

    let code = format!(
                "
            use miden::core::sys

            use miden::protocol::tx

            begin
                # pad the stack for the `execute_foreign_procedure` execution
                padw padw padw push.0.0.0
                # => [pad(15)]

                # get the hash of the `get_item` account procedure
                push.{foreign_account_proc_hash}

                # push the foreign account ID
                push.{foreign_prefix} push.{foreign_suffix}
                # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, storage_item_index, pad(14)]

                exec.tx::execute_foreign_procedure
                # => [storage_value]

                exec.sys::truncate_stack
            end
            ",
                foreign_account_proc_hash =
                    foreign_accounts.last().unwrap().0.code().procedures()[1].mast_root(),
                foreign_prefix = foreign_accounts.last().unwrap().0.id().prefix().as_felt(),
                foreign_suffix = foreign_accounts.last().unwrap().0.id().suffix(),
            );

    let tx_script = CodeBuilder::default().compile_tx_script(code).unwrap();

    let tx_context = mock_chain
        .build_tx_context(native_account.id(), &[], &[])?
        .foreign_accounts(foreign_accounts)
        .tx_script(tx_script)
        .build()?;

    let result = tx_context.execute().await;

    assert_transaction_executor_error!(result, ERR_FOREIGN_ACCOUNT_MAX_NUMBER_EXCEEDED);
    Ok(())
}

/// Test that code will panic in attempt to call a procedure from the native account.
#[tokio::test]
async fn test_nested_fpi_native_account_invocation() -> anyhow::Result<()> {
    // ------ FIRST FOREIGN ACCOUNT ---------------------------------------------------------------
    let foreign_account_code_source = "
        use miden::protocol::tx

        use miden::core::sys

        pub proc first_account_foreign_proc
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw padw push.0.0.0
            # => [pad(15)]

            # get the hash of the native account procedure from the advice stack
            padw adv_loadw

            # push the ID of the native account from the advice stack
            adv_push.2
            # => [native_account_id_suffix, native_account_id_prefix, NATIVE_PROC_ROOT, pad(15)]

            exec.tx::execute_foreign_procedure
            # => [storage_value]

            exec.sys::truncate_stack
        end
    ";

    let foreign_account_component = AccountComponent::new(
        CodeBuilder::default()
            .compile_component_code("foreign_account", foreign_account_code_source)?,
        vec![],
        AccountComponentMetadata::mock("foreign_account"),
    )?;

    let foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(foreign_account_component.clone())
        .build_existing()?;

    // ------ NATIVE ACCOUNT ---------------------------------------------------------------
    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .storage_mode(AccountStorageMode::Public)
        .build_existing()?;

    let mut mock_chain =
        MockChainBuilder::with_accounts([native_account.clone(), foreign_account.clone()])?
            .build()?;
    mock_chain.prove_next_block().unwrap();

    let code = format!(
        "
        use miden::core::sys

        use miden::protocol::tx

        begin
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw padw push.0.0.0
            # => [pad(15)]

            # get the hash of the `get_item` account procedure
            push.{first_account_foreign_proc_hash}

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, storage_item_index, pad(14)]

            exec.tx::execute_foreign_procedure
            # => [storage_value]

            exec.sys::truncate_stack
        end
        ",
        foreign_prefix = foreign_account.id().prefix().as_felt(),
        foreign_suffix = foreign_account.id().suffix(),
        first_account_foreign_proc_hash = foreign_account.code().procedures()[1].mast_root(),
    );

    let tx_script = CodeBuilder::default()
        .with_dynamically_linked_library(foreign_account_component.component_code())?
        .compile_tx_script(code)?;

    let foreign_account_inputs = mock_chain
        .get_foreign_account_inputs(foreign_account.id())
        .expect("failed to get foreign account inputs");

    // push the hash of the native procedure and native account IDs to the advice stack to be able
    // to call them dynamically.
    let mut advice_inputs = AdviceInputs::default();
    advice_inputs.stack.extend(*native_account.code().procedures()[3].mast_root());
    advice_inputs
        .stack
        .extend([native_account.id().prefix().as_felt(), native_account.id().suffix()]);

    let result = mock_chain
        .build_tx_context(native_account.id(), &[], &[])
        .expect("failed to build tx context")
        .foreign_accounts(vec![foreign_account_inputs])
        .extend_advice_inputs(advice_inputs)
        .tx_script(tx_script)
        .build()?
        .execute()
        .await;

    assert_transaction_executor_error!(result, ERR_FOREIGN_ACCOUNT_CONTEXT_AGAINST_NATIVE_ACCOUNT);
    Ok(())
}

/// Test that providing an account whose commitment does not match the one in the account tree
/// results in an error.
#[tokio::test]
async fn test_fpi_stale_account() -> anyhow::Result<()> {
    // Prepare the test data
    let foreign_account_code_source = "
        use miden::protocol::native_account

        # code is not used in this test
        pub proc set_some_item_foreign
            push.34.1
            exec.native_account::set_item
        end
    ";

    let mock_value_slot0 = AccountStorage::mock_value_slot0();
    let foreign_account_component = AccountComponent::new(
        CodeBuilder::default()
            .compile_component_code("foreign_account_invalid", foreign_account_code_source)?,
        vec![mock_value_slot0.clone()],
        AccountComponentMetadata::mock("foreign_account_invalid"),
    )?;

    let mut foreign_account = AccountBuilder::new([5; 32])
        .with_auth_component(Auth::IncrNonce)
        .with_component(foreign_account_component)
        .build_existing()?;

    let native_account = AccountBuilder::new([4; 32])
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_slots(vec![AccountStorage::mock_map_slot()]))
        .build_existing()?;

    let mut mock_chain =
        MockChainBuilder::with_accounts([native_account.clone(), foreign_account.clone()])?
            .build()?;
    mock_chain.prove_next_block()?;

    // Make the foreign account invalid.
    // --------------------------------------------------------------------------------------------

    // Modify the account's storage to change its storage commitment and in turn the account
    // commitment.
    foreign_account.storage_mut().set_item(
        mock_value_slot0.name(),
        Word::from([Felt::ONE, Felt::ONE, Felt::ONE, Felt::ONE]),
    )?;

    // We pass the modified foreign account with a witness that is valid against the ref block. This
    // means the foreign account's commitment does not match the commitment that the account witness
    // proves inclusion for.
    let (_foreign_account, foreign_account_witness) = mock_chain
        .get_foreign_account_inputs(foreign_account.id())
        .expect("failed to get foreign account inputs");

    // The account tree from which the transaction inputs are fetched here has the state from the
    // original unmodified foreign account. This should result in the foreign account's proof to be
    // invalid for this account tree root.
    let tx_context = mock_chain
        .build_tx_context(native_account, &[], &[])?
        .foreign_accounts(vec![(foreign_account.clone(), foreign_account_witness)])
        .build()?;

    // Attempt to run FPI.
    // --------------------------------------------------------------------------------------------

    let code = format!(
        "
      use miden::core::sys

      use $kernel::prologue
      use miden::protocol::tx

      begin
          exec.prologue::prepare_transaction

          # pad the stack for the `execute_foreign_procedure` execution
          padw padw padw padw
          # => [pad(16)]

          # push some hash onto the stack - for this test it does not matter
          push.[1,2,3,4]
          # => [FOREIGN_PROC_ROOT, pad(16)]

          # push the foreign account ID
          push.{foreign_prefix} push.{foreign_suffix}
          # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, pad(16)]

          exec.tx::execute_foreign_procedure
        end
      ",
        foreign_prefix = foreign_account.id().prefix().as_felt(),
        foreign_suffix = foreign_account.id().suffix(),
    );

    let result = tx_context.execute_code(&code).await.map(|_| ());
    assert_execution_error!(result, ERR_FOREIGN_ACCOUNT_INVALID_COMMITMENT);

    Ok(())
}

/// This test checks that our `miden::get_id` and `miden::get_native_id` procedures return IDs of
/// the current and native account respectively while being called from the foreign account.
#[tokio::test]
async fn test_fpi_get_account_id() -> anyhow::Result<()> {
    let foreign_account_code_source = "
        use miden::protocol::active_account
        use miden::protocol::native_account

        pub proc get_current_and_native_ids
            # get the ID of the current (foreign) account
            exec.active_account::get_id
            # => [acct_id_suffix, acct_id_prefix, pad(16)]

            # get the ID of the native account
            exec.native_account::get_id
            # => [native_acct_id_suffix, native_acct_id_prefix, acct_id_suffix, acct_id_prefix, pad(16)]

            # truncate the stack
            swapw dropw
            # => [native_acct_id_suffix, native_acct_id_prefix, acct_id_suffix, acct_id_prefix, pad(12)]
        end
    ";

    let foreign_account_component = AccountComponent::new(
        CodeBuilder::default()
            .compile_component_code("foreign_account", foreign_account_code_source)?,
        Vec::new(),
        AccountComponentMetadata::mock("foreign_account"),
    )?;

    let foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(foreign_account_component.clone())
        .build_existing()?;

    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .storage_mode(AccountStorageMode::Public)
        .build_existing()?;

    let mut mock_chain =
        MockChainBuilder::with_accounts([native_account.clone(), foreign_account.clone()])?
            .build()?;
    mock_chain.prove_next_block()?;

    let code = format!(
        r#"
        use miden::core::sys

        use miden::protocol::tx
        use miden::protocol::account_id

        begin
            # get the IDs of the foreign and native accounts
            # pad the stack for the `execute_foreign_procedure` execution
            padw padw padw push.0.0.0
            # => [pad(15)]

            # get the hash of the `get_current_and_native_ids` foreign account procedure
            procref.::foreign_account::get_current_and_native_ids

            # push the foreign account ID
            push.{foreign_prefix} push.{foreign_suffix}
            # => [foreign_account_id_suffix, foreign_account_id_prefix, FOREIGN_PROC_ROOT, pad(15)]

            exec.tx::execute_foreign_procedure
            # => [native_acct_id_suffix, native_acct_id_prefix, acct_id_suffix, acct_id_prefix]

            # push the expected native account ID and check that it is equal to the one returned
            # from the FPI
            push.{expected_native_prefix} push.{expected_native_suffix}
            exec.account_id::is_equal
            assert.err="native account ID returned from the FPI is not equal to the expected one"
            # => [acct_id_suffix, acct_id_prefix]

            # push the expected foreign account ID and check that it is equal to the one returned
            # from the FPI
            push.{foreign_prefix} push.{foreign_suffix}
            exec.account_id::is_equal
            assert.err="foreign account ID returned from the FPI is not equal to the expected one"
            # => []

            # truncate the stack
            exec.sys::truncate_stack
        end
        "#,
        foreign_suffix = foreign_account.id().suffix(),
        foreign_prefix = foreign_account.id().prefix().as_felt(),
        expected_native_suffix = native_account.id().suffix(),
        expected_native_prefix = native_account.id().prefix().as_felt(),
    );

    let tx_script = CodeBuilder::default()
        .with_dynamically_linked_library(foreign_account_component.component_code())?
        .compile_tx_script(code)?;

    let foreign_account_inputs = mock_chain
        .get_foreign_account_inputs(foreign_account.id())
        .expect("failed to get foreign account inputs");

    mock_chain
        .build_tx_context(native_account.id(), &[], &[])
        .expect("failed to build tx context")
        .foreign_accounts(vec![foreign_account_inputs])
        .tx_script(tx_script)
        .build()?
        .execute()
        .await?;

    Ok(())
}

/// Test that get_initial_item and get_initial_map_item work correctly with foreign accounts.
#[tokio::test]
async fn test_get_initial_item_and_get_initial_map_item_with_foreign_account() -> anyhow::Result<()>
{
    // Create a native account
    let native_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .storage_mode(AccountStorageMode::Public)
        .build_existing()?;

    let mock_value_slot0 = AccountStorage::mock_value_slot0();
    let mock_map_slot = AccountStorage::mock_map_slot();
    let (map_key, map_value) = STORAGE_LEAVES_2[0];

    // Create foreign procedures that test get_initial_item and get_initial_map_item
    let foreign_account_code_source = format!(
        r#"
        use miden::protocol::active_account
        use miden::core::sys

        const MOCK_VALUE_SLOT0 = word("{mock_value_slot0}")

        pub proc test_get_initial_item
            push.MOCK_VALUE_SLOT0[0..2]
            exec.active_account::get_initial_item
            exec.sys::truncate_stack
        end

        pub proc test_get_initial_map_item
            exec.active_account::get_initial_map_item
            exec.sys::truncate_stack
        end
    "#,
        mock_value_slot0 = mock_value_slot0.name()
    );

    let foreign_account_component = AccountComponent::new(
        CodeBuilder::default()
            .compile_component_code("foreign_account", foreign_account_code_source)?,
        vec![mock_value_slot0.clone(), mock_map_slot.clone()],
        AccountComponentMetadata::mock("foreign_account"),
    )?;

    let foreign_account = AccountBuilder::new(ChaCha20Rng::from_os_rng().random())
        .with_auth_component(Auth::IncrNonce)
        .with_component(foreign_account_component.clone())
        .build_existing()?;

    // Create the mock chain with both accounts
    let mut mock_chain =
        MockChainBuilder::with_accounts([native_account.clone(), foreign_account.clone()])?
            .build()?;
    mock_chain.prove_next_block()?;

    let foreign_account_inputs = mock_chain.get_foreign_account_inputs(foreign_account.id())?;

    let code = format!(
        r#"
        use miden::core::sys
        use miden::protocol::tx

        const MOCK_MAP_SLOT = word("{mock_map_slot}")

        begin
            # Test get_initial_item on foreign account
            padw padw padw push.0.0.0
            # => [pad(15)]
            procref.::foreign_account::test_get_initial_item
            push.{foreign_account_id_prefix} push.{foreign_account_id_suffix}
            exec.tx::execute_foreign_procedure
            push.{expected_value_slot_0}
            assert_eqw.err="foreign account get_initial_item should work"

            # Test get_initial_map_item on foreign account
            padw padw push.0.0
            push.{map_key}
            push.MOCK_MAP_SLOT[0..2]
            procref.::foreign_account::test_get_initial_map_item
            push.{foreign_account_id_prefix} push.{foreign_account_id_suffix}
            exec.tx::execute_foreign_procedure
            push.{map_value}
            assert_eqw.err="foreign account get_initial_map_item should work"

            exec.sys::truncate_stack
        end
        "#,
        mock_map_slot = mock_map_slot.name(),
        foreign_account_id_prefix = foreign_account.id().prefix().as_felt(),
        foreign_account_id_suffix = foreign_account.id().suffix(),
        expected_value_slot_0 = mock_value_slot0.content().value(),
        map_key = &map_key,
        map_value = &map_value,
    );

    let tx_script = CodeBuilder::with_mock_libraries()
        .with_dynamically_linked_library(foreign_account_component.component_code())?
        .compile_tx_script(code)?;

    mock_chain
        .build_tx_context(native_account.id(), &[], &[])?
        .foreign_accounts(vec![foreign_account_inputs])
        .tx_script(tx_script)
        .build()?
        .execute()
        .await?;

    Ok(())
}

// HELPER FUNCTIONS
// ================================================================================================

fn foreign_account_data_memory_assertions(
    foreign_account: &Account,
    exec_output: &ExecutionOutput,
) {
    let foreign_account_data_ptr = NATIVE_ACCOUNT_DATA_PTR + ACCOUNT_DATA_LENGTH as u32;

    // assert that the account ID and procedure root stored in the
    // UPCOMING_FOREIGN_ACCOUNT_{SUFFIX, PREFIX}_PTR and UPCOMING_FOREIGN_PROCEDURE_PTR memory
    // pointers respectively hold the ID and root of the account and procedure which were used
    // during the FPI

    // foreign account ID prefix should be zero after FPI has ended
    assert_eq!(exec_output.get_kernel_mem_element(UPCOMING_FOREIGN_ACCOUNT_PREFIX_PTR), ZERO);

    // foreign account ID suffix should be zero after FPI has ended
    assert_eq!(exec_output.get_kernel_mem_element(UPCOMING_FOREIGN_ACCOUNT_SUFFIX_PTR), ZERO);

    // foreign procedure root should be zero word after FPI has ended
    assert_eq!(exec_output.get_kernel_mem_word(UPCOMING_FOREIGN_PROCEDURE_PTR), EMPTY_WORD);

    // Check that account id and nonce match.
    let header = AccountHeader::from(foreign_account);
    assert_eq!(
        exec_output
            .get_kernel_mem_word(foreign_account_data_ptr + ACCT_ID_AND_NONCE_OFFSET)
            .as_slice(),
        &header.to_elements()[0..4]
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(foreign_account_data_ptr + ACCT_VAULT_ROOT_OFFSET),
        foreign_account.vault().root(),
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(foreign_account_data_ptr + ACCT_STORAGE_COMMITMENT_OFFSET),
        foreign_account.storage().to_commitment(),
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(foreign_account_data_ptr + ACCT_CODE_COMMITMENT_OFFSET),
        foreign_account.code().commitment(),
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(foreign_account_data_ptr + ACCT_NUM_STORAGE_SLOTS_OFFSET),
        Word::from([u16::try_from(foreign_account.storage().slots().len()).unwrap(), 0, 0, 0]),
    );

    for (i, elements) in foreign_account
        .storage()
        .to_elements()
        .chunks(StorageSlot::NUM_ELEMENTS / 2)
        .enumerate()
    {
        assert_eq!(
            exec_output.get_kernel_mem_word(
                foreign_account_data_ptr
                    + ACCT_ACTIVE_STORAGE_SLOTS_SECTION_OFFSET
                    + (i as u32) * 4
            ),
            Word::try_from(elements).unwrap(),
        )
    }

    assert_eq!(
        exec_output.get_kernel_mem_word(foreign_account_data_ptr + ACCT_NUM_PROCEDURES_OFFSET),
        Word::from([u16::try_from(foreign_account.code().num_procedures()).unwrap(), 0, 0, 0]),
    );

    for (i, elements) in foreign_account
        .code()
        .as_elements()
        .chunks(AccountProcedureRoot::NUM_ELEMENTS)
        .enumerate()
    {
        assert_eq!(
            exec_output.get_kernel_mem_word(
                foreign_account_data_ptr + ACCT_PROCEDURES_SECTION_OFFSET + (i as u32) * 4
            ),
            Word::try_from(elements).unwrap(),
        );
    }
}