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
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
#![allow(clippy::arithmetic_side_effects)]
use {
    crate::{
        bench::*,
        clap_app::*,
        config::{Config, MintInfo},
        encryption_keypair::*,
        output::*,
        sort::{sort_and_parse_token_accounts, AccountFilter},
    },
    clap::{value_t, value_t_or_exit, ArgMatches},
    futures::try_join,
    serde::Serialize,
    miraland_account_decoder::{
        parse_token::{get_token_account_mint, parse_token, TokenAccountType, UiAccountState},
        UiAccountData,
    },
    miraland_clap_utils::{
        input_parsers::{pubkey_of_signer, pubkeys_of_multiple_signers, value_of},
        keypair::signer_from_path,
    },
    miraland_cli_output::{
        return_signers_data, CliSignOnlyData, CliSignature, OutputFormat, QuietDisplay,
        ReturnSignersConfig, VerboseDisplay,
    },
    miraland_client::rpc_request::TokenAccountsFilter,
    miraland_remote_wallet::remote_wallet::RemoteWalletManager,
    solana_sdk::{
        instruction::AccountMeta,
        native_token::*,
        program_option::COption,
        pubkey::Pubkey,
        signature::{Keypair, Signer},
        system_program,
    },
    spl_associated_token_account::get_associated_token_address_with_program_id,
    spl_token_2022::{
        extension::{
            confidential_transfer::{
                account_info::{
                    ApplyPendingBalanceAccountInfo, TransferAccountInfo, WithdrawAccountInfo,
                },
                instruction::TransferSplitContextStateAccounts,
                ConfidentialTransferAccount, ConfidentialTransferMint,
            },
            confidential_transfer_fee::ConfidentialTransferFeeConfig,
            cpi_guard::CpiGuard,
            default_account_state::DefaultAccountState,
            interest_bearing_mint::InterestBearingConfig,
            memo_transfer::MemoTransfer,
            metadata_pointer::MetadataPointer,
            mint_close_authority::MintCloseAuthority,
            permanent_delegate::PermanentDelegate,
            transfer_fee::{TransferFeeAmount, TransferFeeConfig},
            transfer_hook::TransferHook,
            BaseStateWithExtensions, ExtensionType, StateWithExtensionsOwned,
        },
        solana_zk_token_sdk::{
            encryption::{
                auth_encryption::AeKey,
                elgamal::{self, ElGamalKeypair},
            },
            zk_token_elgamal::pod::ElGamalPubkey,
        },
        state::{Account, AccountState, Mint},
    },
    spl_token_client::{
        client::{ProgramRpcClientSendTransaction, RpcClientResponse},
        token::{ExtensionInitializationParams, Token},
    },
    spl_token_metadata_interface::state::{Field, TokenMetadata},
    std::{collections::HashMap, fmt::Display, process::exit, rc::Rc, str::FromStr, sync::Arc},
};

fn print_error_and_exit<T, E: Display>(e: E) -> T {
    eprintln!("error: {}", e);
    exit(1)
}

type BulkSigners = Vec<Arc<dyn Signer>>;
pub type CommandResult = Result<String, Error>;

fn push_signer_with_dedup(signer: Arc<dyn Signer>, bulk_signers: &mut BulkSigners) {
    if !bulk_signers.contains(&signer) {
        bulk_signers.push(signer);
    }
}

fn new_throwaway_signer() -> (Arc<dyn Signer>, Pubkey) {
    let keypair = Keypair::new();
    let pubkey = keypair.pubkey();
    (Arc::new(keypair) as Arc<dyn Signer>, pubkey)
}

fn get_signer(
    matches: &ArgMatches<'_>,
    keypair_name: &str,
    wallet_manager: &mut Option<Rc<RemoteWalletManager>>,
) -> Option<(Arc<dyn Signer>, Pubkey)> {
    matches.value_of(keypair_name).map(|path| {
        let signer = signer_from_path(matches, path, keypair_name, wallet_manager)
            .unwrap_or_else(print_error_and_exit);
        let signer_pubkey = signer.pubkey();
        (Arc::from(signer), signer_pubkey)
    })
}
async fn check_wallet_balance(
    config: &Config<'_>,
    wallet: &Pubkey,
    required_balance: u64,
) -> Result<(), Error> {
    let balance = config.rpc_client.get_balance(wallet).await?;
    if balance < required_balance {
        Err(format!(
            "Wallet {}, has insufficient balance: {} required, {} available",
            wallet,
            lamports_to_mln(required_balance),
            lamports_to_mln(balance)
        )
        .into())
    } else {
        Ok(())
    }
}

fn token_client_from_config(
    config: &Config<'_>,
    token_pubkey: &Pubkey,
    decimals: Option<u8>,
) -> Result<Token<ProgramRpcClientSendTransaction>, Error> {
    let token = Token::new(
        config.program_client.clone(),
        &config.program_id,
        token_pubkey,
        decimals,
        config.fee_payer()?.clone(),
    );

    if let (Some(nonce_account), Some(nonce_authority), Some(nonce_blockhash)) = (
        config.nonce_account,
        &config.nonce_authority,
        config.nonce_blockhash,
    ) {
        Ok(token.with_nonce(
            &nonce_account,
            Arc::clone(nonce_authority),
            &nonce_blockhash,
        ))
    } else {
        Ok(token)
    }
}

fn native_token_client_from_config(
    config: &Config<'_>,
) -> Result<Token<ProgramRpcClientSendTransaction>, Error> {
    let token = Token::new_native(
        config.program_client.clone(),
        &config.program_id,
        config.fee_payer()?.clone(),
    );

    if let (Some(nonce_account), Some(nonce_authority), Some(nonce_blockhash)) = (
        config.nonce_account,
        &config.nonce_authority,
        config.nonce_blockhash,
    ) {
        Ok(token.with_nonce(
            &nonce_account,
            Arc::clone(nonce_authority),
            &nonce_blockhash,
        ))
    } else {
        Ok(token)
    }
}

#[allow(clippy::too_many_arguments)]
async fn command_create_token(
    config: &Config<'_>,
    decimals: u8,
    token_pubkey: Pubkey,
    authority: Pubkey,
    enable_freeze: bool,
    enable_close: bool,
    enable_non_transferable: bool,
    enable_permanent_delegate: bool,
    memo: Option<String>,
    metadata_address: Option<Pubkey>,
    rate_bps: Option<i16>,
    default_account_state: Option<AccountState>,
    transfer_fee: Option<(u16, u64)>,
    confidential_transfer_auto_approve: Option<bool>,
    transfer_hook_program_id: Option<Pubkey>,
    enable_metadata: bool,
    bulk_signers: Vec<Arc<dyn Signer>>,
) -> CommandResult {
    println_display(
        config,
        format!(
            "Creating token {} under program {}",
            token_pubkey, config.program_id
        ),
    );

    let token = token_client_from_config(config, &token_pubkey, Some(decimals))?;

    let freeze_authority = if enable_freeze { Some(authority) } else { None };

    let mut extensions = vec![];

    if enable_close {
        extensions.push(ExtensionInitializationParams::MintCloseAuthority {
            close_authority: Some(authority),
        });
    }

    if enable_permanent_delegate {
        extensions.push(ExtensionInitializationParams::PermanentDelegate {
            delegate: authority,
        });
    }

    if let Some(rate_bps) = rate_bps {
        extensions.push(ExtensionInitializationParams::InterestBearingConfig {
            rate_authority: Some(authority),
            rate: rate_bps,
        })
    }

    if enable_non_transferable {
        extensions.push(ExtensionInitializationParams::NonTransferable);
    }

    if let Some(state) = default_account_state {
        assert!(
            enable_freeze,
            "Token requires a freeze authority to default to frozen accounts"
        );
        extensions.push(ExtensionInitializationParams::DefaultAccountState { state })
    }

    if let Some((transfer_fee_basis_points, maximum_fee)) = transfer_fee {
        extensions.push(ExtensionInitializationParams::TransferFeeConfig {
            transfer_fee_config_authority: Some(authority),
            withdraw_withheld_authority: Some(authority),
            transfer_fee_basis_points,
            maximum_fee,
        });
    }

    if let Some(auto_approve) = confidential_transfer_auto_approve {
        extensions.push(ExtensionInitializationParams::ConfidentialTransferMint {
            authority: Some(authority),
            auto_approve_new_accounts: auto_approve,
            auditor_elgamal_pubkey: None,
        });
    }

    if let Some(program_id) = transfer_hook_program_id {
        extensions.push(ExtensionInitializationParams::TransferHook {
            authority: Some(authority),
            program_id: Some(program_id),
        });
    }

    if let Some(text) = memo {
        token.with_memo(text, vec![config.default_signer()?.pubkey()]);
    }

    // CLI checks that only one is set
    if metadata_address.is_some() || enable_metadata {
        let metadata_address = if enable_metadata {
            Some(token_pubkey)
        } else {
            metadata_address
        };
        extensions.push(ExtensionInitializationParams::MetadataPointer {
            authority: Some(authority),
            metadata_address,
        });
    }

    let res = token
        .create_mint(
            &authority,
            freeze_authority.as_ref(),
            extensions,
            &bulk_signers,
        )
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;

    if enable_metadata {
        println_display(
            config,
            format!(
                "To initialize metadata inside the mint, please run \
                `spl-token initialize-metadata {token_pubkey} <YOUR_TOKEN_NAME> <YOUR_TOKEN_SYMBOL> <YOUR_TOKEN_URI>`, \
                and sign with the mint authority.",
            ),
        );
    }

    Ok(match tx_return {
        TransactionReturnData::CliSignature(cli_signature) => format_output(
            CliCreateToken {
                address: token_pubkey.to_string(),
                decimals,
                transaction_data: cli_signature,
            },
            &CommandName::CreateToken,
            config,
        ),
        TransactionReturnData::CliSignOnlyData(cli_sign_only_data) => {
            format_output(cli_sign_only_data, &CommandName::CreateToken, config)
        }
    })
}

