namada_apps_lib 0.251.4

Namada CLI apps library code
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
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
use std::fs::File;
use std::io::Write;

use color_eyre::owo_colors::OwoColorize;
use ledger_namada_rs::{BIP44Path, KeyResponse, NamadaApp, NamadaKeys};
use masp_primitives::sapling::redjubjub::PrivateKey;
use masp_primitives::sapling::{ProofGenerationKey, redjubjub};
use masp_primitives::transaction::components::sapling;
use masp_primitives::transaction::components::sapling::builder::{
    BuildParams, ConvertBuildParams, OutputBuildParams, RngBuildParams,
    SpendBuildParams, StoredBuildParams,
};
use masp_primitives::transaction::components::sapling::fees::InputView;
use masp_primitives::zip32::{
    ExtendedFullViewingKey, ExtendedKey, PseudoExtendedKey,
};
use namada_core::masp::MaspTransaction;
use namada_sdk::address::{Address, ImplicitAddress, MASP};
use namada_sdk::args::TxBecomeValidator;
use namada_sdk::borsh::{BorshDeserialize, BorshSerializeExt};
use namada_sdk::collections::HashMap;
use namada_sdk::governance::cli::onchain::{
    DefaultProposal, PgfFundingProposal, PgfStewardProposal,
};
use namada_sdk::ibc::convert_masp_tx_to_ibc_memo;
use namada_sdk::io::{Io, display_line, edisplay_line};
use namada_sdk::key::*;
use namada_sdk::rpc::{InnerTxResult, TxBroadcastData, TxResponse};
use namada_sdk::signing::SigningData;
use namada_sdk::state::EPOCH_SWITCH_BLOCKS_DELAY;
use namada_sdk::tx::data::compute_inner_tx_hash;
use namada_sdk::tx::{CompressedAuthorization, Section, Signer, Tx};
use namada_sdk::wallet::alias::{validator_address, validator_consensus_key};
use namada_sdk::wallet::{Wallet, WalletIo};
use namada_sdk::{ExtendedViewingKey, Namada, error, signing, tx};
use rand::rngs::OsRng;
use tokio::sync::RwLock;

use super::rpc;
use crate::cli::{args, safe_exit};
use crate::client::tx::signing::{SigningTxData, default_sign};
use crate::client::tx::tx::ProcessTxResponse;
use crate::config::TendermintMode;
use crate::tendermint_node;
use crate::tendermint_rpc::endpoint::broadcast::tx_sync::Response;
use crate::wallet::{
    WalletTransport, gen_validator_keys, read_and_confirm_encryption_password,
};

// Maximum number of spend description randomness parameters that can be
// generated on the hardware wallet. It is hard to compute the exact required
// number because a given MASP source could be distributed amongst several
// notes.
const MAX_HW_SPEND: usize = 15;
// Maximum number of convert description randomness parameters that can be
// generated on the hardware wallet. It is hard to compute the exact required
// number because the number of conversions that are used depends on the
// protocol's current state.
const MAX_HW_CONVERT: usize = 15;
// Maximum number of output description randomness parameters that can be
// generated on the hardware wallet. It is hard to compute the exact required
// number because the number of outputs depends on the number of dummy outputs
// introduced.
const MAX_HW_OUTPUT: usize = 15;

pub async fn with_hardware_wallet<U, T>(
    mut tx: Tx,
    pubkey: common::PublicKey,
    parts: signing::Signable,
    (wallet, app): (&RwLock<Wallet<U>>, &NamadaApp<T>),
) -> Result<Tx, error::Error>
where
    U: WalletIo + Clone,
    T: ledger_transport::Exchange + Send + Sync,
    <T as ledger_transport::Exchange>::Error: std::error::Error,
{
    // Obtain derivation path
    let path = wallet
        .read()
        .await
        .find_path_by_pkh(&(&pubkey).into())
        .map_err(|_| {
            error::Error::Other(
                "Unable to find derivation path for key".to_string(),
            )
        })?;
    let path = BIP44Path {
        path: path.to_string(),
    };
    // Now check that the public key at this path in the Ledger
    // matches
    let response_pubkey = app
        .get_address_and_pubkey(&path, false)
        .await
        .map_err(|err| error::Error::Other(err.to_string()))?;
    let response_pubkey =
        common::PublicKey::try_from_slice(&response_pubkey.public_key)
            .map_err(|err| {
                error::Error::Other(format!(
                    "unable to decode public key from hardware wallet: {}",
                    err
                ))
            })?;
    if response_pubkey != pubkey {
        return Err(error::Error::Other(format!(
            "Unrecognized public key fetched from Ledger: {}. Expected {}.",
            response_pubkey, pubkey,
        )));
    }
    // Get the Ledger to sign using our obtained derivation path
    println!(
        "Requesting that hardware wallet sign transaction with transparent \
         key at {}...",
        path.path
    );
    let response = app
        .sign(&path, &tx.serialize_to_vec())
        .await
        .map_err(|err| error::Error::Other(err.to_string()))?;
    // Sign the raw header if that is requested
    if parts == signing::Signable::RawHeader
        || parts == signing::Signable::FeeRawHeader
    {
        let pubkey = common::PublicKey::try_from_slice(&response.pubkey)
            .expect("unable to parse public key from Ledger");
        let signature =
            common::Signature::try_from_slice(&response.raw_signature)
                .expect("unable to parse signature from Ledger");
        // Signatures from the Ledger come back in compressed
        // form
        let compressed = CompressedAuthorization {
            targets: response.raw_indices,
            signer: Signer::PubKeys(vec![pubkey]),
            signatures: [(0, signature)].into(),
        };
        // Expand out the signature before adding it to the
        // transaction
        tx.add_section(Section::Authorization(compressed.expand(&tx)));
    }
    // Sign the fee header if that is requested
    if parts == signing::Signable::FeeRawHeader {
        let pubkey = common::PublicKey::try_from_slice(&response.pubkey)
            .expect("unable to parse public key from Ledger");
        let signature =
            common::Signature::try_from_slice(&response.wrapper_signature)
                .expect("unable to parse signature from Ledger");
        // Signatures from the Ledger come back in compressed
        // form
        let compressed = CompressedAuthorization {
            targets: response.wrapper_indices,
            signer: Signer::PubKeys(vec![pubkey]),
            signatures: [(0, signature)].into(),
        };
        // Expand out the signature before adding it to the
        // transaction
        tx.add_section(Section::Authorization(compressed.expand(&tx)));
    }
    Ok(tx)
}

// Sign the given transaction using a hardware wallet as a backup
pub async fn sign<N: Namada>(
    context: &N,
    tx: &mut Tx,
    args: &args::Tx,
    signing_data: SigningData,
) -> Result<(), error::Error> {
    // Setup a reusable context for signing transactions using the Ledger
    if args.use_device {
        let transport = WalletTransport::from_arg(args.device_transport);
        let app = NamadaApp::new(transport);
        let with_hw_data = (context.wallet_lock(), &app);
        // Finally, begin the signing with the Ledger as backup
        context
            .sign(
                tx,
                args,
                signing_data,
                with_hardware_wallet::<N::WalletUtils, _>,
                with_hw_data,
            )
            .await?;
    } else {
        // Otherwise sign without a backup procedure
        context
            .sign(tx, args, signing_data, default_sign, ())
            .await?;
    }
    Ok(())
}

