miden-client-web 0.7.2

Web Client library that facilitates interaction with the Miden rollup
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
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>WASM Example</title>
  </head>
  <body>
    <label for="accountFileInput" class="custom-file-upload">
      Choose Account File
    </label>
    <input type="file" id="accountFileInput" style="display: none" />
    <label for="noteFileInput" class="custom-file-upload">
      Choose Note File
    </label>
    <input type="file" id="noteFileInput" style="display: none" />
    <script type="module" src="./dist/index.js"></script>
    <script type="module">
      // Example of using the exported WebClient in the browser
      import {
        AdviceMap,
        AccountStorageMode,
        AuthSecretKey,
        Felt,
        FeltArray,
        FungibleAsset,
        InputNoteState,
        Note,
        NoteAssets,
        NoteExecutionHint,
        NoteExecutionMode,
        NoteFilter,
        NoteId,
        NoteIdAndArgs,
        NoteIdAndArgsArray,
        NoteInputs,
        NoteMetadata,
        NoteRecipient,
        NoteTag,
        NoteType,
        OutputNote,
        OutputNotesArray,
        Rpo256,
        TransactionRequest,
        TransactionRequestBuilder,
        TransactionScriptInputPair,
        TransactionScriptInputPairArray,
        WebClient,
      } from "./dist/index.js";

      document
        .getElementById("accountFileInput")
        .addEventListener("change", function (event) {
          const file = event.target.files[0];
          if (file) {
            const reader = new FileReader();

            reader.onload = async function (e) {
              let webClient = await createMidenWebClient();
              const arrayBuffer = e.target.result;
              const byteArray = new Uint8Array(arrayBuffer);

              await testImportAccount(webClient, byteArray);
            };

            reader.readAsArrayBuffer(file);
          }
        });

      document
        .getElementById("noteFileInput")
        .addEventListener("change", async function (event) {
          const file = event.target.files[0];
          if (file) {
            const reader = new FileReader();

            reader.onload = async function (e) {
              let webClient = await createMidenWebClient();
              const arrayBuffer = e.target.result;
              const byteArray = new Uint8Array(arrayBuffer);

              await importInputNote(webClient, byteArray, true);
            };

            reader.readAsArrayBuffer(file);
          }
        });

      function setupNoteFileInputListener(webClient) {
        document
          .getElementById("noteFileInput")
          .addEventListener("change", async function (event) {
            const file = event.target.files[0];
            if (file) {
              try {
                const byteArray = await readFileAsByteArray(file);
                console.log(byteArray); // Output the byte array to check the content
                let result = await importInputNote(webClient, byteArray);
                console.log(result); // Log the result of the import process
              } catch (error) {
                console.error("Error handling file:", error);
              }
            }
          });
      }

      async function readFileAsByteArray(file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();

          reader.onload = () => {
            const arrayBuffer = reader.result;
            const byteArray = new Uint8Array(arrayBuffer);
            console.log("Byte array length:", byteArray.length); // Check the length
            resolve(byteArray);
          };

          reader.onerror = () => {
            console.error("File read error:", reader.error);
            reject(reader.error);
          };

          reader.readAsArrayBuffer(file);
        });
      }

      async function createMidenWebClient(dbName = "MidenClientDB", initSeed) {
        try {
          let rpc_url = "http://localhost:57291";
          let envoy_proxy_url = "http://localhost:8080";
          const webClient = new WebClient();
          await webClient.create_client(rpc_url, null, initSeed);
          return webClient;
        } catch (error) {
          console.error("Failed to create client with web store:", error);
        }
      }

      async function testStoreAndRpc(webClient) {
        try {
          await webClient.test_store_and_rpc();
        } catch (error) {
          console.error("Failed to create client with web store:", error);
        }
      }

      // Account Functions
      ///////////////////////////////////////////////////////////////////

      async function createNewWallet(webClient, storageMode, mutable) {
        try {
          let result = await webClient.new_wallet(storageMode, mutable);
          console.log(`Created new wallet account with id ${result}`);
          return result;
        } catch (error) {
          console.error("Failed to call create account:", error);
        }
      }

      async function createNewFaucet(
        webClient,
        storageMode,
        nonFungible,
        tokenSymbol,
        decimals,
        maxSupply
      ) {
        try {
          let result = await webClient.new_faucet(
            storageMode,
            nonFungible,
            tokenSymbol,
            decimals,
            maxSupply
          );
          console.log(`Created new faucet with id ${result}`);
          return result;
        } catch (error) {
          console.error("Failed to call create account:", error);
        }
      }

      async function importAccount(webClient, accountAsBytes) {
        try {
          let result = await webClient.import_account(accountAsBytes);
          console.log(result);
          return result;
        } catch (error) {
          console.error("Failed to call import account:", error);
        }
      }

      async function getAccounts(webClient) {
        try {
          let accounts = await webClient.get_accounts();
          let accountIds = accounts.map((account) => account.id);
          console.log(accountIds);
          return accountIds;
        } catch (error) {
          console.error("Failed to call get accounts:", error);
        }
      }

      async function getAccount(webClient, accountId) {
        try {
          let result = await webClient.get_account(accountId);
          console.log(result);
          return result;
        } catch (error) {
          console.error("Failed to call get account:", error);
        }
      }

      // Transaction Functions
      ///////////////////////////////////////////////////////////////////

      async function createNewMintTransaction(
        webClient,
        targetAccountId,
        faucetId,
        noteType,
        amount
      ) {
        try {
          let result = await webClient.new_mint_transaction(
            targetAccountId,
            faucetId,
            noteType,
            amount
          );
          console.log(
            `Created new mint transaction with id ${result.transaction_id}`
          );
          console.log(`Output notes created: ${result.created_note_ids}`);
          return result;
        } catch (error) {
          console.error("Failed to call create new mint transaction:", error);
        }
      }

      async function createNewConsumeTransaction(
        webClient,
        accountId,
        listOfNotes
      ) {
        try {
          let result = await webClient.new_consume_transaction(
            accountId,
            listOfNotes
          );
          console.log(
            `Created new consume transaction with id ${result.transaction_id}`
          );
          console.log(`Output notes created: ${result.created_note_ids}`);
          return result;
        } catch (error) {
          console.error(
            "Failed to call create new consume transaction:",
            error
          );
        }
      }

      async function createNewSendTransaction(
        webClient,
        senderAccountId,
        targetAccountId,
        facuetId,
        noteType,
        amount,
        recallHeight
      ) {
        try {
          let result = await webClient.new_send_transaction(
            senderAccountId,
            targetAccountId,
            facuetId,
            noteType,
            amount,
            recallHeight
          );
          console.log(
            `Created new send transaction with id ${result.transaction_id}`
          );
          console.log(`Output notes created: ${result.created_note_ids}`);
          return result;
        } catch (error) {
          console.error("Failed to call create new send transaction:", error);
        }
      }

      async function createNewSwapTransaction(
        webClient,
        senderAccountId,
        offeredAssetFaucetId,
        offeredAssetAmount,
        requestedAssetFaucetId,
        requestedAssetAmount,
        noteType
      ) {
        try {
          let result = await webClient.new_swap_transaction(
            senderAccountId,
            offeredAssetFaucetId,
            offeredAssetAmount,
            requestedAssetFaucetId,
            requestedAssetAmount,
            noteType
          );
          console.log(
            `Created new swap transaction with id ${result.transaction_id}`
          );
          console.log(
            `Output notes created: ${result.expected_output_note_ids}`
          );
          console.log(
            `Expected Partial Notes: ${result.expected_partial_note_ids}`
          );
          console.log(`Payback Note Tag: ${result.payback_note_tag}`);
          return result;
        } catch (error) {
          console.error("Failed to call create new swap transaction:", error);
        }
      }

      async function getTransactions(webClient) {
        try {
          let result = await webClient.get_transactions();
          console.log(result);
          return result;
        } catch (error) {
          console.error("Failed to call get transactions:", error);
        }
      }

      // Note Functions
      ///////////////////////////////////////////////////////////////////

      async function getInputNotes(webClient, status = "All") {
        try {
          let result = await webClient.get_input_notes(status);
          console.log(result);
          return result;
        } catch (error) {
          console.error("Failed to call get input notes:", error);
        }
      }

      async function getInputNote(webClient, noteId) {
        try {
          let result = await webClient.get_input_note(noteId);
          console.log(result);
          return result;
        } catch (error) {
          console.error("Failed to call get input note:", error);
        }
      }

      async function getOutputNotes(webClient, status = "All") {
        try {
          let result = await webClient.get_output_notes(status);
          console.log(result);
          return result;
        } catch (error) {
          console.error("Failed to call get output notes:", error);
        }
      }

      async function getOutputNote(webClient, noteId) {
        try {
          let result = await webClient.get_output_note(noteId);
          console.log(result);
          return result;
        } catch (error) {
          console.error("Failed to call get input note:", error);
        }
      }

      async function importInputNote(webClient, noteAsBytes, verify) {
        try {
          await webClient.import_note(noteAsBytes, verify);
        } catch (error) {
          console.error("Failed to call import input note:", error);
        }
      }

      async function exportNote(webClient, noteId) {
        try {
          let result = await webClient.export_note(noteId, "Partial");
          let byteArray = new Uint8Array(result);
          console.log(byteArray);
          return byteArray;
        } catch (error) {
          console.error("Failed to call export input note:", error);
        }
      }

      // Sync Functions
      ///////////////////////////////////////////////////////////////////

      async function syncState(webClient) {
        try {
          let result = await webClient.sync_state();
          console.log("Synced state to block ", result);
        } catch (error) {
          console.error("Failed to call sync state:", error);
        }
      }

      async function addTag(webClient, noteTag) {
        try {
          let result = await webClient.add_tag(noteTag);
          console.log(result);
        } catch (error) {
          console.error("Failed to call add note tag:", error);
        }
      }

      // Tests
      ///////////////////////////////////////////////////////////////////

      // Done
      async function testCreateNewWallet() {
        const initSeed = new Uint8Array([
          223, 198, 73, 130, 93, 79, 220, 107, 25, 181, 91, 235, 101, 105, 136,
          172, 151, 161, 174, 73, 142, 81, 238, 192, 227, 93, 54, 113, 136, 223,
          75, 174,
        ]);

        console.log("testCreateNewWallet started");
        const webClient = await createMidenWebClient("MidenClientDB", initSeed);
        const wallet = await webClient.new_wallet(
          AccountStorageMode.public(),
          true
        );
        console.log("Wallet id: ");
        console.log(wallet.id().to_string());

        console.log("testCreateNewWallet finished");
      }

      // Done
      async function testCreateNewFaucet() {
        console.log("testCreateNewFaucet started");
        let webClient = await createMidenWebClient();

        await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );

        console.log("testCreateNewFaucet finished");
      }

      // Done
      async function testImportAccount(webClient, accountAsBytes) {
        console.log("testImportAccount started");
        await importAccount(webClient, accountAsBytes);
        console.log("testImportAccount finished");
      }

      // Done
      async function testGetAccounts(shouldCreateAccounts = true) {
        console.log("testGetAccounts started");
        let webClient = await createMidenWebClient();
        if (shouldCreateAccounts) {
          await createNewWallet(webClient, "Private", true);
        }

        await getAccounts(webClient);

        console.log("testGetAccounts finished");
      }

      // Done
      async function testGetAccount() {
        console.log("testGetAccount started");

        let webClient = await createMidenWebClient();
        let accountId = await createNewWallet(webClient, "Private", true);

        await getAccount(webClient, accountId.to_string());

        console.log("testGetAccount finished");
      }

      // Done
      async function testNewMintTransaction() {
        console.log("testNewMintTransaction started");

        let webClient = await createMidenWebClient();
        let targetAccount = await createNewWallet(
          webClient,
          AccountStorageMode.private(),
          true
        );
        let faucet = await createNewFaucet(
          webClient,
          AccountStorageMode.private(),
          false,
          "DAG",
          8,
          BigInt(10000000)
        );
        console.log("syncing state...");
        await syncState(webClient);
        console.log("state synced");
        await new Promise((r) => setTimeout(r, 20000));

        await webClient.fetch_and_cache_account_auth_by_pub_key(faucet.id());
        console.log("fetched");
        let result = await createNewMintTransaction(
          webClient,
          targetAccount.id(),
          faucet.id(),
          NoteType.private(),
          BigInt(1000)
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        console.log("testNewMintTransaction finished");
      }

      // Done
      async function testNewConsumeTransaction() {
        console.log("testNewConsumeTransaction started");

        let webClient = await createMidenWebClient();
        let targetAccount = await createNewWallet(
          webClient,
          AccountStorageMode.private(),
          true
        );
        let faucet = await createNewFaucet(
          webClient,
          AccountStorageMode.private(),
          false,
          "DEN",
          10,
          BigInt(1000000)
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(faucet.id());
        let mintTransactionResult = await createNewMintTransaction(
          webClient,
          targetAccount.id(),
          faucet.id(),
          NoteType.private(),
          BigInt(1000)
        );

        let created_notes = mintTransactionResult.created_notes().notes();
        let created_note_ids = created_notes.map((note) =>
          note.id().to_string()
        );

        console.log("waiting on minted notes to get eaten by the rpc...");
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          targetAccount.id()
        );
        let consumeTransactionResult = await createNewConsumeTransaction(
          webClient,
          targetAccount.id(),
          created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        console.log("testNewConsumeTransaction finished");
      }

      // Done
      async function testNewSendTransaction() {
        console.log("testNewSendTransaction started");

        let webClient = await createMidenWebClient();
        let senderAccountId = await createNewWallet(webClient, "Private", true);
        let targetAccountId = await createNewWallet(webClient, "Private", true);
        let faucetId = await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );
        await syncState(webClient);
        await new Promise((r) => setTimeout(r, 20000));

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          faucetId.to_string()
        );
        let mintTransactionResult = await createNewMintTransaction(
          webClient,
          senderAccountId.to_string(),
          faucetId.to_string(),
          "Private",
          "1000"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          senderAccountId.to_string()
        );
        let consumeTransactionResult = await createNewConsumeTransaction(
          webClient,
          senderAccountId.to_string(),
          mintTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          senderAccountId.to_string()
        );
        let sendTransactionResult = await createNewSendTransaction(
          webClient,
          senderAccountId.to_string(),
          targetAccountId.to_string(),
          faucetId.to_string(),
          "Private",
          "500",
          null
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          targetAccountId.to_string()
        );
        let consumeSendTransactionResult = await createNewConsumeTransaction(
          webClient,
          targetAccountId.to_string(),
          sendTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        console.log("testNewSendTransaction finished");
      }

      // Done
      async function testNewSendTransactionWithRecallHeight() {
        console.log("testNewSendTransactionWithRecallHeight started");

        let webClient = await createMidenWebClient();
        let senderAccountId = await createNewWallet(webClient, "Private", true);
        let targetAccountId = await createNewWallet(webClient, "Private", true);
        let faucetId = await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );
        await syncState(webClient);
        await new Promise((r) => setTimeout(r, 20000));

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          faucetId.to_string()
        );
        let mintTransactionResult = await createNewMintTransaction(
          webClient,
          senderAccountId.to_string(),
          faucetId.to_string(),
          "Private",
          "1000"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          senderAccountId.to_string()
        );
        let consumeTransactionResult = await createNewConsumeTransaction(
          webClient,
          senderAccountId.to_string(),
          mintTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          senderAccountId.to_string()
        );
        let sendTransactionResult = await createNewSendTransaction(
          webClient,
          senderAccountId.to_string(),
          targetAccountId.to_string(),
          faucetId.to_string(),
          "Private",
          "500",
          "0"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          senderAccountId.to_string()
        );
        let consumeSendTransactionResult = await createNewConsumeTransaction(
          webClient,
          senderAccountId.to_string(),
          sendTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        console.log("testNewSendTransactionWithRecallHeight finished");
      }

      // Done
      async function testNewSwapTransaction() {
        console.log("testNewSwapTransaction started");
        let webClient = await createMidenWebClient();

        let walletAAccountId = await createNewWallet(
          webClient,
          "Private",
          true
        );
        let walletBAccountId = await createNewWallet(
          webClient,
          "Private",
          true
        );
        let offeredAssetFaucetId = await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );
        let requestedAssetFaucetId = await createNewFaucet(
          webClient,
          "Private",
          false,
          "GAR",
          "10",
          "1000000"
        );
        await syncState(webClient);
        await new Promise((r) => setTimeout(r, 20000));

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          offeredAssetFaucetId.to_string()
        );
        let walletAMintTransactionResult = await createNewMintTransaction(
          webClient,
          walletAAccountId.to_string(),
          offeredAssetFaucetId.to_string(),
          "Public",
          "1000"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          requestedAssetFaucetId.to_string()
        );
        let walletBMintTransactionResult = await createNewMintTransaction(
          webClient,
          walletBAccountId.to_string(),
          requestedAssetFaucetId.to_string(),
          "Public",
          "1000"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          walletAAccountId.to_string()
        );
        let walletAConsumeTransactionResult = await createNewConsumeTransaction(
          webClient,
          walletAAccountId.to_string(),
          walletAMintTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          walletBAccountId.to_string()
        );
        let walletBConsumeTransactionResult = await createNewConsumeTransaction(
          webClient,
          walletBAccountId.to_string(),
          walletBMintTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          walletAAccountId.to_string()
        );
        let swapTransactionResult = await createNewSwapTransaction(
          webClient,
          walletAAccountId.to_string(),
          offeredAssetFaucetId.to_string(),
          "100",
          requestedAssetFaucetId.to_string(),
          "900",
          "Public"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await addTag(webClient, swapTransactionResult.payback_note_tag);
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          walletBAccountId.to_string()
        );
        let walletBConsumeSwapTransactionResult =
          await createNewConsumeTransaction(
            webClient,
            walletBAccountId.to_string(),
            swapTransactionResult.expected_output_note_ids // TODO CHANGE ME
          );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          walletAAccountId.to_string()
        );
        let walletAConsumeSwapTransactionResult =
          await createNewConsumeTransaction(
            webClient,
            walletAAccountId.to_string(),
            swapTransactionResult.expected_partial_note_ids // TODO CHANGE ME
          );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        console.log("testNewSwapTransaction finished");
      }

      // Done
      async function testGetTransactions() {
        console.log("testGetTransactions started");

        let webClient = await createMidenWebClient();
        let walletAccount = await createNewWallet(webClient, "Private", true);
        let faucetAccount = await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );
        await syncState(webClient);
        await new Promise((r) => setTimeout(r, 20000));

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          faucetAccount.to_string()
        );

        let mintTransactionResult = await createNewMintTransaction(
          webClient,
          walletAccount.to_string(),
          faucetAccount.to_string(),
          "Private",
          "1000"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          walletAccount.to_string()
        );

        let consumeTransactionResult = await createNewConsumeTransaction(
          webClient,
          walletAccount.to_string(),
          mintTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await getTransactions(webClient);

        console.log("testGetTransactions finished");
      }

      // Done
      async function testGetInputNotes() {
        console.log("testGetInputNotes started");

        let webClient = await createMidenWebClient();
        let targetAccountId = await createNewWallet(webClient, "Private", true);
        let faucetId = await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );
        await syncState(webClient);
        await new Promise((r) => setTimeout(r, 20000));

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          faucetId.to_string()
        );

        let mintTransactionResult = await createNewMintTransaction(
          webClient,
          targetAccountId.to_string(),
          faucetId.to_string(),
          "Private",
          "1000"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          targetAccountId.to_string()
        );

        let consumeTransactionResult = await createNewConsumeTransaction(
          webClient,
          targetAccountId.to_string(),
          mintTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await getInputNotes(webClient);

        console.log("testGetInputNotes finished");
      }

      // Done
      async function testGetInputNote() {
        console.log("testGetInputNote started");

        let webClient = await createMidenWebClient();
        let targetAccountId = await createNewWallet(webClient, "Private", true);
        let faucetId = await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );
        await syncState(webClient);
        await new Promise((r) => setTimeout(r, 20000));

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          faucetId.to_string()
        );

        let mintTransactionResult = await createNewMintTransaction(
          webClient,
          targetAccountId.to_string(),
          faucetId.to_string(),
          "Private",
          "1000"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          targetAccountId.to_string()
        );

        let consumeTransactionResult = await createNewConsumeTransaction(
          webClient,
          targetAccountId.to_string(),
          mintTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await getInputNote(
          webClient,
          mintTransactionResult.created_note_ids[0]
        );

        console.log("testGetInputNote finished");
      }

      // Done
      async function testGetNote() {
        console.log("testGetNote started");
        let webClient = await createMidenWebClient();

        // Create accounts and sync
        let regularAccountTemplate = createBasicMutableAccountTemplate("Local");
        let fungibleFaucetAccountTemplate = createFungibleFaucetAccountTemplate(
          "DEN",
          "10",
          "1000000",
          "Local"
        );
        let regularAccountId = await createNewAccount(
          webClient,
          regularAccountTemplate
        );
        let faucetId = await createNewAccount(
          webClient,
          fungibleFaucetAccountTemplate
        );
        await syncState(webClient);
        await new Promise((r) => setTimeout(r, 10000));

        // Create mint transaction and sync
        let transactionTemplate = createMintTransactionTemplate(
          regularAccountId,
          faucetId,
          "1000",
          "Private"
        );
        let createTransactionResult = await createTransaction(
          webClient,
          transactionTemplate
        );
        await new Promise((r) => setTimeout(r, 10000));
        await syncState(webClient);

        await getInputNote(
          webClient,
          createTransactionResult.created_note_ids[0]
        );

        console.log("testGetNote finished");
      }

      // Done
      async function testGetOutputNotes() {
        console.log("testGetOutputNotes started");

        let webClient = await createMidenWebClient();
        let targetAccountId = await createNewWallet(webClient, "Private", true);
        let faucetId = await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );
        await syncState(webClient);
        await new Promise((r) => setTimeout(r, 20000));

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          faucetId.to_string()
        );

        let mintTransactionResult = await createNewMintTransaction(
          webClient,
          targetAccountId.to_string(),
          faucetId.to_string(),
          "Private",
          "1000"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          targetAccountId.to_string()
        );

        let consumeTransactionResult = await createNewConsumeTransaction(
          webClient,
          targetAccountId.to_string(),
          mintTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await getOutputNotes(webClient);

        console.log("testGetOutputNotes finished");
      }

      // Done
      async function testGetOutputNote() {
        console.log("testGetOutputNote started");

        let webClient = await createMidenWebClient();
        let targetAccountId = await createNewWallet(webClient, "Private", true);
        let faucetId = await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );
        await syncState(webClient);
        await new Promise((r) => setTimeout(r, 20000));

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          faucetId.to_string()
        );

        let mintTransactionResult = await createNewMintTransaction(
          webClient,
          targetAccountId.to_string(),
          faucetId.to_string(),
          "Private",
          "1000"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await webClient.fetch_and_cache_account_auth_by_pub_key(
          targetAccountId.to_string()
        );

        let consumeTransactionResult = await createNewConsumeTransaction(
          webClient,
          targetAccountId.to_string(),
          mintTransactionResult.created_note_ids
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        await getOutputNote(
          webClient,
          mintTransactionResult.created_note_ids[0]
        );

        console.log("testGetOutputNote finished");
      }

      // Done
      async function testExportNote() {
        console.log("testExportNote started");

        let webClient = await createMidenWebClient();
        // let senderAccountId = await createNewWallet(webClient, "Private", true);
        let faucetId = await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );
        await syncState(webClient);
        await new Promise((r) => setTimeout(r, 20000));

        await webClient.fetch_and_cache_account_auth_by_pub_key(faucetId);

        let mintTransactionResult = await createNewMintTransaction(
          webClient,
          "0x9186b96f559e852f", // Insert target account id here
          faucetId,
          "Private",
          "1000"
        );
        await new Promise((r) => setTimeout(r, 20000));
        await syncState(webClient);

        let result = await exportNote(
          webClient,
          mintTransactionResult.created_note_ids[0]
        );

        const blob = new Blob([result], { type: "application/octet-stream" });

        // Create a URL for the Blob
        const url = URL.createObjectURL(blob);

        // Create a temporary anchor element
        const a = document.createElement("a");
        a.href = url;
        a.download = "exportNoteTest.mno"; // Specify the file name

        // Append the anchor to the document
        document.body.appendChild(a);

        // Programmatically click the anchor to trigger the download
        a.click();

        // Remove the anchor from the document
        document.body.removeChild(a);

        // Revoke the object URL to free up resources
        URL.revokeObjectURL(url);

        console.log("testExportNote finished");
      }

      // Done
      async function testImportInputNote() {
        console.log("testImportInputNote started");

        let webClient = await createMidenWebClient();
        let walletAccount = await createNewWallet(webClient, "Private", true);

        function setupNoteFileInputListener(webClient, targetAccountId) {
          document
            .getElementById("noteFileInput")
            .addEventListener("change", async function (event) {
              const file = event.target.files[0];
              if (file) {
                const reader = new FileReader();
                reader.onload = async function (e) {
                  const arrayBuffer = e.target.result;
                  const byteArray = new Uint8Array(arrayBuffer);
                  console.log(byteArray); // Now you can work with the bytes

                  let result = await importInputNote(
                    webClient,
                    byteArray,
                    false
                  );
                  console.log(result); // Log the result of the import process

                  await webClient.fetch_and_cache_account_auth_by_pub_key(
                    targetAccountId
                  );

                  let consumeTransactionResult =
                    await createNewConsumeTransaction(
                      webClient,
                      "0x98f63aaa54c58c14",
                      // targetAccountId,
                      [result]
                    );
                  await new Promise((r) => setTimeout(r, 20000));
                  await syncState(webClient);

                  console.log("testImportInputNote finished");
                };
                reader.readAsArrayBuffer(file);
              }
            });
        }

        setupNoteFileInputListener(webClient, walletAccount);
      }

      // This test is modeled after this test in the Miden codebase:
      // https://github.com/0xPolygonMiden/miden-client/blob/2f8707faeded3725a1d732310f616e3e2170a50d/tests/integration/custom_transactions_tests.rs#L54
      async function testCustomTransaction() {
        console.log("testCustomTransaction started");
        // Creating Wallet and Faucet
        let webClient = await createMidenWebClient();
        let walletId = await createNewWallet(webClient, "Private", false);
        let faucetId = await createNewFaucet(
          webClient,
          "Private",
          false,
          "DEN",
          "10",
          "1000000"
        );
        await syncState(webClient);

        // Creating Custom Note which needs the following:
        // - Note Assets
        // - Note Metadata
        // - Note Recipient

        // Creating NOTE_ARGS
        let felt1 = new Felt(BigInt(9));
        let felt2 = new Felt(BigInt(12));
        let felt3 = new Felt(BigInt(18));
        let felt4 = new Felt(BigInt(3));
        let felt5 = new Felt(BigInt(3));
        let felt6 = new Felt(BigInt(18));
        let felt7 = new Felt(BigInt(12));
        let felt8 = new Felt(BigInt(9));
        let noteArgs = [felt1, felt2, felt3, felt4, felt5, felt6, felt7, felt8];
        let feltArray = new FeltArray();
        noteArgs.forEach((felt) => feltArray.append(felt));

        let noteAssets = new NoteAssets([
          new FungibleAsset(faucetId, BigInt(10)),
        ]);

        let noteMetadata = new NoteMetadata(
          faucetId,
          NoteType.private(),
          NoteTag.from_account_id(walletId, NoteExecutionMode.new_local()),
          NoteExecutionHint.none(),
          null
        );

        let expectedNoteArgs = noteArgs.map((felt) => felt.as_int());
        let memAddress = "1000";
        let memAddress2 = "1004";
        let expectedNoteArg1 = expectedNoteArgs.slice(0, 4).join(".");
        let expectedNoteArg2 = expectedNoteArgs.slice(4, 8).join(".");
        let note_script = `
                # Custom P2ID note script
                #
                # This note script asserts that the note args are exactly the same as passed 
                # (currently defined as {expected_note_arg_1} and {expected_note_arg_2}).
                # Since the args are too big to fit in a single note arg, we provide them via advice inputs and 
                # address them via their commitment (noted as NOTE_ARG)
                # This note script is based off of the P2ID note script because notes currently need to have 
                # assets, otherwise it could have been boiled down to the assert. 

                use.miden::account
                use.miden::note
                use.miden::contracts::wallets::basic->wallet
                use.std::mem


                proc.add_note_assets_to_account
                    push.0 exec.note::get_assets
                    # => [num_of_assets, 0 = ptr, ...]

                    # compute the pointer at which we should stop iterating
                    mul.4 dup.1 add
                    # => [end_ptr, ptr, ...]

                    # pad the stack and move the pointer to the top
                    padw movup.5
                    # => [ptr, 0, 0, 0, 0, end_ptr, ...]

                    # compute the loop latch
                    dup dup.6 neq
                    # => [latch, ptr, 0, 0, 0, 0, end_ptr, ...]

                    while.true
                        # => [ptr, 0, 0, 0, 0, end_ptr, ...]

                        # save the pointer so that we can use it later
                        dup movdn.5
                        # => [ptr, 0, 0, 0, 0, ptr, end_ptr, ...]

                        # load the asset
                        mem_loadw
                        # => [ASSET, ptr, end_ptr, ...]

                        # pad the stack before call
                        padw swapw padw padw swapdw
                        # => [ASSET, pad(12), ptr, end_ptr, ...]

                        # add asset to the account
                        call.wallet::receive_asset
                        # => [pad(16), ptr, end_ptr, ...]

                        # clean the stack after call
                        dropw dropw dropw
                        # => [0, 0, 0, 0, ptr, end_ptr, ...]

                        # increment the pointer and compare it to the end_ptr
                        movup.4 add.4 dup dup.6 neq
                        # => [latch, ptr+4, ASSET, end_ptr, ...]
                    end

                    # clear the stack
                    drop dropw drop
                end

                begin
                    # push data from the advice map into the advice stack
                    adv.push_mapval
                    # => [NOTE_ARG] 

                    # memory address where to write the data
                    push.${memAddress}
                    # => [target_mem_addr, NOTE_ARG_COMMITMENT]
                    # number of words
                    push.2
                    # => [number_of_words, target_mem_addr, NOTE_ARG_COMMITMENT]
                    exec.mem::pipe_preimage_to_memory
                    # => [target_mem_addr']
                    dropw
                    # => []
                    
                    # read first word
                    push.${memAddress}
                    # => [data_mem_address]
                    mem_loadw
                    # => [NOTE_ARG_1]
                    
                    push.${expectedNoteArg1} assert_eqw.err=101
                    # => []

                    # read second word
                    push.${memAddress2}
                    # => [data_mem_address_2]
                    mem_loadw
                    # => [NOTE_ARG_2]

                    push.${expectedNoteArg2} assert_eqw.err=102
                    # => []

                    # store the note inputs to memory starting at address 0
                    push.0 exec.note::get_inputs
                    # => [num_inputs, inputs_ptr]

                    # make sure the number of inputs is 1
                    eq.2 assert.err=103
                    # => [inputs_ptr]

                    # read the target account id from the note inputs
                    mem_load
                    # => [target_account_id_prefix]

                    exec.account::get_id swap drop
                    # => [account_id_prefix, target_account_id_prefix, ...]

                    # ensure account_id = target_account_id, fails otherwise
                    assert_eq.err=104
                    # => [...]

                    exec.add_note_assets_to_account
                    # => [...]
                end
            `;

        let compiledNoteScript =
          await webClient.compile_note_script(note_script);
        let noteInputs = new NoteInputs(new FeltArray([walletId.to_felt()]));

        let noteRecipient = new NoteRecipient(compiledNoteScript, noteInputs);

        let note = new Note(noteAssets, noteMetadata, noteRecipient);

        // Creating First Custom Transaction Request to Mint the Custom Note
        let transaction_request = new TransactionRequestBuilder()
          .with_own_output_notes(new OutputNotesArray([OutputNote.full(note)]))
          .build();

        // Execute and Submit Transaction
        await webClient.fetch_and_cache_account_auth_by_pub_key(
          faucetId.to_string()
        );
        let transaction_result = await webClient.new_transaction(
          faucetId,
          transaction_request
        );
        await webClient.submit_transaction(transaction_result);
        await new Promise((r) => setTimeout(r, 10000));
        await webClient.sync_state();

        // Just like in the miden test, you can modify this script to get the execution to fail
        // by modifying the assert
        let tx_script = `
                use.miden::contracts::auth::basic->auth_tx
                use.miden::kernels::tx::prologue
                use.miden::kernels::tx::memory

                begin
                    push.0 push.0
                    # => [0, 0]
                    assert_eq

                    call.auth_tx::auth_tx_rpo_falcon512
                end
            `;

        // Creating Second Custom Transaction Request to Consume Custom Note
        // with Invalid/Valid Transaction Script
        let account_auth = await webClient.get_account_auth(walletId);
        let public_key = account_auth.get_rpo_falcon_512_public_key_as_word();
        let secret_key = account_auth.get_rpo_falcon_512_secret_key_as_felts();
        let transcription_script_input_pair_array =
          new TransactionScriptInputPairArray([
            new TransactionScriptInputPair(public_key, secret_key),
          ]);
        let transaction_script = await webClient.compile_tx_script(
          tx_script,
          transcription_script_input_pair_array
        );
        let note_id = note.id();
        let note_args_commitment = Rpo256.hash_elements(feltArray); // gets consumed by NoteIdAndArgs
        let note_id_and_args = new NoteIdAndArgs(
          note_id,
          note_args_commitment.to_word()
        );
        let note_id_and_args_array = new NoteIdAndArgsArray([note_id_and_args]);
        let advice_map = new AdviceMap();
        let note_args_commitment_2 = Rpo256.hash_elements(feltArray);
        advice_map.insert(note_args_commitment_2, feltArray);

        let transaction_request_2 = new TransactionRequest()
          .with_authenticated_input_notes(note_id_and_args_array)
          .with_custom_script(transaction_script)
          .extend_advice_map(advice_map);

        // Execute and Submit Transaction
        await webClient.fetch_and_cache_account_auth_by_pub_key(
          walletId.to_string()
        );
        let transaction_result_2 = await webClient.new_transaction(
          walletId,
          transaction_request_2
        );
        await webClient.submit_transaction(transaction_result_2);
        await new Promise((r) => setTimeout(r, 10000));
        await webClient.sync_state();

        console.log("testCustomTransaction finished");
      }

      await testCreateNewWallet();
      // await testCreateNewFaucet();
      // await testGetAccounts();
      // await testGetAccount();
      // await testNewMintTransaction();
      // await testNewConsumeTransaction();
      // await testNewSendTransaction();
      // await testNewSendTransactionWithRecallHeight();
      // await testNewSwapTransaction();
      // await testGetTransactions();
      // await testGetInputNotes();
      // await testGetInputNote();
      // await testGetOutputNotes();
      // await testGetOutputNote();
      // await testExportNote();
      // await testImportInputNote();
      // await testCustomTransaction();
    </script>
  </body>
</html>