async fn command_set_interest_rate(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    rate_authority: Pubkey,
    rate_bps: i16,
    bulk_signers: Vec<Arc<dyn Signer>>,
) -> CommandResult {
    let token = token_client_from_config(config, &token_pubkey, None)?;

    if !config.sign_only {
        let mint_account = config.get_account_checked(&token_pubkey).await?;

        let mint_state = StateWithExtensionsOwned::<Mint>::unpack(mint_account.data)
            .map_err(|_| format!("Could not deserialize token mint {}", token_pubkey))?;

        if let Ok(interest_rate_config) = mint_state.get_extension::<InterestBearingConfig>() {
            let mint_rate_authority_pubkey =
                Option::<Pubkey>::from(interest_rate_config.rate_authority);

            if mint_rate_authority_pubkey != Some(rate_authority) {
                return Err(format!(
                    "Mint {} has interest rate authority {}, but {} was provided",
                    token_pubkey,
                    mint_rate_authority_pubkey
                        .map(|pubkey| pubkey.to_string())
                        .unwrap_or_else(|| "disabled".to_string()),
                    rate_authority
                )
                .into());
            }
        } else {
            return Err(format!("Mint {} is not interest-bearing", token_pubkey).into());
        }
    }

    println_display(
        config,
        format!(
            "Setting Interest Rate for {} to {} bps",
            token_pubkey, rate_bps
        ),
    );

    let res = token
        .update_interest_rate(&rate_authority, rate_bps, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_set_transfer_hook_program(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    authority: Pubkey,
    new_program_id: Option<Pubkey>,
    bulk_signers: Vec<Arc<dyn Signer>>,
) -> CommandResult {
    let token = token_client_from_config(config, &token_pubkey, None)?;

    if !config.sign_only {
        let mint_account = config.get_account_checked(&token_pubkey).await?;

        let mint_state = StateWithExtensionsOwned::<Mint>::unpack(mint_account.data)
            .map_err(|_| format!("Could not deserialize token mint {}", token_pubkey))?;

        if let Ok(extension) = mint_state.get_extension::<TransferHook>() {
            let authority_pubkey = Option::<Pubkey>::from(extension.authority);

            if authority_pubkey != Some(authority) {
                return Err(format!(
                    "Mint {} has transfer hook authority {}, but {} was provided",
                    token_pubkey,
                    authority_pubkey
                        .map(|pubkey| pubkey.to_string())
                        .unwrap_or_else(|| "disabled".to_string()),
                    authority
                )
                .into());
            }
        } else {
            return Err(
                format!("Mint {} does not have permissioned-transfers", token_pubkey).into(),
            );
        }
    }

    println_display(
        config,
        format!(
            "Setting Transfer Hook Program id for {} to {}",
            token_pubkey,
            new_program_id
                .map(|pubkey| pubkey.to_string())
                .unwrap_or_else(|| "disabled".to_string())
        ),
    );

    let res = token
        .update_transfer_hook_program_id(&authority, new_program_id, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

#[allow(clippy::too_many_arguments)]
async fn command_initialize_metadata(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    update_authority: Pubkey,
    mint_authority: Pubkey,
    name: String,
    symbol: String,
    uri: String,
    bulk_signers: Vec<Arc<dyn Signer>>,
) -> CommandResult {
    let token = token_client_from_config(config, &token_pubkey, None)?;

    let res = token
        .token_metadata_initialize_with_rent_transfer(
            &config.fee_payer()?.pubkey(),
            &update_authority,
            &mint_authority,
            name,
            symbol,
            uri,
            &bulk_signers,
        )
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_update_metadata(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    authority: Pubkey,
    field: Field,
    value: Option<String>,
    transfer_lamports: Option<u64>,
    bulk_signers: Vec<Arc<dyn Signer>>,
) -> CommandResult {
    let token = token_client_from_config(config, &token_pubkey, None)?;

    let res = if let Some(value) = value {
        token
            .token_metadata_update_field_with_rent_transfer(
                &config.fee_payer()?.pubkey(),
                &authority,
                field,
                value,
                transfer_lamports,
                &bulk_signers,
            )
            .await?
    } else if let Field::Key(key) = field {
        token
            .token_metadata_remove_key(
                &authority,
                key,
                true, // idempotent
                &bulk_signers,
            )
            .await?
    } else {
        return Err(format!(
            "Attempting to remove field {field:?}, which cannot be removed. \
            Please re-run the command with a value of \"\" rather than the `--remove` flag."
        )
        .into());
    };

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_set_transfer_fee(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    transfer_fee_authority: Pubkey,
    transfer_fee_basis_points: u16,
    maximum_fee: f64,
    mint_decimals: Option<u8>,
    bulk_signers: Vec<Arc<dyn Signer>>,
) -> CommandResult {
    let decimals = if !config.sign_only {
        let mint_account = config.get_account_checked(&token_pubkey).await?;

        let mint_state = StateWithExtensionsOwned::<Mint>::unpack(mint_account.data)
            .map_err(|_| format!("Could not deserialize token mint {}", token_pubkey))?;

        if mint_decimals.is_some() && mint_decimals != Some(mint_state.base.decimals) {
            return Err(format!(
                "Decimals {} was provided, but actual value is {}",
                mint_decimals.unwrap(),
                mint_state.base.decimals
            )
            .into());
        }

        if let Ok(transfer_fee_config) = mint_state.get_extension::<TransferFeeConfig>() {
            let mint_fee_authority_pubkey =
                Option::<Pubkey>::from(transfer_fee_config.transfer_fee_config_authority);

            if mint_fee_authority_pubkey != Some(transfer_fee_authority) {
                return Err(format!(
                    "Mint {} has transfer fee authority {}, but {} was provided",
                    token_pubkey,
                    mint_fee_authority_pubkey
                        .map(|pubkey| pubkey.to_string())
                        .unwrap_or_else(|| "disabled".to_string()),
                    transfer_fee_authority
                )
                .into());
            }
        } else {
            return Err(format!("Mint {} does not have a transfer fee", token_pubkey).into());
        }
        mint_state.base.decimals
    } else {
        mint_decimals.unwrap()
    };

    println_display(
        config,
        format!(
            "Setting transfer fee for {} to {} bps, {} maximum",
            token_pubkey, transfer_fee_basis_points, maximum_fee
        ),
    );

    let token = token_client_from_config(config, &token_pubkey, Some(decimals))?;
    let maximum_fee = spl_token::ui_amount_to_amount(maximum_fee, decimals);
    let res = token
        .set_transfer_fee(
            &transfer_fee_authority,
            transfer_fee_basis_points,
            maximum_fee,
            &bulk_signers,
        )
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_create_account(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    owner: Pubkey,
    maybe_account: Option<Pubkey>,
    immutable_owner: bool,
    bulk_signers: Vec<Arc<dyn Signer>>,
) -> CommandResult {
    let token = token_client_from_config(config, &token_pubkey, None)?;
    let mut extensions = vec![];

    let (account, is_associated) = if let Some(account) = maybe_account {
        (
            account,
            token.get_associated_token_address(&owner) == account,
        )
    } else {
        (token.get_associated_token_address(&owner), true)
    };

    println_display(config, format!("Creating account {}", account));

    if !config.sign_only {
        if let Some(account_data) = config.program_client.get_account(account).await? {
            if account_data.owner != system_program::id() || !is_associated {
                return Err(format!("Error: Account already exists: {}", account).into());
            }
        }
    }

    if immutable_owner {
        if config.program_id == spl_token::id() {
            return Err(format!(
                "Specified --immutable, but token program {} does not support the extension",
                config.program_id
            )
            .into());
        } else if is_associated {
            println_display(
                config,
                "Note: --immutable specified, but Token-2022 ATAs are always immutable, ignoring"
                    .to_string(),
            );
        } else {
            extensions.push(ExtensionType::ImmutableOwner);
        }
    }

    let res = if is_associated {
        token.create_associated_token_account(&owner).await
    } else {
        let signer = bulk_signers
            .iter()
            .find(|signer| signer.pubkey() == account)
            .unwrap_or_else(|| panic!("No signer provided for account {}", account));

        token
            .create_auxiliary_token_account_with_extension_space(&**signer, &owner, extensions)
            .await
    }?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_create_multisig(
    config: &Config<'_>,
    multisig: Arc<dyn Signer>,
    minimum_signers: u8,
    multisig_members: Vec<Pubkey>,
) -> CommandResult {
    println_display(
        config,
        format!(
            "Creating {}/{} multisig {} under program {}",
            minimum_signers,
            multisig_members.len(),
            multisig.pubkey(),
            config.program_id,
        ),
    );

    // default is safe here because create_multisig doesnt use it
    let token = token_client_from_config(config, &Pubkey::default(), None)?;

    let res = token
        .create_multisig(
            &*multisig,
            &multisig_members.iter().collect::<Vec<_>>(),
            minimum_signers,
        )
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

#[allow(clippy::too_many_arguments)]
async fn command_authorize(
    config: &Config<'_>,
    account: Pubkey,
    authority_type: CliAuthorityType,
    authority: Pubkey,
    new_authority: Option<Pubkey>,
    force_authorize: bool,
    bulk_signers: BulkSigners,
) -> CommandResult {
    let auth_str: &'static str = (&authority_type).into();

    let (mint_pubkey, previous_authority) = if !config.sign_only {
        let target_account = config.get_account_checked(&account).await?;

        let (mint_pubkey, previous_authority) = if let Ok(mint) =
            StateWithExtensionsOwned::<Mint>::unpack(target_account.data.clone())
        {
            let previous_authority = match authority_type {
                CliAuthorityType::Owner | CliAuthorityType::Close => Err(format!(
                    "Authority type `{}` not supported for SPL Token mints",
                    auth_str
                )),
                CliAuthorityType::Mint => Ok(Option::<Pubkey>::from(mint.base.mint_authority)),
                CliAuthorityType::Freeze => Ok(Option::<Pubkey>::from(mint.base.freeze_authority)),
                CliAuthorityType::CloseMint => {
                    if let Ok(mint_close_authority) = mint.get_extension::<MintCloseAuthority>() {
                        Ok(Option::<Pubkey>::from(mint_close_authority.close_authority))
                    } else {
                        Err(format!(
                            "Mint `{}` does not support close authority",
                            account
                        ))
                    }
                }
                CliAuthorityType::TransferFeeConfig => {
                    if let Ok(transfer_fee_config) = mint.get_extension::<TransferFeeConfig>() {
                        Ok(Option::<Pubkey>::from(
                            transfer_fee_config.transfer_fee_config_authority,
                        ))
                    } else {
                        Err(format!("Mint `{}` does not support transfer fees", account))
                    }
                }
                CliAuthorityType::WithheldWithdraw => {
                    if let Ok(transfer_fee_config) = mint.get_extension::<TransferFeeConfig>() {
                        Ok(Option::<Pubkey>::from(
                            transfer_fee_config.withdraw_withheld_authority,
                        ))
                    } else {
                        Err(format!("Mint `{}` does not support transfer fees", account))
                    }
                }
                CliAuthorityType::InterestRate => {
                    if let Ok(interest_rate_config) = mint.get_extension::<InterestBearingConfig>()
                    {
                        Ok(Option::<Pubkey>::from(interest_rate_config.rate_authority))
                    } else {
                        Err(format!("Mint `{}` is not interest-bearing", account))
                    }
                }
                CliAuthorityType::PermanentDelegate => {
                    if let Ok(permanent_delegate) = mint.get_extension::<PermanentDelegate>() {
                        Ok(Option::<Pubkey>::from(permanent_delegate.delegate))
                    } else {
                        Err(format!(
                            "Mint `{}` does not support permanent delegate",
                            account
                        ))
                    }
                }
                CliAuthorityType::ConfidentialTransferMint => {
                    if let Ok(confidential_transfer_mint) =
                        mint.get_extension::<ConfidentialTransferMint>()
                    {
                        Ok(Option::<Pubkey>::from(confidential_transfer_mint.authority))
                    } else {
                        Err(format!(
                            "Mint `{}` does not support confidential transfers",
                            account
                        ))
                    }
                }
                CliAuthorityType::TransferHookProgramId => {
                    if let Ok(extension) = mint.get_extension::<TransferHook>() {
                        Ok(Option::<Pubkey>::from(extension.authority))
                    } else {
                        Err(format!(
                            "Mint `{}` does not support a transfer hook program",
                            account
                        ))
                    }
                }
                CliAuthorityType::ConfidentialTransferFee => {
                    if let Ok(confidential_transfer_fee_config) =
                        mint.get_extension::<ConfidentialTransferFeeConfig>()
                    {
                        Ok(Option::<Pubkey>::from(
                            confidential_transfer_fee_config.authority,
                        ))
                    } else {
                        Err(format!(
                            "Mint `{}` does not support confidential transfer fees",
                            account
                        ))
                    }
                }
                CliAuthorityType::MetadataPointer => {
                    if let Ok(extension) = mint.get_extension::<MetadataPointer>() {
                        Ok(Option::<Pubkey>::from(extension.authority))
                    } else {
                        Err(format!(
                            "Mint `{}` does not support a metadata pointer",
                            account
                        ))
                    }
                }
                CliAuthorityType::Metadata => {
                    if let Ok(extension) = mint.get_variable_len_extension::<TokenMetadata>() {
                        Ok(Option::<Pubkey>::from(extension.update_authority))
                    } else {
                        Err(format!("Mint `{account}` does not support metadata"))
                    }
                }
            }?;

            Ok((account, previous_authority))
        } else if let Ok(token_account) =
            StateWithExtensionsOwned::<Account>::unpack(target_account.data)
        {
            let check_associated_token_account = || -> Result<(), Error> {
                let maybe_associated_token_account = get_associated_token_address_with_program_id(
                    &token_account.base.owner,
                    &token_account.base.mint,
                    &config.program_id,
                );
                if account == maybe_associated_token_account
                    && !force_authorize
                    && Some(authority) != new_authority
                {
                    Err(format!(
                        "Error: attempting to change the `{}` of an associated token account",
                        auth_str
                    )
                    .into())
                } else {
                    Ok(())
                }
            };

            let previous_authority = match authority_type {
                CliAuthorityType::Mint
                | CliAuthorityType::Freeze
                | CliAuthorityType::CloseMint
                | CliAuthorityType::TransferFeeConfig
                | CliAuthorityType::WithheldWithdraw
                | CliAuthorityType::InterestRate
                | CliAuthorityType::PermanentDelegate
                | CliAuthorityType::ConfidentialTransferMint
                | CliAuthorityType::TransferHookProgramId
                | CliAuthorityType::ConfidentialTransferFee
                | CliAuthorityType::MetadataPointer
                | CliAuthorityType::Metadata => Err(format!(
                    "Authority type `{auth_str}` not supported for SPL Token accounts",
                )),
                CliAuthorityType::Owner => {
                    check_associated_token_account()?;
                    Ok(Some(token_account.base.owner))
                }
                CliAuthorityType::Close => {
                    check_associated_token_account()?;
                    Ok(Some(
                        token_account
                            .base
                            .close_authority
                            .unwrap_or(token_account.base.owner),
                    ))
                }
            }?;

            Ok((token_account.base.mint, previous_authority))
        } else {
            Err("Unsupported account data format".to_string())
        }?;

        (mint_pubkey, previous_authority)
    } else {
        // default is safe here because authorize doesnt use it
        (Pubkey::default(), None)
    };

    let token = token_client_from_config(config, &mint_pubkey, None)?;

    println_display(
        config,
        format!(
            "Updating {}\n  Current {}: {}\n  New {}: {}",
            account,
            auth_str,
            previous_authority
                .map(|pubkey| pubkey.to_string())
                .unwrap_or_else(|| if config.sign_only {
                    "unknown".to_string()
                } else {
                    "disabled".to_string()
                }),
            auth_str,
            new_authority
                .map(|pubkey| pubkey.to_string())
                .unwrap_or_else(|| "disabled".to_string())
        ),
    );

    let res = if let CliAuthorityType::Metadata = authority_type {
        token
            .token_metadata_update_authority(&authority, new_authority, &bulk_signers)
            .await?
    } else {
        token
            .set_authority(
                &account,
                &authority,
                new_authority.as_ref(),
                authority_type.try_into()?,
                &bulk_signers,
            )
            .await?
    };

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

#[allow(clippy::too_many_arguments)]
async fn command_transfer(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    ui_amount: Option<f64>,
    recipient: Pubkey,
    sender: Option<Pubkey>,
    sender_owner: Pubkey,
    allow_unfunded_recipient: bool,
    fund_recipient: bool,
    mint_decimals: Option<u8>,
    no_recipient_is_ata_owner: bool,
    use_unchecked_instruction: bool,
    ui_fee: Option<f64>,
    memo: Option<String>,
    bulk_signers: BulkSigners,
    no_wait: bool,
    allow_non_system_account_recipient: bool,
    transfer_hook_accounts: Option<Vec<AccountMeta>>,
    confidential_transfer_args: Option<&ConfidentialTransferArgs>,
) -> CommandResult {
    let mint_info = config.get_mint_info(&token_pubkey, mint_decimals).await?;

    // if the user got the decimals wrong, they may well have calculated the
    // transfer amount wrong we only check in online mode, because in offline,
    // mint_info.decimals is always 9
    if !config.sign_only && mint_decimals.is_some() && mint_decimals != Some(mint_info.decimals) {
        return Err(format!(
            "Decimals {} was provided, but actual value is {}",
            mint_decimals.unwrap(),
            mint_info.decimals
        )
        .into());
    }

    // decimals determines whether transfer_checked is used or not
    // in online mode, mint_decimals may be None but mint_info.decimals is always
    // correct in offline mode, mint_info.decimals may be wrong, but
    // mint_decimals is always provided and in online mode, when mint_decimals
    // is provided, it is verified correct hence the fallthrough logic here
    let decimals = if use_unchecked_instruction {
        None
    } else if mint_decimals.is_some() {
        mint_decimals
    } else {
        Some(mint_info.decimals)
    };

    let token = if let Some(transfer_hook_accounts) = transfer_hook_accounts {
        token_client_from_config(config, &token_pubkey, decimals)?
            .with_transfer_hook_accounts(transfer_hook_accounts)
    } else {
        token_client_from_config(config, &token_pubkey, decimals)?
    };

    // pubkey of the actual account we are sending from
    let sender = if let Some(sender) = sender {
        sender
    } else {
        token.get_associated_token_address(&sender_owner)
    };

    // the amount the user wants to tranfer, as a f64
    let maybe_transfer_balance =
        ui_amount.map(|ui_amount| spl_token::ui_amount_to_amount(ui_amount, mint_info.decimals));

    // the amount we will transfer, as a u64
    let transfer_balance = if !config.sign_only {
        let sender_balance = token.get_account_info(&sender).await?.base.amount;
        let transfer_balance = maybe_transfer_balance.unwrap_or(sender_balance);

        println_display(
            config,
            format!(
                "{}Transfer {} tokens\n  Sender: {}\n  Recipient: {}",
                if confidential_transfer_args.is_some() {
                    "Confidential "
                } else {
                    ""
                },
                spl_token::amount_to_ui_amount(transfer_balance, mint_info.decimals),
                sender,
                recipient
            ),
        );

        if transfer_balance > sender_balance && confidential_transfer_args.is_none() {
            return Err(format!(
                "Error: Sender has insufficient funds, current balance is {}",
                spl_token_2022::amount_to_ui_amount_string_trimmed(
                    sender_balance,
                    mint_info.decimals
                )
            )
            .into());
        }

        transfer_balance
    } else {
        maybe_transfer_balance.unwrap()
    };

    let maybe_fee =
        ui_fee.map(|ui_amount| spl_token::ui_amount_to_amount(ui_amount, mint_info.decimals));

    // determine whether recipient is a token account or an expected owner of one
    let recipient_is_token_account = if !config.sign_only {
        // in online mode we can fetch it and see
        let maybe_recipient_account_data = config.program_client.get_account(recipient).await?;

        // if the account exists, and:
        // * its a token for this program, we are happy
        // * its a system account, we are happy
        // * its a non-account for this program, we error helpfully
        // * its a token account for a different program, we error helpfully
        // * otherwise its probabaly a program account owner of an ata, in which case we
        //   gate transfer with a flag
        if let Some(recipient_account_data) = maybe_recipient_account_data {
            let recipient_account_owner = recipient_account_data.owner;
            let maybe_account_state =
                StateWithExtensionsOwned::<Account>::unpack(recipient_account_data.data);

            if recipient_account_owner == config.program_id && maybe_account_state.is_ok() {
                if let Ok(memo_transfer) = maybe_account_state?.get_extension::<MemoTransfer>() {
                    if memo_transfer.require_incoming_transfer_memos.into() && memo.is_none() {
                        return Err(
                            "Error: Recipient expects a transfer memo, but none was provided. \
                                    Provide a memo using `--with-memo`."
                                .into(),
                        );
                    }
                }

                true
            } else if recipient_account_owner == system_program::id() {
                false
            } else if recipient_account_owner == config.program_id {
                return Err(
                    "Error: Recipient is owned by this token program, but is not a token account."
                        .into(),
                );
            } else if VALID_TOKEN_PROGRAM_IDS.contains(&recipient_account_owner) {
                return Err(format!(
                    "Error: Recipient is owned by {}, but the token mint is owned by {}.",
                    recipient_account_owner, config.program_id
                )
                .into());
            } else if allow_non_system_account_recipient {
                false
            } else {
                return Err("Error: The recipient address is not owned by the System Program. \
                                     Add `--allow-non-system-account-recipient` to complete the transfer.".into());
            }
        }
        // if it doesnt exist, it definitely isnt a token account!
        // we gate transfer with a different flag
        else if maybe_recipient_account_data.is_none() && allow_unfunded_recipient {
            false
        } else {
            return Err("Error: The recipient address is not funded. \
                        Add `--allow-unfunded-recipient` to complete the transfer."
                .into());
        }
    } else {
        // in offline mode we gotta trust them
        no_recipient_is_ata_owner
    };

    // now if its a token account, life is ez
    let (recipient_token_account, fundable_owner) = if recipient_is_token_account {
        (recipient, None)
    }
    // but if not, we need to determine if we can or should create an ata for recipient
    else {
        // first, get the ata address
        let recipient_token_account = token.get_associated_token_address(&recipient);

        println_display(
            config,
            format!(
                "  Recipient associated token account: {}",
                recipient_token_account
            ),
        );

        // if we can fetch it to determine if it exists, do so
        let needs_funding = if !config.sign_only {
            if let Some(recipient_token_account_data) = config
                .program_client
                .get_account(recipient_token_account)
                .await?
            {
                let recipient_token_account_owner = recipient_token_account_data.owner;

                if let Ok(account_state) =
                    StateWithExtensionsOwned::<Account>::unpack(recipient_token_account_data.data)
                {
                    if let Ok(memo_transfer) = account_state.get_extension::<MemoTransfer>() {
                        if memo_transfer.require_incoming_transfer_memos.into() && memo.is_none() {
                            return Err(
                                "Error: Recipient expects a transfer memo, but none was provided. \
                                        Provide a memo using `--with-memo`."
                                    .into(),
                            );
                        }
                    }
                }

                if recipient_token_account_owner == system_program::id() {
                    true
                } else if recipient_token_account_owner == config.program_id {
                    false
                } else {
                    return Err(
                        format!("Error: Unsupported recipient address: {}", recipient).into(),
                    );
                }
            } else {
                true
            }
        }
        // otherwise trust the cli flag
        else {
            fund_recipient
        };

        // and now we determine if we will actually fund it, based on its need and our
        // willingness
        let fundable_owner = if needs_funding {
            if confidential_transfer_args.is_some() {
                return Err(
                    "Error: Recipient's associated token account does not exist. \
                        Accounts cannot be funded for confidential transfers."
                        .into(),
                );
            } else if fund_recipient {
                println_display(
                    config,
                    format!("  Funding recipient: {}", recipient_token_account,),
                );

                Some(recipient)
            } else {
                return Err(
                    "Error: Recipient's associated token account does not exist. \
                                    Add `--fund-recipient` to fund their account"
                        .into(),
                );
            }
        } else {
            None
        };

        (recipient_token_account, fundable_owner)
    };

    // set up memo if provided...
    if let Some(text) = memo {
        token.with_memo(text, vec![config.default_signer()?.pubkey()]);
    }

    // fetch confidential transfer info for recipient and auditor
    let (recipient_elgamal_pubkey, auditor_elgamal_pubkey) = if let Some(args) =
        confidential_transfer_args
    {
        if !config.sign_only {
            // we can use the mint data from the start of the function, but will require
            // non-trivial amount of refactoring the code due to ownership; for now, we
            // fetch the mint a second time. This can potentially be optimized
            // in the future.
            let confidential_transfer_mint = config.get_account_checked(&token_pubkey).await?;
            let mint_state =
                StateWithExtensionsOwned::<Mint>::unpack(confidential_transfer_mint.data)
                    .map_err(|_| format!("Could not deserialize token mint {}", token_pubkey))?;

            let auditor_elgamal_pubkey = if let Ok(confidential_transfer_mint) =
                mint_state.get_extension::<ConfidentialTransferMint>()
            {
                let expected_auditor_elgamal_pubkey = Option::<ElGamalPubkey>::from(
                    confidential_transfer_mint.auditor_elgamal_pubkey,
                );

                // if auditor ElGamal pubkey is provided, check consistency with the one in the
                // mint if auditor ElGamal pubkey is not provided, then use the
                // expected one from the   mint, which could also be `None` if
                // auditing is disabled
                if args.auditor_elgamal_pubkey.is_some()
                    && expected_auditor_elgamal_pubkey != args.auditor_elgamal_pubkey
                {
                    return Err(format!(
                        "Mint {} has confidential transfer auditor {}, but {} was provided",
                        token_pubkey,
                        expected_auditor_elgamal_pubkey
                            .map(|pubkey| pubkey.to_string())
                            .unwrap_or_else(|| "disabled".to_string()),
                        args.auditor_elgamal_pubkey.unwrap(),
                    )
                    .into());
                }

                expected_auditor_elgamal_pubkey
            } else {
                return Err(format!(
                    "Mint {} does not support confidential transfers",
                    token_pubkey
                )
                .into());
            };

            let recipient_account = config.get_account_checked(&recipient_token_account).await?;
            let recipient_elgamal_pubkey =
                StateWithExtensionsOwned::<Account>::unpack(recipient_account.data)?
                    .get_extension::<ConfidentialTransferAccount>()?
                    .elgamal_pubkey;

            (Some(recipient_elgamal_pubkey), auditor_elgamal_pubkey)
        } else {
            let recipient_elgamal_pubkey = args
                .recipient_elgamal_pubkey
                .expect("Recipient ElGamal pubkey must be provided");
            let auditor_elgamal_pubkey = args
                .auditor_elgamal_pubkey
                .expect("Auditor ElGamal pubkey must be provided");

            (Some(recipient_elgamal_pubkey), Some(auditor_elgamal_pubkey))
        }
    } else {
        (None, None)
    };

    // ...and, finally, the transfer
    let res = match (fundable_owner, maybe_fee, confidential_transfer_args) {
        (Some(recipient_owner), None, None) => {
            token
                .create_recipient_associated_account_and_transfer(
                    &sender,
                    &recipient_token_account,
                    &recipient_owner,
                    &sender_owner,
                    transfer_balance,
                    maybe_fee,
                    &bulk_signers,
                )
                .await?
        }
        (Some(_), _, _) => {
            panic!("Recipient account cannot be created for transfer with fees or confidential transfers");
        }
        (None, Some(fee), None) => {
            token
                .transfer_with_fee(
                    &sender,
                    &recipient_token_account,
                    &sender_owner,
                    transfer_balance,
                    fee,
                    &bulk_signers,
                )
                .await?
        }
        (None, None, Some(args)) => {
            // deserialize `pod` ElGamal pubkeys
            let recipient_elgamal_pubkey: elgamal::ElGamalPubkey = recipient_elgamal_pubkey
                .unwrap()
                .try_into()
                .expect("Invalid recipient ElGamal pubkey");
            let auditor_elgamal_pubkey = auditor_elgamal_pubkey.map(|pubkey| {
                let auditor_elgamal_pubkey: elgamal::ElGamalPubkey =
                    pubkey.try_into().expect("Invalid auditor ElGamal pubkey");
                auditor_elgamal_pubkey
            });

            let context_state_authority = config.fee_payer()?;
            let equality_proof_context_state_account = Keypair::new();
            let equality_proof_pubkey = equality_proof_context_state_account.pubkey();
            let ciphertext_validity_proof_context_state_account = Keypair::new();
            let ciphertext_validity_proof_pubkey =
                ciphertext_validity_proof_context_state_account.pubkey();
            let range_proof_context_state_account = Keypair::new();
            let range_proof_pubkey = range_proof_context_state_account.pubkey();

            let transfer_context_state_accounts = TransferSplitContextStateAccounts {
                equality_proof: &equality_proof_pubkey,
                ciphertext_validity_proof: &ciphertext_validity_proof_pubkey,
                range_proof: &range_proof_pubkey,
                authority: &context_state_authority.pubkey(),
                no_op_on_uninitialized_split_context_state: false,
                close_split_context_state_accounts: None,
            };

            let state = token.get_account_info(&sender).await.unwrap();
            let extension = state
                .get_extension::<ConfidentialTransferAccount>()
                .unwrap();
            let transfer_account_info = TransferAccountInfo::new(extension);

            let (
                equality_proof_data,
                ciphertext_validity_proof_data,
                range_proof_data,
                source_decrypt_handles,
            ) = transfer_account_info
                .generate_split_transfer_proof_data(
                    transfer_balance,
                    &args.sender_elgamal_keypair,
                    &args.sender_aes_key,
                    &recipient_elgamal_pubkey,
                    auditor_elgamal_pubkey.as_ref(),
                )
                .unwrap();

            // setup proofs
            let _ = try_join!(
                token.create_range_proof_context_state_for_transfer(
                    transfer_context_state_accounts,
                    &range_proof_data,
                    &range_proof_context_state_account,
                ),
                token.create_equality_proof_context_state_for_transfer(
                    transfer_context_state_accounts,
                    &equality_proof_data,
                    &equality_proof_context_state_account,
                ),
                token.create_ciphertext_validity_proof_context_state_for_transfer(
                    transfer_context_state_accounts,
                    &ciphertext_validity_proof_data,
                    &ciphertext_validity_proof_context_state_account,
                )
            )?;

            // do the transfer
            let transfer_result = token
                .confidential_transfer_transfer_with_split_proofs(
                    &sender,
                    &recipient_token_account,
                    &sender_owner,
                    transfer_context_state_accounts,
                    transfer_balance,
                    Some(transfer_account_info),
                    &args.sender_aes_key,
                    &source_decrypt_handles,
                    &bulk_signers,
                )
                .await?;

            // close context state accounts
            let context_state_authority_pubkey = context_state_authority.pubkey();
            let close_context_state_signers = &[context_state_authority];
            let _ = try_join!(
                token.confidential_transfer_close_context_state(
                    &equality_proof_pubkey,
                    &sender,
                    &context_state_authority_pubkey,
                    close_context_state_signers,
                ),
                token.confidential_transfer_close_context_state(
                    &ciphertext_validity_proof_pubkey,
                    &sender,
                    &context_state_authority_pubkey,
                    close_context_state_signers,
                ),
                token.confidential_transfer_close_context_state(
                    &range_proof_pubkey,
                    &sender,
                    &context_state_authority_pubkey,
                    close_context_state_signers,
                ),
            )?;

            transfer_result
        }
        (None, Some(_), Some(_)) => {
            panic!("Confidential transfer with fee is not yet supported.");
        }
        (None, None, None) => {
            token
                .transfer(
                    &sender,
                    &recipient_token_account,
                    &sender_owner,
                    transfer_balance,
                    &bulk_signers,
                )
                .await?
        }
    };

    let tx_return = finish_tx(config, &res, no_wait).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

#[allow(clippy::too_many_arguments)]
async fn command_burn(
    config: &Config<'_>,
    account: Pubkey,
    owner: Pubkey,
    ui_amount: f64,
    mint_address: Option<Pubkey>,
    mint_decimals: Option<u8>,
    use_unchecked_instruction: bool,
    memo: Option<String>,
    bulk_signers: BulkSigners,
) -> CommandResult {
    println_display(
        config,
        format!("Burn {} tokens\n  Source: {}", ui_amount, account),
    );

    let mint_address = config.check_account(&account, mint_address).await?;
    let mint_info = config.get_mint_info(&mint_address, mint_decimals).await?;
    let amount = spl_token::ui_amount_to_amount(ui_amount, mint_info.decimals);
    let decimals = if use_unchecked_instruction {
        None
    } else {
        Some(mint_info.decimals)
    };

    let token = token_client_from_config(config, &mint_info.address, decimals)?;
    if let Some(text) = memo {
        token.with_memo(text, vec![config.default_signer()?.pubkey()]);
    }

    let res = token.burn(&account, &owner, amount, &bulk_signers).await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

#[allow(clippy::too_many_arguments)]
async fn command_mint(
    config: &Config<'_>,
    token: Pubkey,
    ui_amount: f64,
    recipient: Pubkey,
    mint_info: MintInfo,
    mint_authority: Pubkey,
    use_unchecked_instruction: bool,
    memo: Option<String>,
    bulk_signers: BulkSigners,
) -> CommandResult {
    println_display(
        config,
        format!(
            "Minting {} tokens\n  Token: {}\n  Recipient: {}",
            ui_amount, token, recipient
        ),
    );

    let amount = spl_token::ui_amount_to_amount(ui_amount, mint_info.decimals);
    let decimals = if use_unchecked_instruction {
        None
    } else {
        Some(mint_info.decimals)
    };

    let token = token_client_from_config(config, &mint_info.address, decimals)?;
    if let Some(text) = memo {
        token.with_memo(text, vec![config.default_signer()?.pubkey()]);
    }

    let res = token
        .mint_to(&recipient, &mint_authority, amount, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_freeze(
    config: &Config<'_>,
    account: Pubkey,
    mint_address: Option<Pubkey>,
    freeze_authority: Pubkey,
    bulk_signers: BulkSigners,
) -> CommandResult {
    let mint_address = config.check_account(&account, mint_address).await?;
    let mint_info = config.get_mint_info(&mint_address, None).await?;

    println_display(
        config,
        format!(
            "Freezing account: {}\n  Token: {}",
            account, mint_info.address
        ),
    );

    // we dont use the decimals from mint_info because its not need and in sign-only
    // its wrong
    let token = token_client_from_config(config, &mint_info.address, None)?;
    let res = token
        .freeze(&account, &freeze_authority, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_thaw(
    config: &Config<'_>,
    account: Pubkey,
    mint_address: Option<Pubkey>,
    freeze_authority: Pubkey,
    bulk_signers: BulkSigners,
) -> CommandResult {
    let mint_address = config.check_account(&account, mint_address).await?;
    let mint_info = config.get_mint_info(&mint_address, None).await?;

    println_display(
        config,
        format!(
            "Thawing account: {}\n  Token: {}",
            account, mint_info.address
        ),
    );

    // we dont use the decimals from mint_info because its not need and in sign-only
    // its wrong
    let token = token_client_from_config(config, &mint_info.address, None)?;
    let res = token
        .thaw(&account, &freeze_authority, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_wrap(
    config: &Config<'_>,
    mln: f64,
    wallet_address: Pubkey,
    wrapped_mln_account: Option<Pubkey>,
    immutable_owner: bool,
    bulk_signers: BulkSigners,
) -> CommandResult {
    let lamports = mln_to_lamports(mln);
    let token = native_token_client_from_config(config)?;

    let account =
        wrapped_mln_account.unwrap_or_else(|| token.get_associated_token_address(&wallet_address));

    println_display(config, format!("Wrapping {} MLN into {}", mln, account));

    if !config.sign_only {
        if let Some(account_data) = config.program_client.get_account(account).await? {
            if account_data.owner != system_program::id() {
                return Err(format!("Error: Account already exists: {}", account).into());
            }
        }

        check_wallet_balance(config, &wallet_address, lamports).await?;
    }

    let res = if immutable_owner {
        if config.program_id == spl_token::id() {
            return Err(format!(
                "Specified --immutable, but token program {} does not support the extension",
                config.program_id
            )
            .into());
        }

        token
            .wrap(&account, &wallet_address, lamports, &bulk_signers)
            .await?
    } else {
        // this case is hit for a token22 ata, which is always immutable. but it does
        // the right thing anyway
        token
            .wrap_with_mutable_ownership(&account, &wallet_address, lamports, &bulk_signers)
            .await?
    };

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_unwrap(
    config: &Config<'_>,
    wallet_address: Pubkey,
    maybe_account: Option<Pubkey>,
    bulk_signers: BulkSigners,
) -> CommandResult {
    let use_associated_account = maybe_account.is_none();
    let token = native_token_client_from_config(config)?;

    let account =
        maybe_account.unwrap_or_else(|| token.get_associated_token_address(&wallet_address));

    println_display(config, format!("Unwrapping {}", account));

    if !config.sign_only {
        let account_data = config.get_account_checked(&account).await?;

        if !use_associated_account {
            let account_state = StateWithExtensionsOwned::<Account>::unpack(account_data.data)?;

            if account_state.base.mint != *token.get_address() {
                return Err(format!("{} is not a native token account", account).into());
            }
        }

        if account_data.lamports == 0 {
            if use_associated_account {
                return Err("No wrapped MLN in associated account; did you mean to specify an auxiliary address?".to_string().into());
            } else {
                return Err(format!("No wrapped MLN in {}", account).into());
            }
        }

        println_display(
            config,
            format!("  Amount: {} MLN", lamports_to_mln(account_data.lamports)),
        );
    }

    println_display(config, format!("  Recipient: {}", &wallet_address));

    let res = token
        .close_account(&account, &wallet_address, &wallet_address, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

#[allow(clippy::too_many_arguments)]
async fn command_approve(
    config: &Config<'_>,
    account: Pubkey,
    owner: Pubkey,
    ui_amount: f64,
    delegate: Pubkey,
    mint_address: Option<Pubkey>,
    mint_decimals: Option<u8>,
    use_unchecked_instruction: bool,
    bulk_signers: BulkSigners,
) -> CommandResult {
    println_display(
        config,
        format!(
            "Approve {} tokens\n  Account: {}\n  Delegate: {}",
            ui_amount, account, delegate
        ),
    );

    let mint_address = config.check_account(&account, mint_address).await?;
    let mint_info = config.get_mint_info(&mint_address, mint_decimals).await?;
    let amount = spl_token::ui_amount_to_amount(ui_amount, mint_info.decimals);
    let decimals = if use_unchecked_instruction {
        None
    } else {
        Some(mint_info.decimals)
    };

    let token = token_client_from_config(config, &mint_info.address, decimals)?;
    let res = token
        .approve(&account, &delegate, &owner, amount, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_revoke(
    config: &Config<'_>,
    account: Pubkey,
    owner: Pubkey,
    delegate: Option<Pubkey>,
    bulk_signers: BulkSigners,
) -> CommandResult {
    let (mint_pubkey, delegate) = if !config.sign_only {
        let source_account = config.get_account_checked(&account).await?;
        let source_state = StateWithExtensionsOwned::<Account>::unpack(source_account.data)
            .map_err(|_| format!("Could not deserialize token account {}", account))?;

        let delegate = if let COption::Some(delegate) = source_state.base.delegate {
            Some(delegate)
        } else {
            None
        };

        (source_state.base.mint, delegate)
    } else {
        // default is safe here because revoke doesnt use it
        (Pubkey::default(), delegate)
    };

    if let Some(delegate) = delegate {
        println_display(
            config,
            format!(
                "Revoking approval\n  Account: {}\n  Delegate: {}",
                account, delegate
            ),
        );
    } else {
        return Err(format!("No delegate on account {}", account).into());
    }

    let token = token_client_from_config(config, &mint_pubkey, None)?;
    let res = token.revoke(&account, &owner, &bulk_signers).await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_close(
    config: &Config<'_>,
    account: Pubkey,
    close_authority: Pubkey,
    recipient: Pubkey,
    bulk_signers: BulkSigners,
) -> CommandResult {
    let mut results = vec![];
    let token = if !config.sign_only {
        let source_account = config.get_account_checked(&account).await?;

        let source_state = StateWithExtensionsOwned::<Account>::unpack(source_account.data)
            .map_err(|_| format!("Could not deserialize token account {}", account))?;
        let source_amount = source_state.base.amount;

        if !source_state.base.is_native() && source_amount > 0 {
            return Err(format!(
                "Account {} still has {} tokens; empty the account in order to close it.",
                account, source_amount,
            )
            .into());
        }

        let token = token_client_from_config(config, &source_state.base.mint, None)?;
        if let Ok(extension) = source_state.get_extension::<TransferFeeAmount>() {
            if u64::from(extension.withheld_amount) != 0 {
                let res = token.harvest_withheld_tokens_to_mint(&[&account]).await?;
                let tx_return = finish_tx(config, &res, false).await?;
                results.push(match tx_return {
                    TransactionReturnData::CliSignature(signature) => {
                        config.output_format.formatted_string(&signature)
                    }
                    TransactionReturnData::CliSignOnlyData(sign_only_data) => {
                        config.output_format.formatted_string(&sign_only_data)
                    }
                });
            }
        }

        token
    } else {
        // default is safe here because close doesnt use it
        token_client_from_config(config, &Pubkey::default(), None)?
    };

    let res = token
        .close_account(&account, &recipient, &close_authority, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    results.push(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    });
    Ok(results.join(""))
}

async fn command_close_mint(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    close_authority: Pubkey,
    recipient: Pubkey,
    bulk_signers: BulkSigners,
) -> CommandResult {
    if !config.sign_only {
        let mint_account = config.get_account_checked(&token_pubkey).await?;

        let mint_state = StateWithExtensionsOwned::<Mint>::unpack(mint_account.data)
            .map_err(|_| format!("Could not deserialize token mint {}", token_pubkey))?;
        let mint_supply = mint_state.base.supply;

        if mint_supply > 0 {
            return Err(format!(
                "Mint {} still has {} outstanding tokens; these must be burned before closing the mint.",
                token_pubkey, mint_supply,
            )
            .into());
        }

        if let Ok(mint_close_authority) = mint_state.get_extension::<MintCloseAuthority>() {
            let mint_close_authority_pubkey =
                Option::<Pubkey>::from(mint_close_authority.close_authority);

            if mint_close_authority_pubkey != Some(close_authority) {
                return Err(format!(
                    "Mint {} has close authority {}, but {} was provided",
                    token_pubkey,
                    mint_close_authority_pubkey
                        .map(|pubkey| pubkey.to_string())
                        .unwrap_or_else(|| "disabled".to_string()),
                    close_authority
                )
                .into());
            }
        } else {
            return Err(format!("Mint {} does not support close authority", token_pubkey).into());
        }
    }

    let token = token_client_from_config(config, &token_pubkey, None)?;
    let res = token
        .close_account(&token_pubkey, &recipient, &close_authority, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_balance(config: &Config<'_>, address: Pubkey) -> CommandResult {
    let balance = config
        .rpc_client
        .get_token_account_balance(&address)
        .await
        .map_err(|_| format!("Could not find token account {}", address))?;
    let cli_token_amount = CliTokenAmount { amount: balance };
    Ok(config.output_format.formatted_string(&cli_token_amount))
}

async fn command_supply(config: &Config<'_>, token: Pubkey) -> CommandResult {
    let supply = config.rpc_client.get_token_supply(&token).await?;
    let cli_token_amount = CliTokenAmount { amount: supply };
    Ok(config.output_format.formatted_string(&cli_token_amount))
}

async fn command_accounts(
    config: &Config<'_>,
    maybe_token: Option<Pubkey>,
    owner: Pubkey,
    account_filter: AccountFilter,
    print_addresses_only: bool,
) -> CommandResult {
    let filters = if let Some(token_pubkey) = maybe_token {
        let _ = config.get_mint_info(&token_pubkey, None).await?;
        vec![TokenAccountsFilter::Mint(token_pubkey)]
    } else if config.restrict_to_program_id {
        vec![TokenAccountsFilter::ProgramId(config.program_id)]
    } else {
        vec![
            TokenAccountsFilter::ProgramId(spl_token::id()),
            TokenAccountsFilter::ProgramId(spl_token_2022::id()),
        ]
    };

    let mut accounts = vec![];
    for filter in filters {
        accounts.push(
            config
                .rpc_client
                .get_token_accounts_by_owner(&owner, filter)
                .await?,
        );
    }
    let accounts = accounts.into_iter().flatten().collect();

    let cli_token_accounts =
        sort_and_parse_token_accounts(&owner, accounts, maybe_token.is_some(), account_filter)?;

    if print_addresses_only {
        Ok(cli_token_accounts
            .accounts
            .into_iter()
            .flatten()
            .map(|a| a.address)
            .collect::<Vec<_>>()
            .join("\n"))
    } else {
        Ok(config.output_format.formatted_string(&cli_token_accounts))
    }
}

async fn command_address(
    config: &Config<'_>,
    token: Option<Pubkey>,
    owner: Pubkey,
) -> CommandResult {
    let mut cli_address = CliWalletAddress {
        wallet_address: owner.to_string(),
        ..CliWalletAddress::default()
    };
    if let Some(token) = token {
        config.get_mint_info(&token, None).await?;
        let associated_token_address =
            get_associated_token_address_with_program_id(&owner, &token, &config.program_id);
        cli_address.associated_token_address = Some(associated_token_address.to_string());
    }
    Ok(config.output_format.formatted_string(&cli_address))
}

async fn command_display(config: &Config<'_>, address: Pubkey) -> CommandResult {
    let account_data = config.get_account_checked(&address).await?;

    let (decimals, has_permanent_delegate) =
        if let Some(mint_address) = get_token_account_mint(&account_data.data) {
            let mint_account = config.get_account_checked(&mint_address).await?;
            let mint_state = StateWithExtensionsOwned::<Mint>::unpack(mint_account.data)
                .map_err(|_| format!("Could not deserialize token mint {}", mint_address))?;

            let has_permanent_delegate =
                if let Ok(permanent_delegate) = mint_state.get_extension::<PermanentDelegate>() {
                    Option::<Pubkey>::from(permanent_delegate.delegate).is_some()
                } else {
                    false
                };

            (Some(mint_state.base.decimals), has_permanent_delegate)
        } else {
            (None, false)
        };

    let token_data = parse_token(&account_data.data, decimals);

    match token_data {
        Ok(TokenAccountType::Account(account)) => {
            let mint_address = Pubkey::from_str(&account.mint)?;
            let owner = Pubkey::from_str(&account.owner)?;
            let associated_address = get_associated_token_address_with_program_id(
                &owner,
                &mint_address,
                &config.program_id,
            );

            let cli_output = CliTokenAccount {
                address: address.to_string(),
                program_id: config.program_id.to_string(),
                is_associated: associated_address == address,
                account,
                has_permanent_delegate,
            };

            Ok(config.output_format.formatted_string(&cli_output))
        }
        Ok(TokenAccountType::Mint(mint)) => {
            let epoch_info = config.rpc_client.get_epoch_info().await?;
            let cli_output = CliMint {
                address: address.to_string(),
                epoch: epoch_info.epoch,
                program_id: config.program_id.to_string(),
                mint,
            };

            Ok(config.output_format.formatted_string(&cli_output))
        }
        Ok(TokenAccountType::Multisig(multisig)) => {
            let cli_output = CliMultisig {
                address: address.to_string(),
                program_id: config.program_id.to_string(),
                multisig,
            };

            Ok(config.output_format.formatted_string(&cli_output))
        }
        Err(e) => Err(e.into()),
    }
}

async fn command_gc(
    config: &Config<'_>,
    owner: Pubkey,
    close_empty_associated_accounts: bool,
    bulk_signers: BulkSigners,
) -> CommandResult {
    println_display(
        config,
        format!(
            "Fetching token accounts associated with program {}",
            config.program_id
        ),
    );
    let accounts = config
        .rpc_client
        .get_token_accounts_by_owner(&owner, TokenAccountsFilter::ProgramId(config.program_id))
        .await?;
    if accounts.is_empty() {
        println_display(config, "Nothing to do".to_string());
        return Ok("".to_string());
    }

    let mut accounts_by_token = HashMap::new();

    for keyed_account in accounts {
        if let UiAccountData::Json(parsed_account) = keyed_account.account.data {
            if let Ok(TokenAccountType::Account(ui_token_account)) =
                serde_json::from_value(parsed_account.parsed)
            {
                let frozen = ui_token_account.state == UiAccountState::Frozen;
                let decimals = ui_token_account.token_amount.decimals;

                let token = ui_token_account
                    .mint
                    .parse::<Pubkey>()
                    .unwrap_or_else(|err| panic!("Invalid mint: {}", err));
                let token_account = keyed_account
                    .pubkey
                    .parse::<Pubkey>()
                    .unwrap_or_else(|err| panic!("Invalid token account: {}", err));
                let token_amount = ui_token_account
                    .token_amount
                    .amount
                    .parse::<u64>()
                    .unwrap_or_else(|err| panic!("Invalid token amount: {}", err));

                let close_authority = ui_token_account.close_authority.map_or(owner, |s| {
                    s.parse::<Pubkey>()
                        .unwrap_or_else(|err| panic!("Invalid close authority: {}", err))
                });

                let entry = accounts_by_token
                    .entry((token, decimals))
                    .or_insert_with(HashMap::new);
                entry.insert(token_account, (token_amount, frozen, close_authority));
            }
        }
    }

    let mut results = vec![];
    for ((token_pubkey, decimals), accounts) in accounts_by_token.into_iter() {
        println_display(config, format!("Processing token: {}", token_pubkey));

        let token = token_client_from_config(config, &token_pubkey, Some(decimals))?;
        let total_balance: u64 = accounts.values().map(|account| account.0).sum();

        let associated_token_account = token.get_associated_token_address(&owner);
        if !accounts.contains_key(&associated_token_account) && total_balance > 0 {
            token.create_associated_token_account(&owner).await?;
        }

        for (address, (amount, frozen, close_authority)) in accounts {
            let is_associated = address == associated_token_account;

            // only close the associated account if --close-empty-associated-accounts is
            // provided
            if is_associated && !close_empty_associated_accounts {
                continue;
            }

            // never close the associated account if *any* account carries a balance
            if is_associated && total_balance > 0 {
                continue;
            }

            // dont attempt to close frozen accounts
            if frozen {
                continue;
            }

            if is_associated {
                println!("Closing associated account {}", address);
            }

            // this logic is quite fiendish, but its more readable this way than if/else
            let maybe_res = match (close_authority == owner, is_associated, amount == 0) {
                // owner authority, associated or auxiliary, empty -> close
                (true, _, true) => Some(
                    token
                        .close_account(&address, &owner, &owner, &bulk_signers)
                        .await,
                ),
                // owner authority, auxiliary, nonempty -> empty and close
                (true, false, false) => Some(
                    token
                        .empty_and_close_account(
                            &address,
                            &owner,
                            &associated_token_account,
                            &owner,
                            &bulk_signers,
                        )
                        .await,
                ),
                // separate authority, auxiliary, nonempty -> transfer
                (false, false, false) => Some(
                    token
                        .transfer(
                            &address,
                            &associated_token_account,
                            &owner,
                            amount,
                            &bulk_signers,
                        )
                        .await,
                ),
                // separate authority, associated or auxiliary, empty -> print warning
                (false, _, true) => {
                    println_display(
                        config,
                        format!(
                            "Note: skipping {} due to separate close authority {}; \
                             revoke authority and rerun gc, or rerun gc with --owner",
                            address, close_authority
                        ),
                    );
                    None
                }
                // anything else, including a nonempty associated account -> unreachable
                (_, _, _) => unreachable!(),
            };

            if let Some(res) = maybe_res {
                let tx_return = finish_tx(config, &res?, false).await?;

                results.push(match tx_return {
                    TransactionReturnData::CliSignature(signature) => {
                        config.output_format.formatted_string(&signature)
                    }
                    TransactionReturnData::CliSignOnlyData(sign_only_data) => {
                        config.output_format.formatted_string(&sign_only_data)
                    }
                });
            };
        }
    }

    Ok(results.join(""))
}

async fn command_sync_native(config: &Config<'_>, native_account_address: Pubkey) -> CommandResult {
    let token = native_token_client_from_config(config)?;

    if !config.sign_only {
        let account_data = config.get_account_checked(&native_account_address).await?;
        let account_state = StateWithExtensionsOwned::<Account>::unpack(account_data.data)?;

        if account_state.base.mint != *token.get_address() {
            return Err(format!("{} is not a native token account", native_account_address).into());
        }
    }

    let res = token.sync_native(&native_account_address).await?;
    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_withdraw_excess_lamports(
    config: &Config<'_>,
    source_account: Pubkey,
    destination_account: Pubkey,
    authority: Pubkey,
    bulk_signers: Vec<Arc<dyn Signer>>,
) -> CommandResult {
    // default is safe here because withdraw_excess_lamports doesn't use it
    let token = token_client_from_config(config, &Pubkey::default(), None)?;
    println_display(
        config,
        format!(
            "Withdrawing excess lamports\n  Sender: {}\n  Destination: {}",
            source_account, destination_account
        ),
    );

    let res = token
        .withdraw_excess_lamports(
            &source_account,
            &destination_account,
            &authority,
            &bulk_signers,
        )
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;

    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

// both enables and disables required transfer memos, via enable_memos bool
async fn command_required_transfer_memos(
    config: &Config<'_>,
    token_account_address: Pubkey,
    owner: Pubkey,
    bulk_signers: BulkSigners,
    enable_memos: bool,
) -> CommandResult {
    if config.sign_only {
        panic!("Config can not be sign-only for enabling/disabling required transfer memos.");
    }

    let account = config.get_account_checked(&token_account_address).await?;
    let current_account_len = account.data.len();

    let state_with_extension = StateWithExtensionsOwned::<Account>::unpack(account.data)?;
    let token = token_client_from_config(config, &state_with_extension.base.mint, None)?;

    // Reallocation (if needed)
    let mut existing_extensions: Vec<ExtensionType> = state_with_extension.get_extension_types()?;
    if existing_extensions.contains(&ExtensionType::MemoTransfer) {
        let extension_state = state_with_extension
            .get_extension::<MemoTransfer>()?
            .require_incoming_transfer_memos
            .into();

        if extension_state == enable_memos {
            return Ok(format!(
                "Required transfer memos were already {}",
                if extension_state {
                    "enabled"
                } else {
                    "disabled"
                }
            ));
        }
    } else {
        existing_extensions.push(ExtensionType::MemoTransfer);
        let needed_account_len =
            ExtensionType::try_calculate_account_len::<Account>(&existing_extensions)?;
        if needed_account_len > current_account_len {
            token
                .reallocate(
                    &token_account_address,
                    &owner,
                    &[ExtensionType::MemoTransfer],
                    &bulk_signers,
                )
                .await?;
        }
    }

    let res = if enable_memos {
        token
            .enable_required_transfer_memos(&token_account_address, &owner, &bulk_signers)
            .await
    } else {
        token
            .disable_required_transfer_memos(&token_account_address, &owner, &bulk_signers)
            .await
    }?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

// both enables and disables cpi guard, via enable_guard bool
async fn command_cpi_guard(
    config: &Config<'_>,
    token_account_address: Pubkey,
    owner: Pubkey,
    bulk_signers: BulkSigners,
    enable_guard: bool,
) -> CommandResult {
    if config.sign_only {
        panic!("Config can not be sign-only for enabling/disabling required transfer memos.");
    }

    let account = config.get_account_checked(&token_account_address).await?;
    let current_account_len = account.data.len();

    let state_with_extension = StateWithExtensionsOwned::<Account>::unpack(account.data)?;
    let token = token_client_from_config(config, &state_with_extension.base.mint, None)?;

    // reallocation (if needed)
    let mut existing_extensions: Vec<ExtensionType> = state_with_extension.get_extension_types()?;
    if existing_extensions.contains(&ExtensionType::CpiGuard) {
        let extension_state = state_with_extension
            .get_extension::<CpiGuard>()?
            .lock_cpi
            .into();

        if extension_state == enable_guard {
            return Ok(format!(
                "CPI Guard was already {}",
                if extension_state {
                    "enabled"
                } else {
                    "disabled"
                }
            ));
        }
    } else {
        existing_extensions.push(ExtensionType::CpiGuard);
        let required_account_len =
            ExtensionType::try_calculate_account_len::<Account>(&existing_extensions)?;
        if required_account_len > current_account_len {
            token
                .reallocate(
                    &token_account_address,
                    &owner,
                    &[ExtensionType::CpiGuard],
                    &bulk_signers,
                )
                .await?;
        }
    }

    let res = if enable_guard {
        token
            .enable_cpi_guard(&token_account_address, &owner, &bulk_signers)
            .await
    } else {
        token
            .disable_cpi_guard(&token_account_address, &owner, &bulk_signers)
            .await
    }?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_update_metadata_pointer_address(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    authority: Pubkey,
    new_metadata_address: Option<Pubkey>,
    bulk_signers: BulkSigners,
) -> CommandResult {
    if config.sign_only {
        panic!("Config can not be sign-only for updating metadata pointer address.");
    }

    let token = token_client_from_config(config, &token_pubkey, None)?;
    let res = token
        .update_metadata_address(&authority, new_metadata_address, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_update_default_account_state(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    freeze_authority: Pubkey,
    new_default_state: AccountState,
    bulk_signers: BulkSigners,
) -> CommandResult {
    if !config.sign_only {
        let mint_account = config.get_account_checked(&token_pubkey).await?;

        let mint_state = StateWithExtensionsOwned::<Mint>::unpack(mint_account.data)
            .map_err(|_| format!("Could not deserialize token mint {}", token_pubkey))?;
        match mint_state.base.freeze_authority {
            COption::None => {
                return Err(format!("Mint {} has no freeze authority.", token_pubkey).into())
            }
            COption::Some(mint_freeze_authority) => {
                if mint_freeze_authority != freeze_authority {
                    return Err(format!(
                        "Mint {} has a freeze authority {}, {} provided",
                        token_pubkey, mint_freeze_authority, freeze_authority
                    )
                    .into());
                }
            }
        }

        if let Ok(default_account_state) = mint_state.get_extension::<DefaultAccountState>() {
            if default_account_state.state == u8::from(new_default_state) {
                let state_string = match new_default_state {
                    AccountState::Frozen => "frozen",
                    AccountState::Initialized => "initialized",
                    _ => unreachable!(),
                };
                return Err(format!(
                    "Mint {} already has default account state {}",
                    token_pubkey, state_string
                )
                .into());
            }
        } else {
            return Err(format!(
                "Mint {} does not support default account states",
                token_pubkey
            )
            .into());
        }
    }

    let token = token_client_from_config(config, &token_pubkey, None)?;
    let res = token
        .set_default_account_state(&freeze_authority, &new_default_state, &bulk_signers)
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_withdraw_withheld_tokens(
    config: &Config<'_>,
    destination_token_account: Pubkey,
    source_token_accounts: Vec<Pubkey>,
    authority: Pubkey,
    include_mint: bool,
    bulk_signers: BulkSigners,
) -> CommandResult {
    if config.sign_only {
        panic!("Config can not be sign-only for withdrawing withheld tokens.");
    }
    let destination_account = config
        .get_account_checked(&destination_token_account)
        .await?;
    let destination_state = StateWithExtensionsOwned::<Account>::unpack(destination_account.data)
        .map_err(|_| {
        format!(
            "Could not deserialize token account {}",
            destination_token_account
        )
    })?;
    let token_pubkey = destination_state.base.mint;
    destination_state
        .get_extension::<TransferFeeAmount>()
        .map_err(|_| format!("Token mint {} has no transfer fee configured", token_pubkey))?;

    let token = token_client_from_config(config, &token_pubkey, None)?;
    let mut results = vec![];
    if include_mint {
        let res = token
            .withdraw_withheld_tokens_from_mint(
                &destination_token_account,
                &authority,
                &bulk_signers,
            )
            .await;
        let tx_return = finish_tx(config, &res?, false).await?;
        results.push(match tx_return {
            TransactionReturnData::CliSignature(signature) => {
                config.output_format.formatted_string(&signature)
            }
            TransactionReturnData::CliSignOnlyData(sign_only_data) => {
                config.output_format.formatted_string(&sign_only_data)
            }
        });
    }

    let source_refs = source_token_accounts.iter().collect::<Vec<_>>();
    // this can be tweaked better, but keep it simple for now
    const MAX_WITHDRAWAL_ACCOUNTS: usize = 25;
    for sources in source_refs.chunks(MAX_WITHDRAWAL_ACCOUNTS) {
        let res = token
            .withdraw_withheld_tokens_from_accounts(
                &destination_token_account,
                &authority,
                sources,
                &bulk_signers,
            )
            .await;
        let tx_return = finish_tx(config, &res?, false).await?;
        results.push(match tx_return {
            TransactionReturnData::CliSignature(signature) => {
                config.output_format.formatted_string(&signature)
            }
            TransactionReturnData::CliSignOnlyData(sign_only_data) => {
                config.output_format.formatted_string(&sign_only_data)
            }
        });
    }

    Ok(results.join(""))
}

async fn command_update_confidential_transfer_settings(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    authority: Pubkey,
    auto_approve: Option<bool>,
    auditor_pubkey: Option<ElGamalPubkeyOrNone>,
    bulk_signers: Vec<Arc<dyn Signer>>,
) -> CommandResult {
    let (new_auto_approve, new_auditor_pubkey) = if !config.sign_only {
        let confidential_transfer_account = config.get_account_checked(&token_pubkey).await?;

        let mint_state =
            StateWithExtensionsOwned::<Mint>::unpack(confidential_transfer_account.data)
                .map_err(|_| format!("Could not deserialize token mint {}", token_pubkey))?;

        if let Ok(confidential_transfer_mint) =
            mint_state.get_extension::<ConfidentialTransferMint>()
        {
            let expected_authority = Option::<Pubkey>::from(confidential_transfer_mint.authority);

            if expected_authority != Some(authority) {
                return Err(format!(
                    "Mint {} has confidential transfer authority {}, but {} was provided",
                    token_pubkey,
                    expected_authority
                        .map(|pubkey| pubkey.to_string())
                        .unwrap_or_else(|| "disabled".to_string()),
                    authority
                )
                .into());
            }

            let new_auto_approve = if let Some(auto_approve) = auto_approve {
                auto_approve
            } else {
                bool::from(confidential_transfer_mint.auto_approve_new_accounts)
            };

            let new_auditor_pubkey = if let Some(auditor_pubkey) = auditor_pubkey {
                auditor_pubkey.into()
            } else {
                Option::<ElGamalPubkey>::from(confidential_transfer_mint.auditor_elgamal_pubkey)
            };

            (new_auto_approve, new_auditor_pubkey)
        } else {
            return Err(format!(
                "Mint {} does not support confidential transfers",
                token_pubkey
            )
            .into());
        }
    } else {
        let new_auto_approve = auto_approve.expect("The approve policy must be provided");
        let new_auditor_pubkey = auditor_pubkey
            .expect("The auditor encryption pubkey must be provided")
            .into();

        (new_auto_approve, new_auditor_pubkey)
    };

    println_display(
        config,
        format!(
            "Updating confidential transfer settings for {}:",
            token_pubkey,
        ),
    );

    if auto_approve.is_some() {
        println_display(
            config,
            format!(
                "  approve policy set to {}",
                if new_auto_approve { "auto" } else { "manual" }
            ),
        );
    }

    if auditor_pubkey.is_some() {
        if let Some(new_auditor_pubkey) = new_auditor_pubkey {
            println_display(
                config,
                format!("  auditor encryption pubkey set to {}", new_auditor_pubkey,),
            );
        } else {
            println_display(config, "  auditability disabled".to_string())
        }
    }

    let token = token_client_from_config(config, &token_pubkey, None)?;
    let res = token
        .confidential_transfer_update_mint(
            &authority,
            new_auto_approve,
            new_auditor_pubkey,
            &bulk_signers,
        )
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

#[allow(clippy::too_many_arguments)]
async fn command_configure_confidential_transfer_account(
    config: &Config<'_>,
    maybe_token: Option<Pubkey>,
    owner: Pubkey,
    maybe_account: Option<Pubkey>,
    maximum_credit_counter: Option<u64>,
    elgamal_keypair: &ElGamalKeypair,
    aes_key: &AeKey,
    bulk_signers: BulkSigners,
) -> CommandResult {
    if config.sign_only {
        panic!("Sign-only is not yet supported.");
    }

    let token_account_address = if let Some(account) = maybe_account {
        account
    } else {
        let token_pubkey =
            maybe_token.expect("Either a valid token or account address must be provided");
        let token = token_client_from_config(config, &token_pubkey, None)?;
        token.get_associated_token_address(&owner)
    };

    let account = config.get_account_checked(&token_account_address).await?;
    let current_account_len = account.data.len();

    let state_with_extension = StateWithExtensionsOwned::<Account>::unpack(account.data)?;
    let token = token_client_from_config(config, &state_with_extension.base.mint, None)?;

    // Reallocation (if needed)
    let mut existing_extensions: Vec<ExtensionType> = state_with_extension.get_extension_types()?;
    if !existing_extensions.contains(&ExtensionType::ConfidentialTransferAccount) {
        existing_extensions.push(ExtensionType::ConfidentialTransferAccount);
        let needed_account_len =
            ExtensionType::try_calculate_account_len::<Account>(&existing_extensions)?;
        if needed_account_len > current_account_len {
            token
                .reallocate(
                    &token_account_address,
                    &owner,
                    &[ExtensionType::ConfidentialTransferAccount],
                    &bulk_signers,
                )
                .await?;
        }
    }

    let res = token
        .confidential_transfer_configure_token_account(
            &token_account_address,
            &owner,
            None,
            maximum_credit_counter,
            elgamal_keypair,
            aes_key,
            &bulk_signers,
        )
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

async fn command_enable_disable_confidential_transfers(
    config: &Config<'_>,
    maybe_token: Option<Pubkey>,
    owner: Pubkey,
    maybe_account: Option<Pubkey>,
    bulk_signers: BulkSigners,
    allow_confidential_credits: Option<bool>,
    allow_non_confidential_credits: Option<bool>,
) -> CommandResult {
    if config.sign_only {
        panic!("Sign-only is not yet supported.");
    }

    let token_account_address = if let Some(account) = maybe_account {
        account
    } else {
        let token_pubkey =
            maybe_token.expect("Either a valid token or account address must be provided");
        let token = token_client_from_config(config, &token_pubkey, None)?;
        token.get_associated_token_address(&owner)
    };

    let account = config.get_account_checked(&token_account_address).await?;

    let state_with_extension = StateWithExtensionsOwned::<Account>::unpack(account.data)?;
    let token = token_client_from_config(config, &state_with_extension.base.mint, None)?;

    let existing_extensions: Vec<ExtensionType> = state_with_extension.get_extension_types()?;
    if !existing_extensions.contains(&ExtensionType::ConfidentialTransferAccount) {
        panic!(
            "Confidential transfer is not yet configured for this account. \
        Use `configure-confidential-transfer-account` command instead."
        );
    }

    let res = if let Some(allow_confidential_credits) = allow_confidential_credits {
        let extension_state = state_with_extension
            .get_extension::<ConfidentialTransferAccount>()?
            .allow_confidential_credits
            .into();

        if extension_state == allow_confidential_credits {
            return Ok(format!(
                "Confidential transfers are already {}",
                if extension_state {
                    "enabled"
                } else {
                    "disabled"
                }
            ));
        }

        if allow_confidential_credits {
            token
                .confidential_transfer_enable_confidential_credits(
                    &token_account_address,
                    &owner,
                    &bulk_signers,
                )
                .await
        } else {
            token
                .confidential_transfer_disable_confidential_credits(
                    &token_account_address,
                    &owner,
                    &bulk_signers,
                )
                .await
        }
    } else {
        let allow_non_confidential_credits =
            allow_non_confidential_credits.expect("Nothing to be done");
        let extension_state = state_with_extension
            .get_extension::<ConfidentialTransferAccount>()?
            .allow_non_confidential_credits
            .into();

        if extension_state == allow_non_confidential_credits {
            return Ok(format!(
                "Non-confidential transfers are already {}",
                if extension_state {
                    "enabled"
                } else {
                    "disabled"
                }
            ));
        }

        if allow_non_confidential_credits {
            token
                .confidential_transfer_enable_non_confidential_credits(
                    &token_account_address,
                    &owner,
                    &bulk_signers,
                )
                .await
        } else {
            token
                .confidential_transfer_disable_non_confidential_credits(
                    &token_account_address,
                    &owner,
                    &bulk_signers,
                )
                .await
        }
    }?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}
#[derive(PartialEq, Eq)]
enum ConfidentialInstructionType {
    Deposit,
    Withdraw,
}

#[allow(clippy::too_many_arguments)]
async fn command_deposit_withdraw_confidential_tokens(
    config: &Config<'_>,
    token_pubkey: Pubkey,
    owner: Pubkey,
    maybe_account: Option<Pubkey>,
    bulk_signers: BulkSigners,
    ui_amount: Option<f64>,
    mint_decimals: Option<u8>,
    instruction_type: ConfidentialInstructionType,
    elgamal_keypair: Option<&ElGamalKeypair>,
    aes_key: Option<&AeKey>,
) -> CommandResult {
    if config.sign_only {
        panic!("Sign-only is not yet supported.");
    }

    // check if mint decimals provided is consistent
    let mint_info = config.get_mint_info(&token_pubkey, mint_decimals).await?;

    if !config.sign_only && mint_decimals.is_some() && mint_decimals != Some(mint_info.decimals) {
        return Err(format!(
            "Decimals {} was provided, but actual value is {}",
            mint_decimals.unwrap(),
            mint_info.decimals
        )
        .into());
    }

    let decimals = if let Some(decimals) = mint_decimals {
        decimals
    } else {
        mint_info.decimals
    };

    // derive ATA if account address not provided
    let token_account_address = if let Some(account) = maybe_account {
        account
    } else {
        let token = token_client_from_config(config, &token_pubkey, Some(decimals))?;
        token.get_associated_token_address(&owner)
    };

    let account = config.get_account_checked(&token_account_address).await?;

    let state_with_extension = StateWithExtensionsOwned::<Account>::unpack(account.data)?;
    let token = token_client_from_config(config, &state_with_extension.base.mint, None)?;

    // the amount the user wants to deposit or withdraw, as an f64
    let maybe_amount =
        ui_amount.map(|ui_amount| spl_token::ui_amount_to_amount(ui_amount, mint_info.decimals));

    // the amount we will deposit or withdraw, as a u64
    let amount = if !config.sign_only && instruction_type == ConfidentialInstructionType::Deposit {
        let current_balance = state_with_extension.base.amount;
        let deposit_amount = maybe_amount.unwrap_or(current_balance);

        println_display(
            config,
            format!(
                "Depositing {} confidential tokens",
                spl_token::amount_to_ui_amount(deposit_amount, mint_info.decimals),
            ),
        );

        if deposit_amount > current_balance {
            return Err(format!(
                "Error: Insufficient funds, current balance is {}",
                spl_token_2022::amount_to_ui_amount_string_trimmed(
                    current_balance,
                    mint_info.decimals
                )
            )
            .into());
        }

        deposit_amount
    } else if !config.sign_only && instruction_type == ConfidentialInstructionType::Withdraw {
        // // TODO: expose account balance decryption in token
        // let aes_key = aes_key.expect("AES key must be provided");
        // let current_balance = token
        //     .confidential_transfer_get_available_balance_with_key(
        //         &token_account_address,
        //         aes_key,
        //     )
        //     .await?;
        let withdraw_amount =
            maybe_amount.expect("ALL keyword is not currently supported for withdraw");

        println_display(
            config,
            format!(
                "Withdrawing {} confidential tokens",
                spl_token::amount_to_ui_amount(withdraw_amount, mint_info.decimals)
            ),
        );

        withdraw_amount
    } else {
        maybe_amount.unwrap()
    };

    let res = match instruction_type {
        ConfidentialInstructionType::Deposit => {
            token
                .confidential_transfer_deposit(
                    &token_account_address,
                    &owner,
                    amount,
                    decimals,
                    &bulk_signers,
                )
                .await?
        }
        ConfidentialInstructionType::Withdraw => {
            let elgamal_keypair = elgamal_keypair.expect("ElGamal keypair must be provided");
            let aes_key = aes_key.expect("AES key must be provided");

            let extension_state =
                state_with_extension.get_extension::<ConfidentialTransferAccount>()?;
            let withdraw_account_info = WithdrawAccountInfo::new(extension_state);

            let context_state_authority = config.fee_payer()?;
            let context_state_keypair = Keypair::new();
            let context_state_pubkey = context_state_keypair.pubkey();

            let withdraw_proof_data =
                withdraw_account_info.generate_proof_data(amount, elgamal_keypair, aes_key)?;

            // setup proof
            token
                .create_withdraw_proof_context_state(
                    &context_state_pubkey,
                    &context_state_authority.pubkey(),
                    &withdraw_proof_data,
                    &context_state_keypair,
                )
                .await?;

            // do the withdrawal
            token
                .confidential_transfer_withdraw(
                    &token_account_address,
                    &owner,
                    Some(&context_state_pubkey),
                    amount,
                    decimals,
                    Some(withdraw_account_info),
                    elgamal_keypair,
                    aes_key,
                    &bulk_signers,
                )
                .await?;

            // close context state account
            let context_state_authority_pubkey = context_state_authority.pubkey();
            let close_context_state_signers = &[context_state_authority];
            token
                .confidential_transfer_close_context_state(
                    &context_state_pubkey,
                    &token_account_address,
                    &context_state_authority_pubkey,
                    close_context_state_signers,
                )
                .await?
        }
    };

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

#[allow(clippy::too_many_arguments)]
async fn command_apply_pending_balance(
    config: &Config<'_>,
    maybe_token: Option<Pubkey>,
    owner: Pubkey,
    maybe_account: Option<Pubkey>,
    bulk_signers: BulkSigners,
    elgamal_keypair: &ElGamalKeypair,
    aes_key: &AeKey,
) -> CommandResult {
    if config.sign_only {
        panic!("Sign-only is not yet supported.");
    }

    // derive ATA if account address not provided
    let token_account_address = if let Some(account) = maybe_account {
        account
    } else {
        let token_pubkey =
            maybe_token.expect("Either a valid token or account address must be provided");
        let token = token_client_from_config(config, &token_pubkey, None)?;
        token.get_associated_token_address(&owner)
    };

    let account = config.get_account_checked(&token_account_address).await?;

    let state_with_extension = StateWithExtensionsOwned::<Account>::unpack(account.data)?;
    let token = token_client_from_config(config, &state_with_extension.base.mint, None)?;

    let extension_state = state_with_extension.get_extension::<ConfidentialTransferAccount>()?;
    let account_info = ApplyPendingBalanceAccountInfo::new(extension_state);

    let res = token
        .confidential_transfer_apply_pending_balance(
            &token_account_address,
            &owner,
            Some(account_info),
            elgamal_keypair.secret(),
            aes_key,
            &bulk_signers,
        )
        .await?;

    let tx_return = finish_tx(config, &res, false).await?;
    Ok(match tx_return {
        TransactionReturnData::CliSignature(signature) => {
            config.output_format.formatted_string(&signature)
        }
        TransactionReturnData::CliSignOnlyData(sign_only_data) => {
            config.output_format.formatted_string(&sign_only_data)
        }
    })
}

struct ConfidentialTransferArgs {
    sender_elgamal_keypair: ElGamalKeypair,
    sender_aes_key: AeKey,
    recipient_elgamal_pubkey: Option<ElGamalPubkey>,
    auditor_elgamal_pubkey: Option<ElGamalPubkey>,
}

pub async fn process_command<'a>(
    sub_command: &CommandName,
    sub_matches: &ArgMatches<'_>,
    config: &Config<'a>,
    mut wallet_manager: Option<Rc<RemoteWalletManager>>,
    mut bulk_signers: Vec<Arc<dyn Signer>>,
) -> CommandResult {
    match (sub_command, sub_matches) {
        (CommandName::Bench, arg_matches) => {
            bench_process_command(
                arg_matches,
                config,
                std::mem::take(&mut bulk_signers),
                &mut wallet_manager,
            )
            .await
        }
        (CommandName::CreateToken, arg_matches) => {
            let decimals = value_t_or_exit!(arg_matches, "decimals", u8);
            let mint_authority =
                config.pubkey_or_default(arg_matches, "mint_authority", &mut wallet_manager)?;
            let memo = value_t!(arg_matches, "memo", String).ok();
            let rate_bps = value_t!(arg_matches, "interest_rate", i16).ok();
            let metadata_address = value_t!(arg_matches, "metadata_address", Pubkey).ok();

            let transfer_fee = arg_matches.values_of("transfer_fee").map(|mut v| {
                (
                    v.next()
                        .unwrap()
                        .parse::<u16>()
                        .unwrap_or_else(print_error_and_exit),
                    v.next()
                        .unwrap()
                        .parse::<u64>()
                        .unwrap_or_else(print_error_and_exit),
                )
            });

            let (token_signer, token) =
                get_signer(arg_matches, "token_keypair", &mut wallet_manager)
                    .unwrap_or_else(new_throwaway_signer);
            push_signer_with_dedup(token_signer, &mut bulk_signers);
            let default_account_state =
                arg_matches
                    .value_of("default_account_state")
                    .map(|s| match s {
                        "initialized" => AccountState::Initialized,
                        "frozen" => AccountState::Frozen,
                        _ => unreachable!(),
                    });
            let transfer_hook_program_id =
                pubkey_of_signer(arg_matches, "transfer_hook", &mut wallet_manager).unwrap();

            let confidential_transfer_auto_approve = arg_matches
                .value_of("enable_confidential_transfers")
                .map(|b| b == "auto");

            command_create_token(
                config,
                decimals,
                token,
                mint_authority,
                arg_matches.is_present("enable_freeze"),
                arg_matches.is_present("enable_close"),
                arg_matches.is_present("enable_non_transferable"),
                arg_matches.is_present("enable_permanent_delegate"),
                memo,
                metadata_address,
                rate_bps,
                default_account_state,
                transfer_fee,
                confidential_transfer_auto_approve,
                transfer_hook_program_id,
                arg_matches.is_present("enable_metadata"),
                bulk_signers,
            )
            .await
        }
        (CommandName::SetInterestRate, arg_matches) => {
            let token_pubkey = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let rate_bps = value_t_or_exit!(arg_matches, "rate", i16);
            let (rate_authority_signer, rate_authority_pubkey) =
                config.signer_or_default(arg_matches, "rate_authority", &mut wallet_manager);
            let bulk_signers = vec![rate_authority_signer];

            command_set_interest_rate(
                config,
                token_pubkey,
                rate_authority_pubkey,
                rate_bps,
                bulk_signers,
            )
            .await
        }
        (CommandName::SetTransferHook, arg_matches) => {
            let token_pubkey = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let new_program_id =
                pubkey_of_signer(arg_matches, "new_program_id", &mut wallet_manager).unwrap();
            let (authority_signer, authority_pubkey) =
                config.signer_or_default(arg_matches, "authority", &mut wallet_manager);
            let bulk_signers = vec![authority_signer];

            command_set_transfer_hook_program(
                config,
                token_pubkey,
                authority_pubkey,
                new_program_id,
                bulk_signers,
            )
            .await
        }
        (CommandName::InitializeMetadata, arg_matches) => {
            let token_pubkey = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let name = arg_matches.value_of("name").unwrap().to_string();
            let symbol = arg_matches.value_of("symbol").unwrap().to_string();
            let uri = arg_matches.value_of("uri").unwrap().to_string();
            let (mint_authority_signer, mint_authority) =
                config.signer_or_default(arg_matches, "mint_authority", &mut wallet_manager);
            let bulk_signers = vec![mint_authority_signer];
            let update_authority =
                config.pubkey_or_default(arg_matches, "update_authority", &mut wallet_manager)?;

            command_initialize_metadata(
                config,
                token_pubkey,
                update_authority,
                mint_authority,
                name,
                symbol,
                uri,
                bulk_signers,
            )
            .await
        }
        (CommandName::UpdateMetadata, arg_matches) => {
            let token_pubkey = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let (authority_signer, authority) =
                config.signer_or_default(arg_matches, "authority", &mut wallet_manager);
            let field = arg_matches.value_of("field").unwrap();
            let field = match field.to_lowercase().as_str() {
                "name" => Field::Name,
                "symbol" => Field::Symbol,
                "uri" => Field::Uri,
                _ => Field::Key(field.to_string()),
            };
            let value = arg_matches.value_of("value").map(|v| v.to_string());
            let transfer_lamports = value_of::<u64>(arg_matches, TRANSFER_LAMPORTS_ARG.name);
            let bulk_signers = vec![authority_signer];

            command_update_metadata(
                config,
                token_pubkey,
                authority,
                field,
                value,
                transfer_lamports,
                bulk_signers,
            )
            .await
        }
        (CommandName::CreateAccount, arg_matches) => {
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();

            // No need to add a signer when creating an associated token account
            let account = get_signer(arg_matches, "account_keypair", &mut wallet_manager).map(
                |(signer, account)| {
                    push_signer_with_dedup(signer, &mut bulk_signers);
                    account
                },
            );

            let owner = config.pubkey_or_default(arg_matches, "owner", &mut wallet_manager)?;
            command_create_account(
                config,
                token,
                owner,
                account,
                arg_matches.is_present("immutable"),
                bulk_signers,
            )
            .await
        }
        (CommandName::CreateMultisig, arg_matches) => {
            let minimum_signers = value_of::<u8>(arg_matches, "minimum_signers").unwrap();
            let multisig_members =
                pubkeys_of_multiple_signers(arg_matches, "multisig_member", &mut wallet_manager)
                    .unwrap_or_else(print_error_and_exit)
                    .unwrap();
            if minimum_signers as usize > multisig_members.len() {
                eprintln!(
                    "error: MINIMUM_SIGNERS cannot be greater than the number \
                          of MULTISIG_MEMBERs passed"
                );
                exit(1);
            }

            let (signer, _) = get_signer(arg_matches, "address_keypair", &mut wallet_manager)
                .unwrap_or_else(new_throwaway_signer);

            command_create_multisig(config, signer, minimum_signers, multisig_members).await
        }
        (CommandName::Authorize, arg_matches) => {
            let address = pubkey_of_signer(arg_matches, "address", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let authority_type = arg_matches.value_of("authority_type").unwrap();
            let authority_type = CliAuthorityType::from_str(authority_type)?;

            let (authority_signer, authority) =
                config.signer_or_default(arg_matches, "authority", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(authority_signer, &mut bulk_signers);
            }

            let new_authority =
                pubkey_of_signer(arg_matches, "new_authority", &mut wallet_manager).unwrap();
            let force_authorize = arg_matches.is_present("force");
            command_authorize(
                config,
                address,
                authority_type,
                authority,
                new_authority,
                force_authorize,
                bulk_signers,
            )
            .await
        }
        (CommandName::Transfer, arg_matches) => {
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let amount = match arg_matches.value_of("amount").unwrap() {
                "ALL" => None,
                amount => Some(amount.parse::<f64>().unwrap()),
            };
            let recipient = pubkey_of_signer(arg_matches, "recipient", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let sender = pubkey_of_signer(arg_matches, "from", &mut wallet_manager).unwrap();

            let (owner_signer, owner) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);

            let confidential_transfer_args = if arg_matches.is_present("confidential") {
                // Deriving ElGamal and AES key from signer. Custom ElGamal and AES keys will be
                // supported in the future once upgrading to clap-v3.
                //
                // NOTE:: Seed bytes are hardcoded to be empty bytes for now. They will be
                // updated once custom ElGamal and AES keys are supported.
                let sender_elgamal_keypair =
                    ElGamalKeypair::new_from_signer(&*owner_signer, b"").unwrap();
                let sender_aes_key = AeKey::new_from_signer(&*owner_signer, b"").unwrap();

                // Sign-only mode is not yet supported for confidential transfers, so set
                // recipient and auditor ElGamal public to `None` by default.
                Some(ConfidentialTransferArgs {
                    sender_elgamal_keypair,
                    sender_aes_key,
                    recipient_elgamal_pubkey: None,
                    auditor_elgamal_pubkey: None,
                })
            } else {
                None
            };

            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }

            let mint_decimals = value_of::<u8>(arg_matches, MINT_DECIMALS_ARG.name);
            let fund_recipient = arg_matches.is_present("fund_recipient");
            let allow_unfunded_recipient = arg_matches.is_present("allow_empty_recipient")
                || arg_matches.is_present("allow_unfunded_recipient");

            let recipient_is_ata_owner = arg_matches.is_present("recipient_is_ata_owner");
            let no_recipient_is_ata_owner =
                arg_matches.is_present("no_recipient_is_ata_owner") || !recipient_is_ata_owner;
            if recipient_is_ata_owner {
                println_display(config, "recipient-is-ata-owner is now the default behavior. The option has been deprecated and will be removed in a future release.".to_string());
            }
            let use_unchecked_instruction = arg_matches.is_present("use_unchecked_instruction");
            let expected_fee = value_of::<f64>(arg_matches, "expected_fee");
            let memo = value_t!(arg_matches, "memo", String).ok();
            let transfer_hook_accounts = arg_matches.values_of("transfer_hook_account").map(|v| {
                v.into_iter()
                    .map(|s| parse_transfer_hook_account(s).unwrap())
                    .collect::<Vec<_>>()
            });

            command_transfer(
                config,
                token,
                amount,
                recipient,
                sender,
                owner,
                allow_unfunded_recipient,
                fund_recipient,
                mint_decimals,
                no_recipient_is_ata_owner,
                use_unchecked_instruction,
                expected_fee,
                memo,
                bulk_signers,
                arg_matches.is_present("no_wait"),
                arg_matches.is_present("allow_non_system_account_recipient"),
                transfer_hook_accounts,
                confidential_transfer_args.as_ref(),
            )
            .await
        }
        (CommandName::Burn, arg_matches) => {
            let account = pubkey_of_signer(arg_matches, "account", &mut wallet_manager)
                .unwrap()
                .unwrap();

            let (owner_signer, owner) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }

            let amount = value_t_or_exit!(arg_matches, "amount", f64);
            let mint_address =
                pubkey_of_signer(arg_matches, MINT_ADDRESS_ARG.name, &mut wallet_manager).unwrap();
            let mint_decimals = value_of::<u8>(arg_matches, MINT_DECIMALS_ARG.name);
            let use_unchecked_instruction = arg_matches.is_present("use_unchecked_instruction");
            let memo = value_t!(arg_matches, "memo", String).ok();
            command_burn(
                config,
                account,
                owner,
                amount,
                mint_address,
                mint_decimals,
                use_unchecked_instruction,
                memo,
                bulk_signers,
            )
            .await
        }
        (CommandName::Mint, arg_matches) => {
            let (mint_authority_signer, mint_authority) =
                config.signer_or_default(arg_matches, "mint_authority", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(mint_authority_signer, &mut bulk_signers);
            }

            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let amount = value_t_or_exit!(arg_matches, "amount", f64);
            let mint_decimals = value_of::<u8>(arg_matches, MINT_DECIMALS_ARG.name);
            let mint_info = config.get_mint_info(&token, mint_decimals).await?;
            let recipient = if let Some(address) =
                pubkey_of_signer(arg_matches, "recipient", &mut wallet_manager).unwrap()
            {
                address
            } else if let Some(address) =
                pubkey_of_signer(arg_matches, "recipient_owner", &mut wallet_manager).unwrap()
            {
                get_associated_token_address_with_program_id(&address, &token, &config.program_id)
            } else {
                let owner = config.default_signer()?.pubkey();
                config.associated_token_address_for_token_and_program(
                    &mint_info.address,
                    &owner,
                    &mint_info.program_id,
                )?
            };
            config.check_account(&recipient, Some(token)).await?;
            let use_unchecked_instruction = arg_matches.is_present("use_unchecked_instruction");
            let memo = value_t!(arg_matches, "memo", String).ok();
            command_mint(
                config,
                token,
                amount,
                recipient,
                mint_info,
                mint_authority,
                use_unchecked_instruction,
                memo,
                bulk_signers,
            )
            .await
        }
        (CommandName::Freeze, arg_matches) => {
            let (freeze_authority_signer, freeze_authority) =
                config.signer_or_default(arg_matches, "freeze_authority", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(freeze_authority_signer, &mut bulk_signers);
            }

            let account = pubkey_of_signer(arg_matches, "account", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let mint_address =
                pubkey_of_signer(arg_matches, MINT_ADDRESS_ARG.name, &mut wallet_manager).unwrap();
            command_freeze(
                config,
                account,
                mint_address,
                freeze_authority,
                bulk_signers,
            )
            .await
        }
        (CommandName::Thaw, arg_matches) => {
            let (freeze_authority_signer, freeze_authority) =
                config.signer_or_default(arg_matches, "freeze_authority", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(freeze_authority_signer, &mut bulk_signers);
            }

            let account = pubkey_of_signer(arg_matches, "account", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let mint_address =
                pubkey_of_signer(arg_matches, MINT_ADDRESS_ARG.name, &mut wallet_manager).unwrap();
            command_thaw(
                config,
                account,
                mint_address,
                freeze_authority,
                bulk_signers,
            )
            .await
        }
        (CommandName::Wrap, arg_matches) => {
            let amount = value_t_or_exit!(arg_matches, "amount", f64);
            let account = if arg_matches.is_present("create_aux_account") {
                let (signer, account) = new_throwaway_signer();
                bulk_signers.push(signer);
                Some(account)
            } else {
                // No need to add a signer when creating an associated token account
                None
            };

            let (wallet_signer, wallet_address) =
                config.signer_or_default(arg_matches, "wallet_keypair", &mut wallet_manager);
            push_signer_with_dedup(wallet_signer, &mut bulk_signers);

            command_wrap(
                config,
                amount,
                wallet_address,
                account,
                arg_matches.is_present("immutable"),
                bulk_signers,
            )
            .await
        }
        (CommandName::Unwrap, arg_matches) => {
            let (wallet_signer, wallet_address) =
                config.signer_or_default(arg_matches, "wallet_keypair", &mut wallet_manager);
            push_signer_with_dedup(wallet_signer, &mut bulk_signers);

            let account = pubkey_of_signer(arg_matches, "account", &mut wallet_manager).unwrap();
            command_unwrap(config, wallet_address, account, bulk_signers).await
        }
        (CommandName::Approve, arg_matches) => {
            let (owner_signer, owner_address) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }

            let account = pubkey_of_signer(arg_matches, "account", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let amount = value_t_or_exit!(arg_matches, "amount", f64);
            let delegate = pubkey_of_signer(arg_matches, "delegate", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let mint_address =
                pubkey_of_signer(arg_matches, MINT_ADDRESS_ARG.name, &mut wallet_manager).unwrap();
            let mint_decimals = value_of::<u8>(arg_matches, MINT_DECIMALS_ARG.name);
            let use_unchecked_instruction = arg_matches.is_present("use_unchecked_instruction");
            command_approve(
                config,
                account,
                owner_address,
                amount,
                delegate,
                mint_address,
                mint_decimals,
                use_unchecked_instruction,
                bulk_signers,
            )
            .await
        }
        (CommandName::Revoke, arg_matches) => {
            let (owner_signer, owner_address) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }

            let account = pubkey_of_signer(arg_matches, "account", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let delegate_address =
                pubkey_of_signer(arg_matches, DELEGATE_ADDRESS_ARG.name, &mut wallet_manager)
                    .unwrap();
            command_revoke(
                config,
                account,
                owner_address,
                delegate_address,
                bulk_signers,
            )
            .await
        }
        (CommandName::Close, arg_matches) => {
            let (close_authority_signer, close_authority) =
                config.signer_or_default(arg_matches, "close_authority", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(close_authority_signer, &mut bulk_signers);
            }

            let address = config
                .associated_token_address_or_override(arg_matches, "address", &mut wallet_manager)
                .await?;
            let recipient =
                config.pubkey_or_default(arg_matches, "recipient", &mut wallet_manager)?;
            command_close(config, address, close_authority, recipient, bulk_signers).await
        }
        (CommandName::CloseMint, arg_matches) => {
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let (close_authority_signer, close_authority) =
                config.signer_or_default(arg_matches, "close_authority", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(close_authority_signer, &mut bulk_signers);
            }
            let recipient =
                config.pubkey_or_default(arg_matches, "recipient", &mut wallet_manager)?;

            command_close_mint(config, token, close_authority, recipient, bulk_signers).await
        }
        (CommandName::Balance, arg_matches) => {
            let address = config
                .associated_token_address_or_override(arg_matches, "address", &mut wallet_manager)
                .await?;
            command_balance(config, address).await
        }
        (CommandName::Supply, arg_matches) => {
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            command_supply(config, token).await
        }
        (CommandName::Accounts, arg_matches) => {
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager).unwrap();
            let owner = config.pubkey_or_default(arg_matches, "owner", &mut wallet_manager)?;
            let filter = if arg_matches.is_present("delegated") {
                AccountFilter::Delegated
            } else if arg_matches.is_present("externally_closeable") {
                AccountFilter::ExternallyCloseable
            } else {
                AccountFilter::All
            };

            command_accounts(
                config,
                token,
                owner,
                filter,
                arg_matches.is_present("addresses_only"),
            )
            .await
        }
        (CommandName::Address, arg_matches) => {
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager).unwrap();
            let owner = config.pubkey_or_default(arg_matches, "owner", &mut wallet_manager)?;
            command_address(config, token, owner).await
        }
        (CommandName::AccountInfo, arg_matches) => {
            let address = config
                .associated_token_address_or_override(arg_matches, "address", &mut wallet_manager)
                .await?;
            command_display(config, address).await
        }
        (CommandName::MultisigInfo, arg_matches) => {
            let address = pubkey_of_signer(arg_matches, "address", &mut wallet_manager)
                .unwrap()
                .unwrap();
            command_display(config, address).await
        }
        (CommandName::Display, arg_matches) => {
            let address = pubkey_of_signer(arg_matches, "address", &mut wallet_manager)
                .unwrap()
                .unwrap();
            command_display(config, address).await
        }
        (CommandName::Gc, arg_matches) => {
            match config.output_format {
                OutputFormat::Json | OutputFormat::JsonCompact => {
                    eprintln!(
                        "`spl-token gc` does not support the `--ouput` parameter at this time"
                    );
                    exit(1);
                }
                _ => {}
            }

            let close_empty_associated_accounts =
                arg_matches.is_present("close_empty_associated_accounts");

            let (owner_signer, owner_address) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }

            command_gc(
                config,
                owner_address,
                close_empty_associated_accounts,
                bulk_signers,
            )
            .await
        }
        (CommandName::SyncNative, arg_matches) => {
            let native_mint = *native_token_client_from_config(config)?.get_address();
            let address = config
                .associated_token_address_for_token_or_override(
                    arg_matches,
                    "address",
                    &mut wallet_manager,
                    Some(native_mint),
                )
                .await;
            command_sync_native(config, address?).await
        }
        (CommandName::EnableRequiredTransferMemos, arg_matches) => {
            let (owner_signer, owner) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }
            // Since account is required argument it will always be present
            let token_account =
                config.pubkey_or_default(arg_matches, "account", &mut wallet_manager)?;
            command_required_transfer_memos(config, token_account, owner, bulk_signers, true).await
        }
        (CommandName::DisableRequiredTransferMemos, arg_matches) => {
            let (owner_signer, owner) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }
            // Since account is required argument it will always be present
            let token_account =
                config.pubkey_or_default(arg_matches, "account", &mut wallet_manager)?;
            command_required_transfer_memos(config, token_account, owner, bulk_signers, false).await
        }
        (CommandName::EnableCpiGuard, arg_matches) => {
            let (owner_signer, owner) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }
            // Since account is required argument it will always be present
            let token_account =
                config.pubkey_or_default(arg_matches, "account", &mut wallet_manager)?;
            command_cpi_guard(config, token_account, owner, bulk_signers, true).await
        }
        (CommandName::DisableCpiGuard, arg_matches) => {
            let (owner_signer, owner) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }
            // Since account is required argument it will always be present
            let token_account =
                config.pubkey_or_default(arg_matches, "account", &mut wallet_manager)?;
            command_cpi_guard(config, token_account, owner, bulk_signers, false).await
        }
        (CommandName::UpdateDefaultAccountState, arg_matches) => {
            // Since account is required argument it will always be present
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let (freeze_authority_signer, freeze_authority) =
                config.signer_or_default(arg_matches, "freeze_authority", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(freeze_authority_signer, &mut bulk_signers);
            }
            let new_default_state = arg_matches.value_of("state").unwrap();
            let new_default_state = match new_default_state {
                "initialized" => AccountState::Initialized,
                "frozen" => AccountState::Frozen,
                _ => unreachable!(),
            };
            command_update_default_account_state(
                config,
                token,
                freeze_authority,
                new_default_state,
                bulk_signers,
            )
            .await
        }
        (CommandName::UpdateMetadataAddress, arg_matches) => {
            // Since account is required argument it will always be present
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();

            let (authority_signer, authority) =
                config.signer_or_default(arg_matches, "authority", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(authority_signer, &mut bulk_signers);
            }
            let metadata_address = value_t!(arg_matches, "metadata_address", Pubkey).ok();

            command_update_metadata_pointer_address(
                config,
                token,
                authority,
                metadata_address,
                bulk_signers,
            )
            .await
        }
        (CommandName::WithdrawWithheldTokens, arg_matches) => {
            let (authority_signer, authority) = config.signer_or_default(
                arg_matches,
                "withdraw_withheld_authority",
                &mut wallet_manager,
            );
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(authority_signer, &mut bulk_signers);
            }
            // Since destination is required it will always be present
            let destination_token_account =
                pubkey_of_signer(arg_matches, "account", &mut wallet_manager)
                    .unwrap()
                    .unwrap();
            let include_mint = arg_matches.is_present("include_mint");
            let source_accounts = arg_matches
                .values_of("source")
                .unwrap_or_default()
                .map(|s| Pubkey::from_str(s).unwrap_or_else(print_error_and_exit))
                .collect::<Vec<_>>();
            command_withdraw_withheld_tokens(
                config,
                destination_token_account,
                source_accounts,
                authority,
                include_mint,
                bulk_signers,
            )
            .await
        }
        (CommandName::SetTransferFee, arg_matches) => {
            let token_pubkey = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let transfer_fee_basis_points =
                value_t_or_exit!(arg_matches, "transfer_fee_basis_points", u16);
            let maximum_fee = value_t_or_exit!(arg_matches, "maximum_fee", f64);
            let (transfer_fee_authority_signer, transfer_fee_authority_pubkey) = config
                .signer_or_default(arg_matches, "transfer_fee_authority", &mut wallet_manager);
            let mint_decimals = value_of::<u8>(arg_matches, MINT_DECIMALS_ARG.name);
            let bulk_signers = vec![transfer_fee_authority_signer];

            command_set_transfer_fee(
                config,
                token_pubkey,
                transfer_fee_authority_pubkey,
                transfer_fee_basis_points,
                maximum_fee,
                mint_decimals,
                bulk_signers,
            )
            .await
        }
        (CommandName::WithdrawExcessLamports, arg_matches) => {
            let (signer, authority) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);
            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(signer, &mut bulk_signers);
            }

            let source = config.pubkey_or_default(arg_matches, "from", &mut wallet_manager)?;
            let destination =
                config.pubkey_or_default(arg_matches, "recipient", &mut wallet_manager)?;

            command_withdraw_excess_lamports(config, source, destination, authority, bulk_signers)
                .await
        }
        (CommandName::UpdateConfidentialTransferSettings, arg_matches) => {
            let token_pubkey = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();

            let auto_approve = arg_matches.value_of("approve_policy").map(|b| b == "auto");

            let auditor_encryption_pubkey = if arg_matches.is_present("auditor_pubkey") {
                Some(elgamal_pubkey_or_none(arg_matches, "auditor_pubkey")?)
            } else {
                None
            };

            let (authority_signer, authority_pubkey) = config.signer_or_default(
                arg_matches,
                "confidential_transfer_authority",
                &mut wallet_manager,
            );
            let bulk_signers = vec![authority_signer];

            command_update_confidential_transfer_settings(
                config,
                token_pubkey,
                authority_pubkey,
                auto_approve,
                auditor_encryption_pubkey,
                bulk_signers,
            )
            .await
        }
        (CommandName::ConfigureConfidentialTransferAccount, arg_matches) => {
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager).unwrap();

            let (owner_signer, owner) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);

            let account = pubkey_of_signer(arg_matches, "address", &mut wallet_manager).unwrap();

            // Deriving ElGamal and AES key from signer. Custom ElGamal and AES keys will be
            // supported in the future once upgrading to clap-v3.
            //
            // NOTE:: Seed bytes are hardcoded to be empty bytes for now. They will be
            // updated once custom ElGamal and AES keys are supported.
            let elgamal_keypair = ElGamalKeypair::new_from_signer(&*owner_signer, b"").unwrap();
            let aes_key = AeKey::new_from_signer(&*owner_signer, b"").unwrap();

            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }

            let maximum_credit_counter =
                if arg_matches.is_present("maximum_pending_balance_credit_counter") {
                    let maximum_credit_counter = value_t_or_exit!(
                        arg_matches.value_of("maximum_pending_balance_credit_counter"),
                        u64
                    );
                    Some(maximum_credit_counter)
                } else {
                    None
                };

            command_configure_confidential_transfer_account(
                config,
                token,
                owner,
                account,
                maximum_credit_counter,
                &elgamal_keypair,
                &aes_key,
                bulk_signers,
            )
            .await
        }
        (c @ CommandName::EnableConfidentialCredits, arg_matches)
        | (c @ CommandName::DisableConfidentialCredits, arg_matches)
        | (c @ CommandName::EnableNonConfidentialCredits, arg_matches)
        | (c @ CommandName::DisableNonConfidentialCredits, arg_matches) => {
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager).unwrap();

            let (owner_signer, owner) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);

            let account = pubkey_of_signer(arg_matches, "address", &mut wallet_manager).unwrap();

            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }

            let (allow_confidential_credits, allow_non_confidential_credits) = match c {
                CommandName::EnableConfidentialCredits => (Some(true), None),
                CommandName::DisableConfidentialCredits => (Some(false), None),
                CommandName::EnableNonConfidentialCredits => (None, Some(true)),
                CommandName::DisableNonConfidentialCredits => (None, Some(false)),
                _ => (None, None),
            };

            command_enable_disable_confidential_transfers(
                config,
                token,
                owner,
                account,
                bulk_signers,
                allow_confidential_credits,
                allow_non_confidential_credits,
            )
            .await
        }
        (c @ CommandName::DepositConfidentialTokens, arg_matches)
        | (c @ CommandName::WithdrawConfidentialTokens, arg_matches) => {
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager)
                .unwrap()
                .unwrap();
            let amount = match arg_matches.value_of("amount").unwrap() {
                "ALL" => None,
                amount => Some(amount.parse::<f64>().unwrap()),
            };
            let account = pubkey_of_signer(arg_matches, "address", &mut wallet_manager).unwrap();

            let (owner_signer, owner) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);

            let mint_decimals = value_of::<u8>(arg_matches, MINT_DECIMALS_ARG.name);

            let (instruction_type, elgamal_keypair, aes_key) = match c {
                CommandName::DepositConfidentialTokens => {
                    (ConfidentialInstructionType::Deposit, None, None)
                }
                CommandName::WithdrawConfidentialTokens => {
                    // Deriving ElGamal and AES key from signer. Custom ElGamal and AES keys will be
                    // supported in the future once upgrading to clap-v3.
                    //
                    // NOTE:: Seed bytes are hardcoded to be empty bytes for now. They will be
                    // updated once custom ElGamal and AES keys are supported.
                    let elgamal_keypair =
                        ElGamalKeypair::new_from_signer(&*owner_signer, b"").unwrap();
                    let aes_key = AeKey::new_from_signer(&*owner_signer, b"").unwrap();

                    (
                        ConfidentialInstructionType::Withdraw,
                        Some(elgamal_keypair),
                        Some(aes_key),
                    )
                }
                _ => panic!("Instruction not supported"),
            };

            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }

            command_deposit_withdraw_confidential_tokens(
                config,
                token,
                owner,
                account,
                bulk_signers,
                amount,
                mint_decimals,
                instruction_type,
                elgamal_keypair.as_ref(),
                aes_key.as_ref(),
            )
            .await
        }
        (CommandName::ApplyPendingBalance, arg_matches) => {
            let token = pubkey_of_signer(arg_matches, "token", &mut wallet_manager).unwrap();

            let (owner_signer, owner) =
                config.signer_or_default(arg_matches, "owner", &mut wallet_manager);

            let account = pubkey_of_signer(arg_matches, "address", &mut wallet_manager).unwrap();

            // Deriving ElGamal and AES key from signer. Custom ElGamal and AES keys will be
            // supported in the future once upgrading to clap-v3.
            //
            // NOTE:: Seed bytes are hardcoded to be empty bytes for now. They will be
            // updated once custom ElGamal and AES keys are supported.
            let elgamal_keypair = ElGamalKeypair::new_from_signer(&*owner_signer, b"").unwrap();
            let aes_key = AeKey::new_from_signer(&*owner_signer, b"").unwrap();

            if config.multisigner_pubkeys.is_empty() {
                push_signer_with_dedup(owner_signer, &mut bulk_signers);
            }

            command_apply_pending_balance(
                config,
                token,
                owner,
                account,
                bulk_signers,
                &elgamal_keypair,
                &aes_key,
            )
            .await
        }
    }
}

fn format_output<T>(command_output: T, command_name: &CommandName, config: &Config) -> String
where
    T: Serialize + Display + QuietDisplay + VerboseDisplay,
{
    config.output_format.formatted_string(&CommandOutput {
        command_name: command_name.to_string(),
        command_output,
    })
}
enum TransactionReturnData {
    CliSignature(CliSignature),
    CliSignOnlyData(CliSignOnlyData),
}

async fn finish_tx<'a>(
    config: &Config<'a>,
    rpc_response: &RpcClientResponse,
    no_wait: bool,
) -> Result<TransactionReturnData, Error> {
    match rpc_response {
        RpcClientResponse::Transaction(transaction) => {
            Ok(TransactionReturnData::CliSignOnlyData(return_signers_data(
                transaction,
                &ReturnSignersConfig {
                    dump_transaction_message: config.dump_transaction_message,
                },
            )))
        }
        RpcClientResponse::Signature(signature) if no_wait => {
            Ok(TransactionReturnData::CliSignature(CliSignature {
                signature: signature.to_string(),
            }))
        }
        RpcClientResponse::Signature(signature) => {
            let blockhash = config.program_client.get_latest_blockhash().await?;
            config
                .rpc_client
                .confirm_transaction_with_spinner(
                    signature,
                    &blockhash,
                    config.rpc_client.commitment(),
                )
                .await?;

            Ok(TransactionReturnData::CliSignature(CliSignature {
                signature: signature.to_string(),
            }))
        }
        RpcClientResponse::Simulation(_) => {
            // Implement this once the CLI supports dry-running / simulation
            unreachable!()
        }
    }
}