// Build a transaction to reveal the signer of the given transaction.
pub async fn submit_reveal_aux(
    context: &impl Namada,
    args: &args::Tx,
    address: &Address,
) -> Result<Option<(Tx, SigningData)>, error::Error> {
    if let Address::Implicit(ImplicitAddress(pkh)) = address {
        let public_key = context
            .wallet_mut()
            .await
            .find_public_key_by_pkh(pkh)
            .map_err(|e| error::Error::Other(e.to_string()))?;

        if tx::is_reveal_pk_needed(context.client(), address).await? {
            display_line!(
                context.io(),
                "Submitting a tx to reveal the public key for address \
                 {address}"
            );
            return Ok(Some(
                tx::build_reveal_pk(context, args, &public_key).await?,
            ));
        }
    }

    Ok(None)
}

async fn batch_opt_reveal_pk_and_submit<N: Namada>(
    namada: &N,
    args: &args::Tx,
    owners: &[&Address],
    mut tx_data: (Tx, SigningData),
) -> Result<ProcessTxResponse, error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let mut batched_tx_data = vec![];

    for owner in owners {
        if let Some(reveal_pk_tx_data) =
            submit_reveal_aux(namada, args, owner).await?
        {
            batched_tx_data.push(reveal_pk_tx_data);
        }
    }

    // Since hardware wallets do not yet support batched transactions, use a
    // different logic in order to achieve compatibility
    if args.use_device {
        // Sign each transaction separately
        for (tx, sig_data) in &mut batched_tx_data {
            sign(namada, tx, args, sig_data.to_owned()).await?;
        }
        sign(namada, &mut tx_data.0, args, tx_data.1).await?;
        // Then submit each transaction separately
        for (tx, _sig_data) in batched_tx_data {
            namada.submit(tx, args).await?;
        }
        // The result of submitting this function's argument is what is returned
        namada.submit(tx_data.0, args).await
    } else {
        // Otherwise complete the batch with this function's argument
        batched_tx_data.push(tx_data);
        let (mut batched_tx, batched_signing_data) =
            namada_sdk::tx::build_batch(batched_tx_data)?;
        // Sign the batch with the union of the signers required for each part
        match batched_signing_data {
            either::Either::Left(wrapper_sig_data) => {
                sign(
                    namada,
                    &mut batched_tx,
                    args,
                    SigningData::Wrapper(wrapper_sig_data),
                )
                .await?;
            }
            either::Either::Right(sig_data_collection) => {
                // In this case we need to loop on all the signing data and
                // produce a signature for each one
                for sig_data in sig_data_collection {
                    sign(
                        namada,
                        &mut batched_tx,
                        args,
                        SigningData::Inner(sig_data),
                    )
                    .await?;
                }
            }
        }
        // Then finally submit everything in one go
        namada.submit(batched_tx, args).await
    }
}

pub async fn submit_bridge_pool_tx<N: Namada>(
    namada: &N,
    args: args::EthereumBridgePool,
) -> Result<(), error::Error> {
    let bridge_pool_tx_data = args.clone().build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(
            namada.io(),
            dump_tx,
            args.tx.output_folder,
            bridge_pool_tx_data.0,
        )?;
    } else {
        batch_opt_reveal_pk_and_submit(
            namada,
            &args.tx,
            &[&args.sender],
            bridge_pool_tx_data,
        )
        .await?;
    }

    Ok(())
}

pub async fn submit_custom<N: Namada>(
    namada: &N,
    args: args::TxCustom,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        // Attach the provided inner signatures to the tx (if any)
        let signatures = args
            .signatures
            .iter()
            .map(|bytes| {
                tx::SignatureIndex::try_from_json_bytes(bytes).map_err(|err| {
                    error::Error::Encode(error::EncodingError::Serde(
                        err.to_string(),
                    ))
                })
            })
            .collect::<error::Result<Vec<_>>>()?;
        tx.add_signatures(signatures);
        return tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx);
    }

    let owners = args
        .owner
        .map_or_else(Default::default, |owner| vec![owner]);
    let refs: Vec<&Address> = owners.iter().collect();
    batch_opt_reveal_pk_and_submit(namada, &args.tx, &refs, (tx, signing_data))
        .await?;

    Ok(())
}

pub async fn submit_update_account<N: Namada>(
    namada: &N,
    args: args::TxUpdateAccount,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

pub async fn submit_init_account<N: Namada>(
    namada: &N,
    args: args::TxInitAccount,
) -> Result<Option<Address>, error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = tx::build_init_account(namada, &args).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        let cmt = tx.first_commitments().unwrap().to_owned();
        let wrapper_hash = tx.wrapper_hash();
        let response = namada.submit(tx, &args.tx).await?;
        if let Some(result) =
            response.is_applied_and_valid(wrapper_hash.as_ref(), &cmt)
        {
            return Ok(result.initialized_accounts.first().cloned());
        }
    }

    Ok(None)
}

pub async fn submit_change_consensus_key(
    namada: &impl Namada,
    args: args::ConsensusKeyChange,
) -> Result<(), error::Error> {
    let validator = args.validator;
    let consensus_key = args.consensus_key;

    // Determine the alias for the new key
    let mut wallet = namada.wallet_mut().await;
    let alias = wallet.find_alias(&validator).cloned();
    let base_consensus_key_alias = alias
        .map(|al| validator_consensus_key(&al))
        .unwrap_or_else(|| {
            validator_consensus_key(&validator.to_string().into())
        });
    let mut consensus_key_alias = base_consensus_key_alias.to_string();
    let all_keys = wallet.get_secret_keys();
    let mut key_counter = 0;
    while all_keys.contains_key(&consensus_key_alias) {
        key_counter += 1;
        consensus_key_alias =
            format!("{base_consensus_key_alias}-{key_counter}");
    }

    // Check the given key or generate a new one
    let new_key = consensus_key
        .map(|key| match key {
            common::PublicKey::Ed25519(_) => key,
            common::PublicKey::Secp256k1(_) => {
                edisplay_line!(
                    namada.io(),
                    "Consensus key can only be ed25519"
                );
                safe_exit(1)
            }
        })
        .unwrap_or_else(|| {
            display_line!(namada.io(), "Generating new consensus key...");
            let password =
                read_and_confirm_encryption_password(args.unsafe_dont_encrypt);
            wallet
                .gen_store_secret_key(
                    // Note that TM only allows ed25519 for consensus key
                    SchemeType::Ed25519,
                    Some(consensus_key_alias.clone()),
                    args.tx.wallet_alias_force,
                    password,
                    &mut OsRng,
                )
                .expect("Key generation should not fail.")
                .1
                .ref_to()
        });

    // To avoid wallet deadlocks in following operations
    drop(wallet);

    let args = args::ConsensusKeyChange {
        validator: validator.clone(),
        consensus_key: Some(new_key.clone()),
        ..args
    };

    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;
        let cmt = tx.first_commitments().unwrap().to_owned();
        let wrapper_hash = tx.wrapper_hash();
        let resp = namada.submit(tx, &args.tx).await?;

        if args.tx.dry_run.is_none() {
            if resp
                .is_applied_and_valid(wrapper_hash.as_ref(), &cmt)
                .is_some()
            {
                namada.wallet_mut().await.save().unwrap_or_else(|err| {
                    edisplay_line!(namada.io(), "{}", err)
                });

                display_line!(
                    namada.io(),
                    "New consensus key stored with alias \
                     \"{consensus_key_alias}\". It will become active \
                     {EPOCH_SWITCH_BLOCKS_DELAY} blocks before the start of \
                     the pipeline epoch relative to the current epoch \
                     (current epoch + pipeline offset), at which point you \
                     will need to give the new key to CometBFT in order to be \
                     able to sign with it in consensus.",
                );
            }
        } else {
            display_line!(
                namada.io(),
                "Transaction dry run. No new consensus key has been saved."
            );
        }
    }
    Ok(())
}

pub async fn submit_become_validator(
    namada: &impl Namada,
    config: &mut crate::config::Config,
    args: args::TxBecomeValidator,
) -> Result<(), error::Error> {
    let alias = args
        .tx
        .initialized_account_alias
        .as_ref()
        .cloned()
        .unwrap_or_else(|| "validator".to_string());

    let validator_key_alias = format!("{}-key", alias);
    let consensus_key_alias = validator_consensus_key(&alias.clone().into());
    let protocol_key_alias = format!("{}-protocol-key", alias);
    let eth_hot_key_alias = format!("{}-eth-hot-key", alias);
    let eth_cold_key_alias = format!("{}-eth-cold-key", alias);
    let address_alias = validator_address(&alias.clone().into());

    let mut wallet = namada.wallet_mut().await;
    let consensus_key = args
        .consensus_key
        .clone()
        .map(|key| match key {
            common::PublicKey::Ed25519(_) => key,
            common::PublicKey::Secp256k1(_) => {
                edisplay_line!(
                    namada.io(),
                    "Consensus key can only be ed25519"
                );
                safe_exit(1)
            }
        })
        .unwrap_or_else(|| {
            display_line!(namada.io(), "Generating consensus key...");
            let password =
                read_and_confirm_encryption_password(args.unsafe_dont_encrypt);
            wallet
                .gen_store_secret_key(
                    // Note that TM only allows ed25519 for consensus key
                    SchemeType::Ed25519,
                    Some(consensus_key_alias.clone().into()),
                    args.tx.wallet_alias_force,
                    password,
                    &mut OsRng,
                )
                .expect("Key generation should not fail.")
                .1
                .ref_to()
        });

    let eth_cold_pk = args
        .eth_cold_key
        .clone()
        .map(|key| match key {
            common::PublicKey::Secp256k1(_) => key,
            common::PublicKey::Ed25519(_) => {
                edisplay_line!(
                    namada.io(),
                    "Eth cold key can only be secp256k1"
                );
                safe_exit(1)
            }
        })
        .unwrap_or_else(|| {
            display_line!(namada.io(), "Generating Eth cold key...");
            let password =
                read_and_confirm_encryption_password(args.unsafe_dont_encrypt);
            wallet
                .gen_store_secret_key(
                    // Note that ETH only allows secp256k1
                    SchemeType::Secp256k1,
                    Some(eth_cold_key_alias.clone()),
                    args.tx.wallet_alias_force,
                    password,
                    &mut OsRng,
                )
                .expect("Key generation should not fail.")
                .1
                .ref_to()
        });

    let eth_hot_pk = args
        .eth_hot_key
        .clone()
        .map(|key| match key {
            common::PublicKey::Secp256k1(_) => key,
            common::PublicKey::Ed25519(_) => {
                edisplay_line!(
                    namada.io(),
                    "Eth hot key can only be secp256k1"
                );
                safe_exit(1)
            }
        })
        .unwrap_or_else(|| {
            display_line!(namada.io(), "Generating Eth hot key...");
            let password =
                read_and_confirm_encryption_password(args.unsafe_dont_encrypt);
            wallet
                .gen_store_secret_key(
                    // Note that ETH only allows secp256k1
                    SchemeType::Secp256k1,
                    Some(eth_hot_key_alias.clone()),
                    args.tx.wallet_alias_force,
                    password,
                    &mut OsRng,
                )
                .expect("Key generation should not fail.")
                .1
                .ref_to()
        });
    // To avoid wallet deadlocks in following operations
    drop(wallet);

    if args.protocol_key.is_none() {
        display_line!(namada.io(), "Generating protocol signing key...");
    }

    // Generate the validator keys
    let validator_keys = gen_validator_keys(
        &mut *namada.wallet_mut().await,
        Some(eth_hot_pk.clone()),
        args.protocol_key.clone(),
        args.scheme,
    )
    .unwrap();
    let protocol_sk = validator_keys.get_protocol_keypair();
    let protocol_key = protocol_sk.to_public();

    let args = TxBecomeValidator {
        consensus_key: Some(consensus_key.clone()),
        eth_cold_key: Some(eth_cold_pk),
        eth_hot_key: Some(eth_hot_pk),
        protocol_key: Some(protocol_key),
        ..args
    };

    // Store the protocol key in the wallet so that we can sign the tx with it
    // to verify ownership
    display_line!(namada.io(), "Storing protocol key in the wallet...");
    let password =
        read_and_confirm_encryption_password(args.unsafe_dont_encrypt);
    namada
        .wallet_mut()
        .await
        .insert_keypair(
            protocol_key_alias,
            args.tx.wallet_alias_force,
            protocol_sk.clone(),
            password,
            None,
            None,
        )
        .ok_or(error::Error::Other(String::from(
            "Failed to store the keypair.",
        )))?;

    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;
        let cmt = tx.first_commitments().unwrap().to_owned();
        let wrapper_hash = tx.wrapper_hash();
        let resp = namada.submit(tx, &args.tx).await?;

        if args.tx.dry_run.is_some() {
            display_line!(
                namada.io(),
                "Transaction dry run. No key or addresses have been saved."
            );
            safe_exit(0)
        }

        if resp
            .is_applied_and_valid(wrapper_hash.as_ref(), &cmt)
            .is_none()
        {
            return Err(error::Error::Tx(error::TxSubmitError::Other(
                "Transaction failed. No key or addresses have been saved."
                    .to_string(),
            )));
        }

        // add validator address and keys to the wallet
        let mut wallet = namada.wallet_mut().await;
        wallet.insert_address(
            address_alias.normalize(),
            args.address.clone(),
            false,
        );
        wallet.add_validator_data(args.address.clone(), validator_keys);
        wallet
            .save()
            .unwrap_or_else(|err| edisplay_line!(namada.io(), "{}", err));

        let tendermint_home = config.ledger.cometbft_dir();
        tendermint_node::write_validator_key(
            &tendermint_home,
            &wallet
                .find_key_by_pk(&consensus_key, None)
                .expect("unable to find consensus key pair in the wallet"),
        )
        .unwrap();
        // To avoid wallet deadlocks in following operations
        drop(wallet);
        tendermint_node::write_validator_state(tendermint_home).unwrap();

        // Write Namada config stuff or figure out how to do the above
        // tendermint_node things two epochs in the future!!!
        config.ledger.shell.tendermint_mode = TendermintMode::Validator;
        config
            .write(&config.ledger.shell.base_dir, &config.ledger.chain_id, true)
            .unwrap();

        let pos_params = rpc::query_pos_parameters(namada.client()).await;

        display_line!(namada.io(), "");
        display_line!(
            namada.io(),
            "The keys for validator \"{alias}\" were stored in the wallet:"
        );
        display_line!(
            namada.io(),
            "  Validator account key \"{}\"",
            validator_key_alias
        );
        display_line!(
            namada.io(),
            "  Consensus key \"{}\"",
            consensus_key_alias
        );
        display_line!(
            namada.io(),
            "Your validator address {} has been stored in the wallet with \
             alias \"{}\".",
            args.address,
            address_alias
        );
        display_line!(
            namada.io(),
            "The ledger node has been setup to use this validator's address \
             and consensus key."
        );
        display_line!(
            namada.io(),
            "Your validator will be active in {} epochs. Be sure to restart \
             your node for the changes to take effect!",
            pos_params.pipeline_len
        );
    }
    Ok(())
}

pub async fn submit_init_validator(
    namada: &impl Namada,
    config: &mut crate::config::Config,
    args::TxInitValidator {
        tx: tx_args,
        scheme,
        account_keys,
        threshold,
        consensus_key,
        eth_cold_key,
        eth_hot_key,
        protocol_key,
        commission_rate,
        max_commission_rate_change,
        email,
        website,
        description,
        discord_handle,
        avatar,
        name,
        validator_vp_code_path,
        unsafe_dont_encrypt,
        tx_init_account_code_path,
        tx_become_validator_code_path,
    }: args::TxInitValidator,
) -> Result<(), error::Error> {
    let address = submit_init_account(
        namada,
        args::TxInitAccount {
            tx: tx_args.clone(),
            vp_code_path: validator_vp_code_path,
            tx_code_path: tx_init_account_code_path,
            public_keys: account_keys,
            threshold,
        },
    )
    .await?;

    if tx_args.dry_run.is_some() {
        eprintln!(
            "Cannot proceed to become validator in dry-run as no account has \
             been created"
        );
        safe_exit(1)
    }
    let address = address.unwrap_or_else(|| {
        eprintln!(
            "Something went wrong with transaction to initialize an account \
             as no address has been created. Cannot proceed to become \
             validator."
        );
        safe_exit(1);
    });

    submit_become_validator(
        namada,
        config,
        args::TxBecomeValidator {
            tx: tx_args,
            address,
            scheme,
            consensus_key,
            eth_cold_key,
            eth_hot_key,
            protocol_key,
            commission_rate,
            max_commission_rate_change,
            email,
            description,
            website,
            discord_handle,
            avatar,
            name,
            tx_code_path: tx_become_validator_code_path,
            unsafe_dont_encrypt,
        },
    )
    .await
}

pub async fn submit_transparent_transfer(
    namada: &impl Namada,
    args: args::TxTransparentTransfer,
) -> Result<(), error::Error> {
    if args.sources.len() > 1 || args.targets.len() > 1 {
        // TODO(namada#3379): Vectorized transfers are not yet supported in the
        // CLI
        return Err(error::Error::Other(
            "Unexpected vectorized transparent transfer".to_string(),
        ));
    }

    let transfer_data = args.clone().build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(
            namada.io(),
            dump_tx,
            args.tx.output_folder,
            transfer_data.0,
        )?;
    } else {
        let reveal_pks: Vec<_> =
            args.sources.iter().map(|datum| &datum.source).collect();
        batch_opt_reveal_pk_and_submit(
            namada,
            &args.tx,
            &reveal_pks,
            transfer_data,
        )
        .await?;
    }

    Ok(())
}

// A mapper that replaces authorization signatures with those in a built-in map
struct MapSaplingSigAuth(
    HashMap<usize, <sapling::Authorized as sapling::Authorization>::AuthSig>,
);

impl sapling::MapAuth<sapling::Authorized, sapling::Authorized>
    for MapSaplingSigAuth
{
    fn map_proof(
        &self,
        p: <sapling::Authorized as sapling::Authorization>::Proof,
        _pos: usize,
    ) -> <sapling::Authorized as sapling::Authorization>::Proof {
        p
    }

    fn map_auth_sig(
        &self,
        s: <sapling::Authorized as sapling::Authorization>::AuthSig,
        pos: usize,
    ) -> <sapling::Authorized as sapling::Authorization>::AuthSig {
        self.0.get(&pos).cloned().unwrap_or(s)
    }

    fn map_authorization(&self, a: sapling::Authorized) -> sapling::Authorized {
        a
    }
}

// Identify the viewing keys in the given transaction for which we do not
// possess spending keys in the software wallet, and augment them with a proof
// generation key from the hardware wallet. Returns a mapping from viewing keys
// to corresponding ZIP 32 paths in the hardware wallet. This function errors
// out if any ZIP 32 path that it handles maps to a different viewing key than
// it does on the software client.
async fn augment_masp_hardware_keys(
    namada: &impl Namada,
    args: &args::Tx,
    sources: impl Iterator<Item = &mut PseudoExtendedKey>,
) -> Result<HashMap<String, ExtendedViewingKey>, error::Error> {
    // Records the shielded keys that are on the hardware wallet
    let mut shielded_hw_keys = HashMap::new();
    // Construct the build parameters that parameterized the Transaction
    // authorizations
    if args.use_device {
        let transport = WalletTransport::from_arg(args.device_transport);
        let app = NamadaApp::new(transport);
        let wallet = namada.wallet().await;
        let mut checked_app_version = false;
        // Augment the pseudo spending key with a proof authorization key
        for source in sources {
            // Only attempt an augmentation if proof authorization is not there
            if source.to_spending_key().is_none() {
                if !checked_app_version {
                    checked_app_version = true;
                    let version = app.version().await.map_err(|err| {
                        error::Error::Other(format!(
                            "Failed to retrieve Ledger app version: {err}"
                        ))
                    })?;
                    if version.major < 3 {
                        edisplay_line!(
                            namada.io(),
                            "Please upgrade the Ledger app to version greater \
                             than or equal to 3.0.0 (got v{}.{}.{}.), due to \
                             a change in modified ZIP32 derivation path. If \
                             you have keys derived using an older versions, \
                             we recommend that you move any funds associated \
                             with them to new keys.",
                            version.major,
                            version.minor,
                            version.patch
                        );
                    }
                }

                // First find the derivation path corresponding to this viewing
                // key
                let viewing_key =
                    ExtendedViewingKey::from(source.to_viewing_key());
                let path = wallet
                    .find_path_by_viewing_key(&viewing_key)
                    .map_err(|err| {
                        error::Error::Other(format!(
                            "Unable to find derivation path from the wallet \
                             for viewing key {}. Error: {}",
                            viewing_key, err,
                        ))
                    })?;
                let path = BIP44Path {
                    path: path.to_string(),
                };
                // Then confirm that the viewing key at this path in the
                // hardware wallet matches the viewing key in this pseudo
                // spending key
                println!(
                    "Requesting viewing key at {} from hardware wallet...",
                    path.path
                );
                let response = app
                    .retrieve_keys(&path, NamadaKeys::ViewKey, true)
                    .await
                    .map_err(|err| {
                        error::Error::Other(format!(
                            "Unable to obtain viewing key from the hardware \
                             wallet at path {}. Error: {}",
                            path.path, err,
                        ))
                    })?;
                let KeyResponse::ViewKey(response_key) = response else {
                    return Err(error::Error::Other(
                        "Unexpected response from Ledger".to_string(),
                    ));
                };
                let xfvk =
                    ExtendedFullViewingKey::try_from_slice(&response_key.xfvk)
                        .expect(
                            "unable to decode extended full viewing key from \
                             the hardware wallet",
                        );
                if ExtendedFullViewingKey::from(viewing_key) != xfvk {
                    return Err(error::Error::Other(format!(
                        "Unexpected viewing key response from Ledger: {}",
                        ExtendedViewingKey::from(xfvk),
                    )));
                }
                // Then obtain the proof authorization key at this path in the
                // hardware wallet
                let response = app
                    .retrieve_keys(&path, NamadaKeys::ProofGenerationKey, false)
                    .await
                    .map_err(|err| {
                        error::Error::Other(format!(
                            "Unable to obtain proof generation key from the \
                             hardware wallet for viewing key {}. Error: {}",
                            viewing_key, err,
                        ))
                    })?;
                let KeyResponse::ProofGenKey(response_key) = response else {
                    return Err(error::Error::Other(
                        "Unexpected response from Ledger".to_string(),
                    ));
                };
                let pgk = ProofGenerationKey::try_from_slice(
                    &[response_key.ak, response_key.nsk].concat(),
                )
                .map_err(|err| {
                    error::Error::Other(format!(
                        "Unexpected proof generation key in response from the \
                         hardware wallet: {}.",
                        err,
                    ))
                })?;
                // Augment the pseudo spending key
                source.augment_proof_generation_key(pgk).map_err(|_| {
                    error::Error::Other(
                        "Proof generation key in response from the hardware \
                         wallet does not correspond to stored viewing key."
                            .to_string(),
                    )
                })?;
                // Finally, augment an incorrect spend authorization key just to
                // make sure that the Transaction is built.
                source.augment_spend_authorizing_key_unchecked(PrivateKey(
                    jubjub::Fr::default(),
                ));
                shielded_hw_keys.insert(path.path, viewing_key);
            }
        }
        Ok(shielded_hw_keys)
    } else {
        Ok(HashMap::new())
    }
}

// If the hardware wallet is beig used, use it to generate the random build
// parameters for the spend, convert, and output descriptions.
async fn generate_masp_build_params(
    spend_len: usize,
    convert_len: usize,
    output_len: usize,
    args: &args::Tx,
) -> Result<Box<dyn BuildParams>, error::Error> {
    // Construct the build parameters that parameterized the Transaction
    // authorizations
    if args.use_device {
        let transport = WalletTransport::from_arg(args.device_transport);
        let app = NamadaApp::new(transport);
        // Clear hardware wallet randomness buffers
        app.clean_randomness_buffers().await.map_err(|err| {
            error::Error::Other(format!(
                "Unable to clear randomness buffer. Error: {}",
                err,
            ))
        })?;
        // Get randomness to aid in construction of various descriptors
        let mut bparams = StoredBuildParams::default();
        for _ in 0..spend_len {
            let spend_randomness = app
                .get_spend_randomness()
                .await
                .map_err(|err| error::Error::Other(err.to_string()))?;
            bparams.spend_params.push(SpendBuildParams {
                rcv: jubjub::Fr::from_bytes(&spend_randomness.rcv).unwrap(),
                alpha: jubjub::Fr::from_bytes(&spend_randomness.alpha).unwrap(),
            });
        }
        for _ in 0..convert_len {
            let convert_randomness = app
                .get_convert_randomness()
                .await
                .map_err(|err| error::Error::Other(err.to_string()))?;
            bparams.convert_params.push(ConvertBuildParams {
                rcv: jubjub::Fr::from_bytes(&convert_randomness.rcv).unwrap(),
            });
        }
        for _ in 0..output_len {
            let output_randomness = app
                .get_output_randomness()
                .await
                .map_err(|err| error::Error::Other(err.to_string()))?;
            bparams.output_params.push(OutputBuildParams {
                rcv: jubjub::Fr::from_bytes(&output_randomness.rcv).unwrap(),
                rseed: output_randomness.rcm,
                ..OutputBuildParams::default()
            });
        }
        Ok(Box::new(bparams))
    } else {
        Ok(Box::new(RngBuildParams::new(OsRng)))
    }
}

// Sign the given transaction's MASP component using signatures produced by the
// hardware wallet. This function takes the list of spending keys that are
// hosted on the hardware wallet.
async fn masp_sign(
    tx: &mut Tx,
    args: &args::Tx,
    signing_data: &SigningTxData,
    shielded_hw_keys: HashMap<String, ExtendedViewingKey>,
) -> Result<(), error::Error> {
    // Get the MASP section that is the target of our signing
    if let Some(shielded_hash) = signing_data.shielded_hash {
        let mut masp_tx = tx
            .get_masp_section(&shielded_hash)
            .expect("Expected to find the indicated MASP Transaction")
            .clone();

        let masp_builder = tx
            .get_masp_builder(&shielded_hash)
            .expect("Expected to find the indicated MASP Builder");

        // Reverse the spend metadata to enable looking up construction
        // material
        let sapling_inputs = masp_builder.builder.sapling_inputs();
        let mut descriptor_map = vec![0; sapling_inputs.len()];
        for i in 0.. {
            if let Some(pos) = masp_builder.metadata.spend_index(i) {
                descriptor_map[pos] = i;
            } else {
                break;
            };
        }
        // Sign the MASP Transaction using each relevant key in the
        // hardware wallet
        let mut app = None;
        for (path, vk) in shielded_hw_keys {
            // Initialize the Ledger app interface if it is uninitialized
            let app = app.get_or_insert_with(|| {
                NamadaApp::new(WalletTransport::from_arg(args.device_transport))
            });
            // Sign the MASP Transaction using the current viewing key
            let path = BIP44Path {
                path: path.to_string(),
            };
            println!(
                "Requesting that hardware wallet sign shielded transfer with \
                 spending key at {}...",
                path.path
            );
            app.sign_masp_spends(&path, &tx.serialize_to_vec())
                .await
                .map_err(|err| error::Error::Other(err.to_string()))?;
            // Now prepare a new list of authorizations based on hardware
            // wallet responses
            let mut authorizations = HashMap::new();
            for (tx_pos, builder_pos) in descriptor_map.iter().enumerate() {
                // Read the next spend authorization signature from the
                // hardware wallet
                let response = app
                    .get_spend_signature()
                    .await
                    .map_err(|err| error::Error::Other(err.to_string()))?;
                let signature = redjubjub::Signature::try_from_slice(
                    &[response.rbar, response.sbar].concat(),
                )
                .map_err(|err| {
                    error::Error::Other(format!(
                        "Unexpected spend authorization key in response from \
                         the hardware wallet: {}.",
                        err,
                    ))
                })?;
                if *sapling_inputs[*builder_pos].key()
                    == ExtendedFullViewingKey::from(vk)
                {
                    // If this descriptor was produced by the current
                    // viewing key (which comes from the hardware wallet),
                    // then use the authorization from the hardware wallet
                    authorizations.insert(tx_pos, signature);
                }
            }
            // Finally, patch the MASP Transaction with the fetched spend
            // authorization signature
            masp_tx = (*masp_tx)
                .clone()
                .map_authorization::<masp_primitives::transaction::Authorized>(
                    (),
                    MapSaplingSigAuth(authorizations),
                )
                .freeze()
                .map_err(|err| {
                    error::Error::Other(format!(
                        "Unable to apply hardware walleet sourced \
                         authorization signatures to the transaction being \
                         constructed: {}.",
                        err,
                    ))
                })?;
        }
        tx.remove_masp_section(&shielded_hash);
        tx.add_section(Section::MaspTx(masp_tx));
    }
    Ok(())
}

pub async fn submit_shielded_transfer(
    namada: &impl Namada,
    mut args: args::TxShieldedTransfer,
) -> Result<(), error::Error> {
    display_line!(
        namada.io(),
        "{}: {}\n",
        "WARNING".bold().underline().yellow(),
        "Some information might be leaked if your shielded wallet is not up \
         to date, make sure to run `namadac shielded-sync` before running \
         this command.",
    );

    let sources = args
        .sources
        .iter_mut()
        .map(|x| &mut x.source)
        .chain(args.gas_spending_key.iter_mut());
    let shielded_hw_keys =
        augment_masp_hardware_keys(namada, &args.tx, sources).await?;
    let mut bparams = generate_masp_build_params(
        MAX_HW_SPEND,
        MAX_HW_CONVERT,
        MAX_HW_OUTPUT,
        &args.tx,
    )
    .await?;
    let (mut tx, signing_data) =
        args.clone().build(namada, &mut bparams).await?;
    let disposable_fee_payer = match signing_data {
        SigningData::Inner(_) => None,
        SigningData::Wrapper(ref signing_wrapper_data) => {
            Some(signing_wrapper_data.disposable_fee_payer())
        }
    };
    if let Some(false) = disposable_fee_payer {
        display_line!(
            namada.io(),
            "{}: {}\n",
            "WARNING".bold().underline().yellow(),
            "Using a transparent gas payer for a shielded transaction will \
             most likely leak information: please consider paying the gas \
             fees via the MASP with a disposable gas payer.",
        );
    }
    masp_sign(
        &mut tx,
        &args.tx,
        signing_data
            .signing_tx_data()
            .first()
            .expect("Missing expected signing data"),
        shielded_hw_keys,
    )
    .await?;

    let masp_section = tx
        .sections
        .iter()
        .find_map(|section| section.masp_tx())
        .ok_or_else(|| {
            error::Error::Other(
                "Missing MASP section in shielded transaction".to_string(),
            )
        })?;
    if let Some(dump_tx) = args.tx.dump_tx {
        if let Some(true) = disposable_fee_payer {
            display_line!(
                namada.io(),
                "Transaction dry run. The disposable address will not be \
                 saved to wallet."
            )
        }
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
        pre_cache_masp_data(namada, &masp_section).await;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;
        // Store the generated disposable signing key to wallet in case of need
        if let Some(true) = disposable_fee_payer {
            namada.wallet().await.save().map_err(|_| {
                error::Error::Other(
                    "Failed to save disposable address to wallet".to_string(),
                )
            })?;
        }
        let res = namada.submit(tx, &args.tx).await?;
        pre_cache_masp_data_on_tx_result(namada, &res, &masp_section).await;
    }
    Ok(())
}

pub async fn submit_shielding_transfer(
    namada: &impl Namada,
    args: args::TxShieldingTransfer,
) -> Result<(), error::Error> {
    // Repeat once if the tx fails on a crossover of an epoch
    for _ in 0..2 {
        let mut bparams = generate_masp_build_params(
            MAX_HW_SPEND,
            MAX_HW_CONVERT,
            MAX_HW_OUTPUT,
            &args.tx,
        )
        .await?;
        let (tx, signing_data, tx_epoch) =
            args.clone().build(namada, &mut bparams).await?;

        if let Some(dump_tx) = args.tx.dump_tx {
            tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
            break;
        }

        let cmt_hash = tx.commitments().last().unwrap().get_hash();
        let wrapper_hash = tx.wrapper_hash();

        let reveal_pks: Vec<_> =
            args.sources.iter().map(|datum| &datum.source).collect();
        let result = batch_opt_reveal_pk_and_submit(
            namada,
            &args.tx,
            &reveal_pks,
            (tx, signing_data),
        )
        .await?;

        // Check the need for a resubmission
        if let ProcessTxResponse::Applied(resp) = result {
            if let Some(InnerTxResult::VpsRejected(result)) =
                resp.batch_result().get(&compute_inner_tx_hash(
                    wrapper_hash.as_ref(),
                    either::Left(&cmt_hash),
                ))
            {
                let rejected_vps = &result.vps_result.rejected_vps;
                let vps_errors = &result.vps_result.errors;
                // If the transaction is rejected by the MASP VP only and
                // because of an asset's epoch issue
                if rejected_vps.len() == 1
                    && (vps_errors.contains(&(
                        MASP,
                        "Native VP error: epoch is missing from asset type"
                            .to_string(),
                    )) || vps_errors.contains(&(
                        MASP,
                        "Native VP error: Unable to decode asset type"
                            .to_string(),
                    )))
                {
                    let submission_masp_epoch =
                        rpc::query_and_print_masp_epoch(namada).await;
                    // And its submission epoch doesn't match construction
                    // epoch
                    if tx_epoch != submission_masp_epoch {
                        // Then we probably straddled an epoch boundary.
                        // Let's retry...
                        edisplay_line!(
                            namada.io(),
                            "Shielding transaction rejected and this may be \
                             due to the epoch changing. Attempting to \
                             resubmit transaction.",
                        );
                        continue;
                    }
                }
            }
        }

        // Otherwise either the transaction was successful or it will not
        // benefit from resubmission
        break;
    }
    Ok(())
}

pub async fn submit_unshielding_transfer(
    namada: &impl Namada,
    mut args: args::TxUnshieldingTransfer,
) -> Result<(), error::Error> {
    display_line!(
        namada.io(),
        "{}: {}\n",
        "WARNING".bold().underline().yellow(),
        "Some information might be leaked if your shielded wallet is not up \
         to date, make sure to run `namadac shielded-sync` before running \
         this command.",
    );

    let sources = args
        .sources
        .iter_mut()
        .map(|x| &mut x.source)
        .chain(args.gas_spending_key.iter_mut());
    let shielded_hw_keys =
        augment_masp_hardware_keys(namada, &args.tx, sources).await?;
    let mut bparams = generate_masp_build_params(
        MAX_HW_SPEND,
        MAX_HW_CONVERT,
        MAX_HW_OUTPUT,
        &args.tx,
    )
    .await?;
    let (mut tx, signing_data) =
        args.clone().build(namada, &mut bparams).await?;
    let disposable_fee_payer = match signing_data {
        SigningData::Inner(_) => None,
        SigningData::Wrapper(ref signing_wrapper_data) => {
            Some(signing_wrapper_data.disposable_fee_payer())
        }
    };
    if let Some(false) = disposable_fee_payer {
        display_line!(
            namada.io(),
            "{}: {}\n",
            "WARNING".bold().underline().yellow(),
            "Using a transparent gas payer for an unshielding transaction \
             will most likely leak information: please consider paying the \
             gas fees via the MASP with a disposable gas payer.",
        );
    }
    masp_sign(
        &mut tx,
        &args.tx,
        signing_data
            .signing_tx_data()
            .first()
            .expect("Missing signing data"),
        shielded_hw_keys,
    )
    .await?;

    let masp_section = tx
        .sections
        .iter()
        .find_map(|section| section.masp_tx())
        .ok_or_else(|| {
            error::Error::Other(
                "Missing MASP section in shielded transaction".to_string(),
            )
        })?;
    if let Some(dump_tx) = args.tx.dump_tx {
        if let Some(true) = disposable_fee_payer {
            display_line!(
                namada.io(),
                "Transaction dry run. The disposable address will not be \
                 saved to wallet."
            )
        }
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
        pre_cache_masp_data(namada, &masp_section).await;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;
        // Store the generated disposable signing key to wallet in case of need
        if let Some(true) = disposable_fee_payer {
            namada.wallet().await.save().map_err(|_| {
                error::Error::Other(
                    "Failed to save disposable address to wallet".to_string(),
                )
            })?;
        }
        let res = namada.submit(tx, &args.tx).await?;
        pre_cache_masp_data_on_tx_result(namada, &res, &masp_section).await;
    }
    Ok(())
}

pub async fn submit_ibc_transfer<N: Namada>(
    namada: &N,
    mut args: args::TxIbcTransfer,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let sources = args
        .source
        .spending_key_mut()
        .into_iter()
        .chain(args.gas_spending_key.iter_mut());
    let shielded_hw_keys =
        augment_masp_hardware_keys(namada, &args.tx, sources).await?;
    // Try to generate MASP build parameters. This might fail when using a
    // hardware wallet if it does not support MASP operations.
    let bparams_result = generate_masp_build_params(
        MAX_HW_SPEND,
        MAX_HW_CONVERT,
        MAX_HW_OUTPUT,
        &args.tx,
    )
    .await;
    // If MASP build parameter generation failed for any reason, then try to
    // build the transaction with no parameters. Remember the error though.
    let (mut bparams, bparams_err) = bparams_result.map_or_else(
        |e| (Box::new(StoredBuildParams::default()) as _, Some(e)),
        |bparams| (bparams, None),
    );
    // If transaction building fails for any reason, then abort the process
    // blaming MASP build parameter generation if that had also failed.
    let (mut tx, signing_data, _) = args
        .build(namada, &mut bparams)
        .await
        .map_err(|e| bparams_err.unwrap_or(e))?;
    let disposable_fee_payer = match signing_data {
        SigningData::Inner(_) => None,
        SigningData::Wrapper(ref signing_wrapper_data) => {
            Some(signing_wrapper_data.disposable_fee_payer())
        }
    };
    if let Some(false) = disposable_fee_payer {
        display_line!(
            namada.io(),
            "{}: {}\n",
            "WARNING".bold().underline().yellow(),
            "Using a transparent gas payer for an unshielding ibc transaction \
             will most likely leak information: please consider paying the \
             gas fees via the MASP with a disposable gas payer.",
        );
    }
    // Any effects of a MASP build parameter generation failure would have
    // manifested during transaction building. So we discount that as a root
    // cause from now on.
    masp_sign(
        &mut tx,
        &args.tx,
        signing_data
            .signing_tx_data()
            .first()
            .expect("Missing expected signing data"),
        shielded_hw_keys,
    )
    .await?;

    let opt_masp_section =
        tx.sections.iter().find_map(|section| section.masp_tx());
    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
        if let Some(true) = disposable_fee_payer {
            display_line!(
                namada.io(),
                "Transaction dry run. The disposable address will not be \
                 saved to wallet."
            )
        }
        if let Some(masp_section) = opt_masp_section {
            pre_cache_masp_data(namada, &masp_section).await;
        }
    } else {
        // Store the generated disposable signing key to wallet in case of need
        if let Some(true) = disposable_fee_payer {
            namada.wallet().await.save().map_err(|_| {
                error::Error::Other(
                    "Failed to save disposable address to wallet".to_string(),
                )
            })?;
        }
        let res = batch_opt_reveal_pk_and_submit(
            namada,
            &args.tx,
            &[&args.source.effective_address()],
            (tx, signing_data),
        )
        .await?;

        if let Some(masp_section) = opt_masp_section {
            pre_cache_masp_data_on_tx_result(namada, &res, &masp_section).await;
        }
    }
    // NOTE that the tx could fail when its submission epoch doesn't match
    // construction epoch

    Ok(())
}

pub async fn submit_init_proposal<N: Namada>(
    namada: &N,
    args: args::InitProposal,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let current_epoch = rpc::query_and_print_epoch(namada).await;
    let governance_parameters =
        rpc::query_governance_parameters(namada.client()).await;
    let (proposal_tx_data, proposal_author) = if args.is_pgf_funding {
        let proposal =
            PgfFundingProposal::try_from(args.proposal_data.as_ref())
                .map_err(|e| {
                    error::TxSubmitError::FailedGovernaneProposalDeserialize(
                        e.to_string(),
                    )
                })?
                .validate(&governance_parameters, current_epoch, args.tx.force)
                .map_err(|e| {
                    error::TxSubmitError::InvalidProposal(e.to_string())
                })?;
        let proposal_author = proposal.proposal.author.clone();

        (
            tx::build_pgf_funding_proposal(namada, &args, proposal).await?,
            proposal_author,
        )
    } else if args.is_pgf_stewards {
        let proposal = PgfStewardProposal::try_from(
            args.proposal_data.as_ref(),
        )
        .map_err(|e| {
            error::TxSubmitError::FailedGovernaneProposalDeserialize(
                e.to_string(),
            )
        })?;
        let author_balance = namada_sdk::rpc::get_token_balance(
            namada.client(),
            &namada.native_token(),
            &proposal.proposal.author,
            None,
        )
        .await
        .unwrap();
        let proposal = proposal
            .validate(
                &governance_parameters,
                current_epoch,
                author_balance,
                args.tx.force,
            )
            .map_err(|e| {
                error::TxSubmitError::InvalidProposal(e.to_string())
            })?;
        let proposal_author = proposal.proposal.author.clone();

        (
            tx::build_pgf_stewards_proposal(namada, &args, proposal).await?,
            proposal_author,
        )
    } else {
        let proposal = DefaultProposal::try_from(args.proposal_data.as_ref())
            .map_err(|e| {
            error::TxSubmitError::FailedGovernaneProposalDeserialize(
                e.to_string(),
            )
        })?;
        let author_balance = namada_sdk::rpc::get_token_balance(
            namada.client(),
            &namada.native_token(),
            &proposal.proposal.author,
            None,
        )
        .await
        .unwrap();
        let proposal = proposal
            .validate(
                &governance_parameters,
                current_epoch,
                author_balance,
                args.tx.force,
            )
            .map_err(|e| {
                error::TxSubmitError::InvalidProposal(e.to_string())
            })?;
        let proposal_author = proposal.proposal.author.clone();

        (
            tx::build_default_proposal(namada, &args, proposal).await?,
            proposal_author,
        )
    };

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(
            namada.io(),
            dump_tx,
            args.tx.output_folder,
            proposal_tx_data.0,
        )?;
    } else {
        batch_opt_reveal_pk_and_submit(
            namada,
            &args.tx,
            &[&proposal_author],
            proposal_tx_data,
        )
        .await?;
    }

    Ok(())
}

pub async fn submit_vote_proposal<N: Namada>(
    namada: &N,
    args: args::VoteProposal,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let submit_vote_proposal_data = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(
            namada.io(),
            dump_tx,
            args.tx.output_folder,
            submit_vote_proposal_data.0,
        )?;
    } else {
        batch_opt_reveal_pk_and_submit(
            namada,
            &args.tx,
            &[&args.voter_address],
            submit_vote_proposal_data,
        )
        .await?;
    }

    Ok(())
}

pub async fn submit_reveal_pk<N: Namada>(
    namada: &N,
    args: args::RevealPk,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    if let Some(dump_tx) = &args.tx.dump_tx {
        let tx_data =
            tx::build_reveal_pk(namada, &args.tx, &args.public_key).await?;
        tx::dump_tx(
            namada.io(),
            dump_tx.to_owned(),
            args.tx.output_folder,
            tx_data.0.clone(),
        )?;
    } else {
        let tx_data =
            submit_reveal_aux(namada, &args.tx, &(&args.public_key).into())
                .await?;

        if let Some((mut tx, signing_data)) = tx_data {
            sign(namada, &mut tx, &args.tx, signing_data).await?;
            namada.submit(tx, &args.tx).await?;
        }
    }

    Ok(())
}

pub async fn submit_bond<N: Namada>(
    namada: &N,
    args: args::Bond,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let submit_bond_tx_data = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(
            namada.io(),
            dump_tx,
            args.tx.output_folder,
            submit_bond_tx_data.0,
        )?;
    } else {
        let default_address = args.source.as_ref().unwrap_or(&args.validator);
        batch_opt_reveal_pk_and_submit(
            namada,
            &args.tx,
            &[default_address],
            submit_bond_tx_data,
        )
        .await?;
    }

    Ok(())
}

pub async fn submit_unbond<N: Namada>(
    namada: &N,
    args: args::Unbond,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data, latest_withdrawal_pre) =
        args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;
        let cmt = tx.first_commitments().unwrap().to_owned();
        let wrapper_hash = tx.wrapper_hash();
        let resp = namada.submit(tx, &args.tx).await?;

        if args.tx.dry_run.is_none()
            && resp
                .is_applied_and_valid(wrapper_hash.as_ref(), &cmt)
                .is_some()
        {
            tx::query_unbonds(namada, args.clone(), latest_withdrawal_pre)
                .await?;
        }
    }

    Ok(())
}

pub async fn submit_withdraw<N: Namada>(
    namada: &N,
    args: args::Withdraw,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

pub async fn submit_claim_rewards<N: Namada>(
    namada: &N,
    args: args::ClaimRewards,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

pub async fn submit_redelegate<N: Namada>(
    namada: &N,
    args: args::Redelegate,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

pub async fn submit_validator_commission_change<N: Namada>(
    namada: &N,
    args: args::CommissionRateChange,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

pub async fn submit_validator_metadata_change<N: Namada>(
    namada: &N,
    args: args::MetaDataChange,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

pub async fn submit_unjail_validator<N: Namada>(
    namada: &N,
    args: args::TxUnjailValidator,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

pub async fn submit_deactivate_validator<N: Namada>(
    namada: &N,
    args: args::TxDeactivateValidator,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

pub async fn submit_reactivate_validator<N: Namada>(
    namada: &N,
    args: args::TxReactivateValidator,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

pub async fn submit_update_steward_commission<N: Namada>(
    namada: &N,
    args: args::UpdateStewardCommission,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

pub async fn submit_resign_steward<N: Namada>(
    namada: &N,
    args: args::ResignSteward,
) -> Result<(), error::Error>
where
    <N::Client as namada_sdk::io::Client>::Error: std::fmt::Display,
{
    let (mut tx, signing_data) = args.build(namada).await?;

    if let Some(dump_tx) = args.tx.dump_tx {
        tx::dump_tx(namada.io(), dump_tx, args.tx.output_folder, tx)?;
    } else {
        sign(namada, &mut tx, &args.tx, signing_data).await?;

        namada.submit(tx, &args.tx).await?;
    }

    Ok(())
}

/// Save accounts initialized from a tx into the wallet, if any.
pub async fn save_initialized_accounts(
    namada: &impl Namada,
    args: &args::Tx,
    initialized_accounts: Vec<Address>,
) {
    tx::save_initialized_accounts(namada, args, initialized_accounts).await
}

/// Broadcast a transaction to be included in the blockchain and checks that
/// the tx has been successfully included into the mempool of a validator
///
/// In the case of errors in any of those stages, an error message is returned
pub async fn broadcast_tx(
    namada: &impl Namada,
    to_broadcast: &TxBroadcastData,
) -> Result<Response, error::Error> {
    tx::broadcast_tx(namada, to_broadcast).await
}

/// Broadcast a transaction to be included in the blockchain.
///
/// Checks that
/// 1. The tx has been successfully included into the mempool of a validator
/// 2. The tx has been included on the blockchain
///
/// In the case of errors in any of those stages, an error message is returned
pub async fn submit_tx(
    namada: &impl Namada,
    to_broadcast: TxBroadcastData,
) -> Result<TxResponse, error::Error> {
    tx::submit_tx(namada, to_broadcast).await
}

/// Generate MASP transaction and output it
pub async fn gen_ibc_shielding_transfer(
    context: &impl Namada,
    args: args::GenIbcShieldingTransfer,
) -> Result<(), error::Error> {
    let output_folder = args.output_folder.clone();

    if let Some(masp_tx) = tx::gen_ibc_shielding_transfer(context, args).await?
    {
        let tx_id = masp_tx.txid().to_string();
        let filename = format!("ibc_masp_tx_{}.memo", tx_id);
        let output_path = match output_folder {
            Some(path) => path.join(filename),
            None => filename.into(),
        };
        let mut out = File::create(&output_path)
            .expect("Creating a new file for IBC MASP transaction failed.");
        let bytes = convert_masp_tx_to_ibc_memo(&masp_tx);
        out.write_all(bytes.as_bytes())
            .expect("Writing IBC MASP transaction file failed.");
        println!(
            "Output IBC shielding transfer for {tx_id} to {}",
            output_path.to_string_lossy()
        );
    } else {
        eprintln!("No shielded transfer for this IBC transfer.")
    }
    Ok(())
}

// Pre-cache the data for the provided MASP transaction. Log an error on
// failure.
async fn pre_cache_masp_data(namada: &impl Namada, masp_tx: &MaspTransaction) {
    if let Err(e) = namada
        .shielded_mut()
        .await
        .pre_cache_transaction(masp_tx)
        .await
    {
        // Just display the error but do not propagate it
        edisplay_line!(namada.io(), "Failed to pre-cache masp data: {}.", e);
    }
}

// Check the result of a transaction and pre-cache the masp data accordingly
async fn pre_cache_masp_data_on_tx_result(
    namada: &impl Namada,
    tx_result: &ProcessTxResponse,
    masp_tx: &MaspTransaction,
) {
    match tx_result {
        ProcessTxResponse::Applied(resp) => {
            if let Some(InnerTxResult::Success(_)) =
                // If we have the masp data in an ibc transfer it
                // means we are unshielding, so there's no reveal pk
                // tx in the batch which contains only the ibc tx
                resp.batch_result().first().map(|(_, res)| res)
            {
                pre_cache_masp_data(namada, masp_tx).await;
            }
        }
        ProcessTxResponse::Broadcast(_) => {
            pre_cache_masp_data(namada, masp_tx).await;
        }
        // Do not pre-cache when dry-running
        ProcessTxResponse::DryRun(_) => {}
    }
}